viewer.js 4.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860
  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("Viewer3D", [], factory);
  6. else if(typeof exports === 'object')
  7. exports["Viewer3D"] = factory();
  8. else
  9. root["Viewer3D"] = 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 = 5);
  74. /******/ })
  75. /************************************************************************/
  76. /******/ ([
  77. /* 0 */
  78. /***/ (function(module, exports, __webpack_require__) {
  79. 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. var BABYLON;
  96. (function (BABYLON) {
  97. var KeyboardEventTypes = (function () {
  98. function KeyboardEventTypes() {
  99. }
  100. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  101. get: function () {
  102. return KeyboardEventTypes._KEYDOWN;
  103. },
  104. enumerable: true,
  105. configurable: true
  106. });
  107. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  108. get: function () {
  109. return KeyboardEventTypes._KEYUP;
  110. },
  111. enumerable: true,
  112. configurable: true
  113. });
  114. KeyboardEventTypes._KEYDOWN = 0x01;
  115. KeyboardEventTypes._KEYUP = 0x02;
  116. return KeyboardEventTypes;
  117. }());
  118. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  119. var KeyboardInfo = (function () {
  120. function KeyboardInfo(type, event) {
  121. this.type = type;
  122. this.event = event;
  123. }
  124. return KeyboardInfo;
  125. }());
  126. BABYLON.KeyboardInfo = KeyboardInfo;
  127. /**
  128. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  129. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  130. */
  131. var KeyboardInfoPre = (function (_super) {
  132. __extends(KeyboardInfoPre, _super);
  133. function KeyboardInfoPre(type, event) {
  134. var _this = _super.call(this, type, event) || this;
  135. _this.skipOnPointerObservable = false;
  136. return _this;
  137. }
  138. return KeyboardInfoPre;
  139. }(KeyboardInfo));
  140. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  141. })(BABYLON || (BABYLON = {}));
  142. //# sourceMappingURL=babylon.keyboardEvents.js.map
  143. var BABYLON;
  144. (function (BABYLON) {
  145. var PointerEventTypes = (function () {
  146. function PointerEventTypes() {
  147. }
  148. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  149. get: function () {
  150. return PointerEventTypes._POINTERDOWN;
  151. },
  152. enumerable: true,
  153. configurable: true
  154. });
  155. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  156. get: function () {
  157. return PointerEventTypes._POINTERUP;
  158. },
  159. enumerable: true,
  160. configurable: true
  161. });
  162. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  163. get: function () {
  164. return PointerEventTypes._POINTERMOVE;
  165. },
  166. enumerable: true,
  167. configurable: true
  168. });
  169. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  170. get: function () {
  171. return PointerEventTypes._POINTERWHEEL;
  172. },
  173. enumerable: true,
  174. configurable: true
  175. });
  176. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  177. get: function () {
  178. return PointerEventTypes._POINTERPICK;
  179. },
  180. enumerable: true,
  181. configurable: true
  182. });
  183. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  184. get: function () {
  185. return PointerEventTypes._POINTERTAP;
  186. },
  187. enumerable: true,
  188. configurable: true
  189. });
  190. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  191. get: function () {
  192. return PointerEventTypes._POINTERDOUBLETAP;
  193. },
  194. enumerable: true,
  195. configurable: true
  196. });
  197. PointerEventTypes._POINTERDOWN = 0x01;
  198. PointerEventTypes._POINTERUP = 0x02;
  199. PointerEventTypes._POINTERMOVE = 0x04;
  200. PointerEventTypes._POINTERWHEEL = 0x08;
  201. PointerEventTypes._POINTERPICK = 0x10;
  202. PointerEventTypes._POINTERTAP = 0x20;
  203. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  204. return PointerEventTypes;
  205. }());
  206. BABYLON.PointerEventTypes = PointerEventTypes;
  207. var PointerInfoBase = (function () {
  208. function PointerInfoBase(type, event) {
  209. this.type = type;
  210. this.event = event;
  211. }
  212. return PointerInfoBase;
  213. }());
  214. BABYLON.PointerInfoBase = PointerInfoBase;
  215. /**
  216. * This class is used to store pointer related info for the onPrePointerObservable event.
  217. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  218. */
  219. var PointerInfoPre = (function (_super) {
  220. __extends(PointerInfoPre, _super);
  221. function PointerInfoPre(type, event, localX, localY) {
  222. var _this = _super.call(this, type, event) || this;
  223. _this.skipOnPointerObservable = false;
  224. _this.localPosition = new BABYLON.Vector2(localX, localY);
  225. return _this;
  226. }
  227. return PointerInfoPre;
  228. }(PointerInfoBase));
  229. BABYLON.PointerInfoPre = PointerInfoPre;
  230. /**
  231. * This type contains all the data related to a pointer event in Babylon.js.
  232. * 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.
  233. */
  234. var PointerInfo = (function (_super) {
  235. __extends(PointerInfo, _super);
  236. function PointerInfo(type, event, pickInfo) {
  237. var _this = _super.call(this, type, event) || this;
  238. _this.pickInfo = pickInfo;
  239. return _this;
  240. }
  241. return PointerInfo;
  242. }(PointerInfoBase));
  243. BABYLON.PointerInfo = PointerInfo;
  244. })(BABYLON || (BABYLON = {}));
  245. //# sourceMappingURL=babylon.pointerEvents.js.map
  246. var BABYLON;
  247. (function (BABYLON) {
  248. BABYLON.ToGammaSpace = 1 / 2.2;
  249. BABYLON.ToLinearSpace = 2.2;
  250. BABYLON.Epsilon = 0.001;
  251. var Color3 = (function () {
  252. /**
  253. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  254. */
  255. function Color3(r, g, b) {
  256. if (r === void 0) { r = 0; }
  257. if (g === void 0) { g = 0; }
  258. if (b === void 0) { b = 0; }
  259. this.r = r;
  260. this.g = g;
  261. this.b = b;
  262. }
  263. /**
  264. * Returns a string with the Color3 current values.
  265. */
  266. Color3.prototype.toString = function () {
  267. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  268. };
  269. /**
  270. * Returns the string "Color3".
  271. */
  272. Color3.prototype.getClassName = function () {
  273. return "Color3";
  274. };
  275. /**
  276. * Returns the Color3 hash code.
  277. */
  278. Color3.prototype.getHashCode = function () {
  279. var hash = this.r || 0;
  280. hash = (hash * 397) ^ (this.g || 0);
  281. hash = (hash * 397) ^ (this.b || 0);
  282. return hash;
  283. };
  284. // Operators
  285. /**
  286. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  287. * Returns the Color3.
  288. */
  289. Color3.prototype.toArray = function (array, index) {
  290. if (index === undefined) {
  291. index = 0;
  292. }
  293. array[index] = this.r;
  294. array[index + 1] = this.g;
  295. array[index + 2] = this.b;
  296. return this;
  297. };
  298. /**
  299. * Returns a new Color4 object from the current Color3 and the passed alpha.
  300. */
  301. Color3.prototype.toColor4 = function (alpha) {
  302. if (alpha === void 0) { alpha = 1; }
  303. return new Color4(this.r, this.g, this.b, alpha);
  304. };
  305. /**
  306. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  307. */
  308. Color3.prototype.asArray = function () {
  309. var result = new Array();
  310. this.toArray(result, 0);
  311. return result;
  312. };
  313. /**
  314. * Returns the luminance value (float).
  315. */
  316. Color3.prototype.toLuminance = function () {
  317. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  318. };
  319. /**
  320. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  321. * Returns this new object.
  322. */
  323. Color3.prototype.multiply = function (otherColor) {
  324. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  325. };
  326. /**
  327. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  328. * Returns the current Color3.
  329. */
  330. Color3.prototype.multiplyToRef = function (otherColor, result) {
  331. result.r = this.r * otherColor.r;
  332. result.g = this.g * otherColor.g;
  333. result.b = this.b * otherColor.b;
  334. return this;
  335. };
  336. /**
  337. * Boolean : True if the rgb values are equal to the passed ones.
  338. */
  339. Color3.prototype.equals = function (otherColor) {
  340. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  341. };
  342. /**
  343. * Boolean : True if the rgb values are equal to the passed ones.
  344. */
  345. Color3.prototype.equalsFloats = function (r, g, b) {
  346. return this.r === r && this.g === g && this.b === b;
  347. };
  348. /**
  349. * Multiplies in place each rgb value by scale.
  350. * Returns the updated Color3.
  351. */
  352. Color3.prototype.scale = function (scale) {
  353. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  354. };
  355. /**
  356. * Multiplies the rgb values by scale and stores the result into "result".
  357. * Returns the unmodified current Color3.
  358. */
  359. Color3.prototype.scaleToRef = function (scale, result) {
  360. result.r = this.r * scale;
  361. result.g = this.g * scale;
  362. result.b = this.b * scale;
  363. return this;
  364. };
  365. /**
  366. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  367. */
  368. Color3.prototype.add = function (otherColor) {
  369. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  370. };
  371. /**
  372. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  373. * Returns the unmodified current Color3.
  374. */
  375. Color3.prototype.addToRef = function (otherColor, result) {
  376. result.r = this.r + otherColor.r;
  377. result.g = this.g + otherColor.g;
  378. result.b = this.b + otherColor.b;
  379. return this;
  380. };
  381. /**
  382. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  383. */
  384. Color3.prototype.subtract = function (otherColor) {
  385. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  386. };
  387. /**
  388. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  389. * Returns the unmodified current Color3.
  390. */
  391. Color3.prototype.subtractToRef = function (otherColor, result) {
  392. result.r = this.r - otherColor.r;
  393. result.g = this.g - otherColor.g;
  394. result.b = this.b - otherColor.b;
  395. return this;
  396. };
  397. /**
  398. * Returns a new Color3 copied the current one.
  399. */
  400. Color3.prototype.clone = function () {
  401. return new Color3(this.r, this.g, this.b);
  402. };
  403. /**
  404. * Copies the rgb values from the source in the current Color3.
  405. * Returns the updated Color3.
  406. */
  407. Color3.prototype.copyFrom = function (source) {
  408. this.r = source.r;
  409. this.g = source.g;
  410. this.b = source.b;
  411. return this;
  412. };
  413. /**
  414. * Updates the Color3 rgb values from the passed floats.
  415. * Returns the Color3.
  416. */
  417. Color3.prototype.copyFromFloats = function (r, g, b) {
  418. this.r = r;
  419. this.g = g;
  420. this.b = b;
  421. return this;
  422. };
  423. /**
  424. * Updates the Color3 rgb values from the passed floats.
  425. * Returns the Color3.
  426. */
  427. Color3.prototype.set = function (r, g, b) {
  428. return this.copyFromFloats(r, g, b);
  429. };
  430. /**
  431. * Returns the Color3 hexadecimal code as a string.
  432. */
  433. Color3.prototype.toHexString = function () {
  434. var intR = (this.r * 255) | 0;
  435. var intG = (this.g * 255) | 0;
  436. var intB = (this.b * 255) | 0;
  437. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  438. };
  439. /**
  440. * Returns a new Color3 converted to linear space.
  441. */
  442. Color3.prototype.toLinearSpace = function () {
  443. var convertedColor = new Color3();
  444. this.toLinearSpaceToRef(convertedColor);
  445. return convertedColor;
  446. };
  447. /**
  448. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  449. * Returns the unmodified Color3.
  450. */
  451. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  452. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  453. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  454. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  455. return this;
  456. };
  457. /**
  458. * Returns a new Color3 converted to gamma space.
  459. */
  460. Color3.prototype.toGammaSpace = function () {
  461. var convertedColor = new Color3();
  462. this.toGammaSpaceToRef(convertedColor);
  463. return convertedColor;
  464. };
  465. /**
  466. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  467. * Returns the unmodified Color3.
  468. */
  469. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  470. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  471. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  472. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  473. return this;
  474. };
  475. // Statics
  476. /**
  477. * Creates a new Color3 from the string containing valid hexadecimal values.
  478. */
  479. Color3.FromHexString = function (hex) {
  480. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  481. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  482. return new Color3(0, 0, 0);
  483. }
  484. var r = parseInt(hex.substring(1, 3), 16);
  485. var g = parseInt(hex.substring(3, 5), 16);
  486. var b = parseInt(hex.substring(5, 7), 16);
  487. return Color3.FromInts(r, g, b);
  488. };
  489. /**
  490. * Creates a new Vector3 from the startind index of the passed array.
  491. */
  492. Color3.FromArray = function (array, offset) {
  493. if (offset === void 0) { offset = 0; }
  494. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  495. };
  496. /**
  497. * Creates a new Color3 from integer values ( < 256).
  498. */
  499. Color3.FromInts = function (r, g, b) {
  500. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  501. };
  502. /**
  503. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  504. */
  505. Color3.Lerp = function (start, end, amount) {
  506. var r = start.r + ((end.r - start.r) * amount);
  507. var g = start.g + ((end.g - start.g) * amount);
  508. var b = start.b + ((end.b - start.b) * amount);
  509. return new Color3(r, g, b);
  510. };
  511. Color3.Red = function () { return new Color3(1, 0, 0); };
  512. Color3.Green = function () { return new Color3(0, 1, 0); };
  513. Color3.Blue = function () { return new Color3(0, 0, 1); };
  514. Color3.Black = function () { return new Color3(0, 0, 0); };
  515. Color3.White = function () { return new Color3(1, 1, 1); };
  516. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  517. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  518. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  519. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  520. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  521. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  522. return Color3;
  523. }());
  524. BABYLON.Color3 = Color3;
  525. var Color4 = (function () {
  526. /**
  527. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  528. */
  529. function Color4(r, g, b, a) {
  530. if (r === void 0) { r = 0; }
  531. if (g === void 0) { g = 0; }
  532. if (b === void 0) { b = 0; }
  533. if (a === void 0) { a = 1; }
  534. this.r = r;
  535. this.g = g;
  536. this.b = b;
  537. this.a = a;
  538. }
  539. // Operators
  540. /**
  541. * Adds in place the passed Color4 values to the current Color4.
  542. * Returns the updated Color4.
  543. */
  544. Color4.prototype.addInPlace = function (right) {
  545. this.r += right.r;
  546. this.g += right.g;
  547. this.b += right.b;
  548. this.a += right.a;
  549. return this;
  550. };
  551. /**
  552. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  553. */
  554. Color4.prototype.asArray = function () {
  555. var result = new Array();
  556. this.toArray(result, 0);
  557. return result;
  558. };
  559. /**
  560. * Stores from the starting index in the passed array the Color4 successive values.
  561. * Returns the Color4.
  562. */
  563. Color4.prototype.toArray = function (array, index) {
  564. if (index === undefined) {
  565. index = 0;
  566. }
  567. array[index] = this.r;
  568. array[index + 1] = this.g;
  569. array[index + 2] = this.b;
  570. array[index + 3] = this.a;
  571. return this;
  572. };
  573. /**
  574. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  575. */
  576. Color4.prototype.add = function (right) {
  577. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  578. };
  579. /**
  580. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  581. */
  582. Color4.prototype.subtract = function (right) {
  583. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  584. };
  585. /**
  586. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  587. * Returns the Color4.
  588. */
  589. Color4.prototype.subtractToRef = function (right, result) {
  590. result.r = this.r - right.r;
  591. result.g = this.g - right.g;
  592. result.b = this.b - right.b;
  593. result.a = this.a - right.a;
  594. return this;
  595. };
  596. /**
  597. * Creates a new Color4 with the current Color4 values multiplied by scale.
  598. */
  599. Color4.prototype.scale = function (scale) {
  600. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  601. };
  602. /**
  603. * Multiplies the current Color4 values by scale and stores the result in "result".
  604. * Returns the Color4.
  605. */
  606. Color4.prototype.scaleToRef = function (scale, result) {
  607. result.r = this.r * scale;
  608. result.g = this.g * scale;
  609. result.b = this.b * scale;
  610. result.a = this.a * scale;
  611. return this;
  612. };
  613. /**
  614. * Multipy an RGBA Color4 value by another and return a new Color4 object
  615. * @param color The Color4 (RGBA) value to multiply by
  616. * @returns A new Color4.
  617. */
  618. Color4.prototype.multiply = function (color) {
  619. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  620. };
  621. /**
  622. * Multipy an RGBA Color4 value by another and push the result in a reference value
  623. * @param color The Color4 (RGBA) value to multiply by
  624. * @param result The Color4 (RGBA) to fill the result in
  625. * @returns the result Color4.
  626. */
  627. Color4.prototype.multiplyToRef = function (color, result) {
  628. result.r = this.r * color.r;
  629. result.g = this.g * color.g;
  630. result.b = this.b * color.b;
  631. result.a = this.a * color.a;
  632. return result;
  633. };
  634. /**
  635. * Returns a string with the Color4 values.
  636. */
  637. Color4.prototype.toString = function () {
  638. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  639. };
  640. /**
  641. * Returns the string "Color4"
  642. */
  643. Color4.prototype.getClassName = function () {
  644. return "Color4";
  645. };
  646. /**
  647. * Return the Color4 hash code as a number.
  648. */
  649. Color4.prototype.getHashCode = function () {
  650. var hash = this.r || 0;
  651. hash = (hash * 397) ^ (this.g || 0);
  652. hash = (hash * 397) ^ (this.b || 0);
  653. hash = (hash * 397) ^ (this.a || 0);
  654. return hash;
  655. };
  656. /**
  657. * Creates a new Color4 copied from the current one.
  658. */
  659. Color4.prototype.clone = function () {
  660. return new Color4(this.r, this.g, this.b, this.a);
  661. };
  662. /**
  663. * Copies the passed Color4 values into the current one.
  664. * Returns the updated Color4.
  665. */
  666. Color4.prototype.copyFrom = function (source) {
  667. this.r = source.r;
  668. this.g = source.g;
  669. this.b = source.b;
  670. this.a = source.a;
  671. return this;
  672. };
  673. /**
  674. * Copies the passed float values into the current one.
  675. * Returns the updated Color4.
  676. */
  677. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  678. this.r = r;
  679. this.g = g;
  680. this.b = b;
  681. this.a = a;
  682. return this;
  683. };
  684. /**
  685. * Copies the passed float values into the current one.
  686. * Returns the updated Color4.
  687. */
  688. Color4.prototype.set = function (r, g, b, a) {
  689. return this.copyFromFloats(r, g, b, a);
  690. };
  691. /**
  692. * Returns a string containing the hexadecimal Color4 code.
  693. */
  694. Color4.prototype.toHexString = function () {
  695. var intR = (this.r * 255) | 0;
  696. var intG = (this.g * 255) | 0;
  697. var intB = (this.b * 255) | 0;
  698. var intA = (this.a * 255) | 0;
  699. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  700. };
  701. /**
  702. * Returns a new Color4 converted to linear space.
  703. */
  704. Color4.prototype.toLinearSpace = function () {
  705. var convertedColor = new Color4();
  706. this.toLinearSpaceToRef(convertedColor);
  707. return convertedColor;
  708. };
  709. /**
  710. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  711. * Returns the unmodified Color4.
  712. */
  713. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  714. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  715. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  716. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  717. convertedColor.a = this.a;
  718. return this;
  719. };
  720. /**
  721. * Returns a new Color4 converted to gamma space.
  722. */
  723. Color4.prototype.toGammaSpace = function () {
  724. var convertedColor = new Color4();
  725. this.toGammaSpaceToRef(convertedColor);
  726. return convertedColor;
  727. };
  728. /**
  729. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  730. * Returns the unmodified Color4.
  731. */
  732. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  733. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  734. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  735. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  736. convertedColor.a = this.a;
  737. return this;
  738. };
  739. // Statics
  740. /**
  741. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  742. */
  743. Color4.FromHexString = function (hex) {
  744. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  745. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  746. return new Color4(0.0, 0.0, 0.0, 0.0);
  747. }
  748. var r = parseInt(hex.substring(1, 3), 16);
  749. var g = parseInt(hex.substring(3, 5), 16);
  750. var b = parseInt(hex.substring(5, 7), 16);
  751. var a = parseInt(hex.substring(7, 9), 16);
  752. return Color4.FromInts(r, g, b, a);
  753. };
  754. /**
  755. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  756. */
  757. Color4.Lerp = function (left, right, amount) {
  758. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  759. Color4.LerpToRef(left, right, amount, result);
  760. return result;
  761. };
  762. /**
  763. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  764. */
  765. Color4.LerpToRef = function (left, right, amount, result) {
  766. result.r = left.r + (right.r - left.r) * amount;
  767. result.g = left.g + (right.g - left.g) * amount;
  768. result.b = left.b + (right.b - left.b) * amount;
  769. result.a = left.a + (right.a - left.a) * amount;
  770. };
  771. /**
  772. * Creates a new Color4 from the starting index element of the passed array.
  773. */
  774. Color4.FromArray = function (array, offset) {
  775. if (offset === void 0) { offset = 0; }
  776. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  777. };
  778. /**
  779. * Creates a new Color4 from the passed integers ( < 256 ).
  780. */
  781. Color4.FromInts = function (r, g, b, a) {
  782. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  783. };
  784. Color4.CheckColors4 = function (colors, count) {
  785. // Check if color3 was used
  786. if (colors.length === count * 3) {
  787. var colors4 = [];
  788. for (var index = 0; index < colors.length; index += 3) {
  789. var newIndex = (index / 3) * 4;
  790. colors4[newIndex] = colors[index];
  791. colors4[newIndex + 1] = colors[index + 1];
  792. colors4[newIndex + 2] = colors[index + 2];
  793. colors4[newIndex + 3] = 1.0;
  794. }
  795. return colors4;
  796. }
  797. return colors;
  798. };
  799. return Color4;
  800. }());
  801. BABYLON.Color4 = Color4;
  802. var Vector2 = (function () {
  803. /**
  804. * Creates a new Vector2 from the passed x and y coordinates.
  805. */
  806. function Vector2(x, y) {
  807. this.x = x;
  808. this.y = y;
  809. }
  810. /**
  811. * Returns a string with the Vector2 coordinates.
  812. */
  813. Vector2.prototype.toString = function () {
  814. return "{X: " + this.x + " Y:" + this.y + "}";
  815. };
  816. /**
  817. * Returns the string "Vector2"
  818. */
  819. Vector2.prototype.getClassName = function () {
  820. return "Vector2";
  821. };
  822. /**
  823. * Returns the Vector2 hash code as a number.
  824. */
  825. Vector2.prototype.getHashCode = function () {
  826. var hash = this.x || 0;
  827. hash = (hash * 397) ^ (this.y || 0);
  828. return hash;
  829. };
  830. // Operators
  831. /**
  832. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  833. * Returns the Vector2.
  834. */
  835. Vector2.prototype.toArray = function (array, index) {
  836. if (index === void 0) { index = 0; }
  837. array[index] = this.x;
  838. array[index + 1] = this.y;
  839. return this;
  840. };
  841. /**
  842. * Returns a new array with 2 elements : the Vector2 coordinates.
  843. */
  844. Vector2.prototype.asArray = function () {
  845. var result = new Array();
  846. this.toArray(result, 0);
  847. return result;
  848. };
  849. /**
  850. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  851. * Returns the updated Vector2.
  852. */
  853. Vector2.prototype.copyFrom = function (source) {
  854. this.x = source.x;
  855. this.y = source.y;
  856. return this;
  857. };
  858. /**
  859. * Sets the Vector2 coordinates with the passed floats.
  860. * Returns the updated Vector2.
  861. */
  862. Vector2.prototype.copyFromFloats = function (x, y) {
  863. this.x = x;
  864. this.y = y;
  865. return this;
  866. };
  867. /**
  868. * Sets the Vector2 coordinates with the passed floats.
  869. * Returns the updated Vector2.
  870. */
  871. Vector2.prototype.set = function (x, y) {
  872. return this.copyFromFloats(x, y);
  873. };
  874. /**
  875. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  876. */
  877. Vector2.prototype.add = function (otherVector) {
  878. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  879. };
  880. /**
  881. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  882. * Returns the Vector2.
  883. */
  884. Vector2.prototype.addToRef = function (otherVector, result) {
  885. result.x = this.x + otherVector.x;
  886. result.y = this.y + otherVector.y;
  887. return this;
  888. };
  889. /**
  890. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  891. * Returns the updated Vector2.
  892. */
  893. Vector2.prototype.addInPlace = function (otherVector) {
  894. this.x += otherVector.x;
  895. this.y += otherVector.y;
  896. return this;
  897. };
  898. /**
  899. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  900. */
  901. Vector2.prototype.addVector3 = function (otherVector) {
  902. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  903. };
  904. /**
  905. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  906. */
  907. Vector2.prototype.subtract = function (otherVector) {
  908. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  909. };
  910. /**
  911. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  912. * Returns the Vector2.
  913. */
  914. Vector2.prototype.subtractToRef = function (otherVector, result) {
  915. result.x = this.x - otherVector.x;
  916. result.y = this.y - otherVector.y;
  917. return this;
  918. };
  919. /**
  920. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  921. * Returns the updated Vector2.
  922. */
  923. Vector2.prototype.subtractInPlace = function (otherVector) {
  924. this.x -= otherVector.x;
  925. this.y -= otherVector.y;
  926. return this;
  927. };
  928. /**
  929. * Multiplies in place the current Vector2 coordinates by the passed ones.
  930. * Returns the updated Vector2.
  931. */
  932. Vector2.prototype.multiplyInPlace = function (otherVector) {
  933. this.x *= otherVector.x;
  934. this.y *= otherVector.y;
  935. return this;
  936. };
  937. /**
  938. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  939. */
  940. Vector2.prototype.multiply = function (otherVector) {
  941. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  942. };
  943. /**
  944. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  945. * Returns the Vector2.
  946. */
  947. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  948. result.x = this.x * otherVector.x;
  949. result.y = this.y * otherVector.y;
  950. return this;
  951. };
  952. /**
  953. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  954. */
  955. Vector2.prototype.multiplyByFloats = function (x, y) {
  956. return new Vector2(this.x * x, this.y * y);
  957. };
  958. /**
  959. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  960. */
  961. Vector2.prototype.divide = function (otherVector) {
  962. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  963. };
  964. /**
  965. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  966. * Returns the Vector2.
  967. */
  968. Vector2.prototype.divideToRef = function (otherVector, result) {
  969. result.x = this.x / otherVector.x;
  970. result.y = this.y / otherVector.y;
  971. return this;
  972. };
  973. /**
  974. * Returns a new Vector2 with current Vector2 negated coordinates.
  975. */
  976. Vector2.prototype.negate = function () {
  977. return new Vector2(-this.x, -this.y);
  978. };
  979. /**
  980. * Multiply the Vector2 coordinates by scale.
  981. * Returns the updated Vector2.
  982. */
  983. Vector2.prototype.scaleInPlace = function (scale) {
  984. this.x *= scale;
  985. this.y *= scale;
  986. return this;
  987. };
  988. /**
  989. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  990. */
  991. Vector2.prototype.scale = function (scale) {
  992. return new Vector2(this.x * scale, this.y * scale);
  993. };
  994. /**
  995. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  996. */
  997. Vector2.prototype.equals = function (otherVector) {
  998. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  999. };
  1000. /**
  1001. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1002. */
  1003. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1004. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1005. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1006. };
  1007. // Properties
  1008. /**
  1009. * Returns the vector length (float).
  1010. */
  1011. Vector2.prototype.length = function () {
  1012. return Math.sqrt(this.x * this.x + this.y * this.y);
  1013. };
  1014. /**
  1015. * Returns the vector squared length (float);
  1016. */
  1017. Vector2.prototype.lengthSquared = function () {
  1018. return (this.x * this.x + this.y * this.y);
  1019. };
  1020. // Methods
  1021. /**
  1022. * Normalize the vector.
  1023. * Returns the updated Vector2.
  1024. */
  1025. Vector2.prototype.normalize = function () {
  1026. var len = this.length();
  1027. if (len === 0)
  1028. return this;
  1029. var num = 1.0 / len;
  1030. this.x *= num;
  1031. this.y *= num;
  1032. return this;
  1033. };
  1034. /**
  1035. * Returns a new Vector2 copied from the Vector2.
  1036. */
  1037. Vector2.prototype.clone = function () {
  1038. return new Vector2(this.x, this.y);
  1039. };
  1040. // Statics
  1041. /**
  1042. * Returns a new Vector2(0, 0)
  1043. */
  1044. Vector2.Zero = function () {
  1045. return new Vector2(0, 0);
  1046. };
  1047. /**
  1048. * Returns a new Vector2(1, 1)
  1049. */
  1050. Vector2.One = function () {
  1051. return new Vector2(1, 1);
  1052. };
  1053. /**
  1054. * Returns a new Vector2 set from the passed index element of the passed array.
  1055. */
  1056. Vector2.FromArray = function (array, offset) {
  1057. if (offset === void 0) { offset = 0; }
  1058. return new Vector2(array[offset], array[offset + 1]);
  1059. };
  1060. /**
  1061. * Sets "result" from the passed index element of the passed array.
  1062. */
  1063. Vector2.FromArrayToRef = function (array, offset, result) {
  1064. result.x = array[offset];
  1065. result.y = array[offset + 1];
  1066. };
  1067. /**
  1068. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  1069. */
  1070. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  1071. var squared = amount * amount;
  1072. var cubed = amount * squared;
  1073. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1074. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1075. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1076. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1077. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1078. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1079. return new Vector2(x, y);
  1080. };
  1081. /**
  1082. * 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".
  1083. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1084. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1085. */
  1086. Vector2.Clamp = function (value, min, max) {
  1087. var x = value.x;
  1088. x = (x > max.x) ? max.x : x;
  1089. x = (x < min.x) ? min.x : x;
  1090. var y = value.y;
  1091. y = (y > max.y) ? max.y : y;
  1092. y = (y < min.y) ? min.y : y;
  1093. return new Vector2(x, y);
  1094. };
  1095. /**
  1096. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1097. */
  1098. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1099. var squared = amount * amount;
  1100. var cubed = amount * squared;
  1101. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1102. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1103. var part3 = (cubed - (2.0 * squared)) + amount;
  1104. var part4 = cubed - squared;
  1105. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1106. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1107. return new Vector2(x, y);
  1108. };
  1109. /**
  1110. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1111. */
  1112. Vector2.Lerp = function (start, end, amount) {
  1113. var x = start.x + ((end.x - start.x) * amount);
  1114. var y = start.y + ((end.y - start.y) * amount);
  1115. return new Vector2(x, y);
  1116. };
  1117. /**
  1118. * Returns the dot product (float) of the vector "left" and the vector "right".
  1119. */
  1120. Vector2.Dot = function (left, right) {
  1121. return left.x * right.x + left.y * right.y;
  1122. };
  1123. /**
  1124. * Returns a new Vector2 equal to the normalized passed vector.
  1125. */
  1126. Vector2.Normalize = function (vector) {
  1127. var newVector = vector.clone();
  1128. newVector.normalize();
  1129. return newVector;
  1130. };
  1131. /**
  1132. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1133. */
  1134. Vector2.Minimize = function (left, right) {
  1135. var x = (left.x < right.x) ? left.x : right.x;
  1136. var y = (left.y < right.y) ? left.y : right.y;
  1137. return new Vector2(x, y);
  1138. };
  1139. /**
  1140. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1141. */
  1142. Vector2.Maximize = function (left, right) {
  1143. var x = (left.x > right.x) ? left.x : right.x;
  1144. var y = (left.y > right.y) ? left.y : right.y;
  1145. return new Vector2(x, y);
  1146. };
  1147. /**
  1148. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1149. */
  1150. Vector2.Transform = function (vector, transformation) {
  1151. var r = Vector2.Zero();
  1152. Vector2.TransformToRef(vector, transformation, r);
  1153. return r;
  1154. };
  1155. /**
  1156. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1157. */
  1158. Vector2.TransformToRef = function (vector, transformation, result) {
  1159. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1160. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1161. result.x = x;
  1162. result.y = y;
  1163. };
  1164. /**
  1165. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1166. */
  1167. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1168. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1169. var sign = a < 0 ? -1 : 1;
  1170. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1171. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1172. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1173. };
  1174. /**
  1175. * Returns the distance (float) between the vectors "value1" and "value2".
  1176. */
  1177. Vector2.Distance = function (value1, value2) {
  1178. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1179. };
  1180. /**
  1181. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1182. */
  1183. Vector2.DistanceSquared = function (value1, value2) {
  1184. var x = value1.x - value2.x;
  1185. var y = value1.y - value2.y;
  1186. return (x * x) + (y * y);
  1187. };
  1188. /**
  1189. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1190. */
  1191. Vector2.Center = function (value1, value2) {
  1192. var center = value1.add(value2);
  1193. center.scaleInPlace(0.5);
  1194. return center;
  1195. };
  1196. /**
  1197. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1198. */
  1199. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1200. var l2 = Vector2.DistanceSquared(segA, segB);
  1201. if (l2 === 0.0) {
  1202. return Vector2.Distance(p, segA);
  1203. }
  1204. var v = segB.subtract(segA);
  1205. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1206. var proj = segA.add(v.multiplyByFloats(t, t));
  1207. return Vector2.Distance(p, proj);
  1208. };
  1209. return Vector2;
  1210. }());
  1211. BABYLON.Vector2 = Vector2;
  1212. var Vector3 = (function () {
  1213. /**
  1214. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1215. * A Vector3 is the main object used in 3D geometry.
  1216. * It can represent etiher the coordinates of a point the space, either a direction.
  1217. */
  1218. function Vector3(x, y, z) {
  1219. this.x = x;
  1220. this.y = y;
  1221. this.z = z;
  1222. }
  1223. /**
  1224. * Returns a string with the Vector3 coordinates.
  1225. */
  1226. Vector3.prototype.toString = function () {
  1227. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1228. };
  1229. /**
  1230. * Returns the string "Vector3"
  1231. */
  1232. Vector3.prototype.getClassName = function () {
  1233. return "Vector3";
  1234. };
  1235. /**
  1236. * Returns the Vector hash code.
  1237. */
  1238. Vector3.prototype.getHashCode = function () {
  1239. var hash = this.x || 0;
  1240. hash = (hash * 397) ^ (this.y || 0);
  1241. hash = (hash * 397) ^ (this.z || 0);
  1242. return hash;
  1243. };
  1244. // Operators
  1245. /**
  1246. * Returns a new array with three elements : the coordinates the Vector3.
  1247. */
  1248. Vector3.prototype.asArray = function () {
  1249. var result = [];
  1250. this.toArray(result, 0);
  1251. return result;
  1252. };
  1253. /**
  1254. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1255. * Returns the Vector3.
  1256. */
  1257. Vector3.prototype.toArray = function (array, index) {
  1258. if (index === void 0) { index = 0; }
  1259. array[index] = this.x;
  1260. array[index + 1] = this.y;
  1261. array[index + 2] = this.z;
  1262. return this;
  1263. };
  1264. /**
  1265. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1266. */
  1267. Vector3.prototype.toQuaternion = function () {
  1268. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1269. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1270. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1271. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1272. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1273. var cosy = Math.cos(this.y * 0.5);
  1274. var siny = Math.sin(this.y * 0.5);
  1275. result.x = coszMinusx * siny;
  1276. result.y = -sinzMinusx * siny;
  1277. result.z = sinxPlusz * cosy;
  1278. result.w = cosxPlusz * cosy;
  1279. return result;
  1280. };
  1281. /**
  1282. * Adds the passed vector to the current Vector3.
  1283. * Returns the updated Vector3.
  1284. */
  1285. Vector3.prototype.addInPlace = function (otherVector) {
  1286. this.x += otherVector.x;
  1287. this.y += otherVector.y;
  1288. this.z += otherVector.z;
  1289. return this;
  1290. };
  1291. /**
  1292. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1293. */
  1294. Vector3.prototype.add = function (otherVector) {
  1295. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1296. };
  1297. /**
  1298. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1299. * Returns the current Vector3.
  1300. */
  1301. Vector3.prototype.addToRef = function (otherVector, result) {
  1302. result.x = this.x + otherVector.x;
  1303. result.y = this.y + otherVector.y;
  1304. result.z = this.z + otherVector.z;
  1305. return this;
  1306. };
  1307. /**
  1308. * Subtract the passed vector from the current Vector3.
  1309. * Returns the updated Vector3.
  1310. */
  1311. Vector3.prototype.subtractInPlace = function (otherVector) {
  1312. this.x -= otherVector.x;
  1313. this.y -= otherVector.y;
  1314. this.z -= otherVector.z;
  1315. return this;
  1316. };
  1317. /**
  1318. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1319. */
  1320. Vector3.prototype.subtract = function (otherVector) {
  1321. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1322. };
  1323. /**
  1324. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1325. * Returns the current Vector3.
  1326. */
  1327. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1328. result.x = this.x - otherVector.x;
  1329. result.y = this.y - otherVector.y;
  1330. result.z = this.z - otherVector.z;
  1331. return this;
  1332. };
  1333. /**
  1334. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1335. */
  1336. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1337. return new Vector3(this.x - x, this.y - y, this.z - z);
  1338. };
  1339. /**
  1340. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1341. * Returns the current Vector3.
  1342. */
  1343. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1344. result.x = this.x - x;
  1345. result.y = this.y - y;
  1346. result.z = this.z - z;
  1347. return this;
  1348. };
  1349. /**
  1350. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1351. */
  1352. Vector3.prototype.negate = function () {
  1353. return new Vector3(-this.x, -this.y, -this.z);
  1354. };
  1355. /**
  1356. * Multiplies the Vector3 coordinates by the float "scale".
  1357. * Returns the updated Vector3.
  1358. */
  1359. Vector3.prototype.scaleInPlace = function (scale) {
  1360. this.x *= scale;
  1361. this.y *= scale;
  1362. this.z *= scale;
  1363. return this;
  1364. };
  1365. /**
  1366. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1367. */
  1368. Vector3.prototype.scale = function (scale) {
  1369. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1370. };
  1371. /**
  1372. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1373. * Returns the current Vector3.
  1374. */
  1375. Vector3.prototype.scaleToRef = function (scale, result) {
  1376. result.x = this.x * scale;
  1377. result.y = this.y * scale;
  1378. result.z = this.z * scale;
  1379. return this;
  1380. };
  1381. /**
  1382. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1383. */
  1384. Vector3.prototype.equals = function (otherVector) {
  1385. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1386. };
  1387. /**
  1388. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1389. */
  1390. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1391. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1392. 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);
  1393. };
  1394. /**
  1395. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1396. */
  1397. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1398. return this.x === x && this.y === y && this.z === z;
  1399. };
  1400. /**
  1401. * Muliplies the current Vector3 coordinates by the passed ones.
  1402. * Returns the updated Vector3.
  1403. */
  1404. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1405. this.x *= otherVector.x;
  1406. this.y *= otherVector.y;
  1407. this.z *= otherVector.z;
  1408. return this;
  1409. };
  1410. /**
  1411. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1412. */
  1413. Vector3.prototype.multiply = function (otherVector) {
  1414. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1415. };
  1416. /**
  1417. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1418. * Returns the current Vector3.
  1419. */
  1420. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1421. result.x = this.x * otherVector.x;
  1422. result.y = this.y * otherVector.y;
  1423. result.z = this.z * otherVector.z;
  1424. return this;
  1425. };
  1426. /**
  1427. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1428. */
  1429. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1430. return new Vector3(this.x * x, this.y * y, this.z * z);
  1431. };
  1432. /**
  1433. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1434. */
  1435. Vector3.prototype.divide = function (otherVector) {
  1436. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1437. };
  1438. /**
  1439. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1440. * Returns the current Vector3.
  1441. */
  1442. Vector3.prototype.divideToRef = function (otherVector, result) {
  1443. result.x = this.x / otherVector.x;
  1444. result.y = this.y / otherVector.y;
  1445. result.z = this.z / otherVector.z;
  1446. return this;
  1447. };
  1448. /**
  1449. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1450. * Returns the updated Vector3.
  1451. */
  1452. Vector3.prototype.MinimizeInPlace = function (other) {
  1453. if (other.x < this.x)
  1454. this.x = other.x;
  1455. if (other.y < this.y)
  1456. this.y = other.y;
  1457. if (other.z < this.z)
  1458. this.z = other.z;
  1459. return this;
  1460. };
  1461. /**
  1462. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1463. * Returns the updated Vector3.
  1464. */
  1465. Vector3.prototype.MaximizeInPlace = function (other) {
  1466. if (other.x > this.x)
  1467. this.x = other.x;
  1468. if (other.y > this.y)
  1469. this.y = other.y;
  1470. if (other.z > this.z)
  1471. this.z = other.z;
  1472. return this;
  1473. };
  1474. // Properties
  1475. /**
  1476. * Returns the length of the Vector3 (float).
  1477. */
  1478. Vector3.prototype.length = function () {
  1479. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1480. };
  1481. /**
  1482. * Returns the squared length of the Vector3 (float).
  1483. */
  1484. Vector3.prototype.lengthSquared = function () {
  1485. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1486. };
  1487. // Methods
  1488. /**
  1489. * Normalize the current Vector3.
  1490. * Returns the updated Vector3.
  1491. */
  1492. Vector3.prototype.normalize = function () {
  1493. var len = this.length();
  1494. if (len === 0 || len === 1.0)
  1495. return this;
  1496. var num = 1.0 / len;
  1497. this.x *= num;
  1498. this.y *= num;
  1499. this.z *= num;
  1500. return this;
  1501. };
  1502. /**
  1503. * Returns a new Vector3 copied from the current Vector3.
  1504. */
  1505. Vector3.prototype.clone = function () {
  1506. return new Vector3(this.x, this.y, this.z);
  1507. };
  1508. /**
  1509. * Copies the passed vector coordinates to the current Vector3 ones.
  1510. * Returns the updated Vector3.
  1511. */
  1512. Vector3.prototype.copyFrom = function (source) {
  1513. this.x = source.x;
  1514. this.y = source.y;
  1515. this.z = source.z;
  1516. return this;
  1517. };
  1518. /**
  1519. * Copies the passed floats to the current Vector3 coordinates.
  1520. * Returns the updated Vector3.
  1521. */
  1522. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1523. this.x = x;
  1524. this.y = y;
  1525. this.z = z;
  1526. return this;
  1527. };
  1528. /**
  1529. * Copies the passed floats to the current Vector3 coordinates.
  1530. * Returns the updated Vector3.
  1531. */
  1532. Vector3.prototype.set = function (x, y, z) {
  1533. return this.copyFromFloats(x, y, z);
  1534. };
  1535. // Statics
  1536. /**
  1537. *
  1538. */
  1539. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1540. var d0 = Vector3.Dot(vector0, axis) - size;
  1541. var d1 = Vector3.Dot(vector1, axis) - size;
  1542. var s = d0 / (d0 - d1);
  1543. return s;
  1544. };
  1545. /**
  1546. * Returns a new Vector3 set from the index "offset" of the passed array.
  1547. */
  1548. Vector3.FromArray = function (array, offset) {
  1549. if (!offset) {
  1550. offset = 0;
  1551. }
  1552. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1553. };
  1554. /**
  1555. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1556. * This function is deprecated. Use FromArray instead.
  1557. */
  1558. Vector3.FromFloatArray = function (array, offset) {
  1559. return Vector3.FromArray(array, offset);
  1560. };
  1561. /**
  1562. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1563. */
  1564. Vector3.FromArrayToRef = function (array, offset, result) {
  1565. result.x = array[offset];
  1566. result.y = array[offset + 1];
  1567. result.z = array[offset + 2];
  1568. };
  1569. /**
  1570. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1571. * This function is deprecated. Use FromArrayToRef instead.
  1572. */
  1573. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1574. return Vector3.FromArrayToRef(array, offset, result);
  1575. };
  1576. /**
  1577. * Sets the passed vector "result" with the passed floats.
  1578. */
  1579. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1580. result.x = x;
  1581. result.y = y;
  1582. result.z = z;
  1583. };
  1584. /**
  1585. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1586. */
  1587. Vector3.Zero = function () {
  1588. return new Vector3(0.0, 0.0, 0.0);
  1589. };
  1590. /**
  1591. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1592. */
  1593. Vector3.One = function () {
  1594. return new Vector3(1.0, 1.0, 1.0);
  1595. };
  1596. /**
  1597. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1598. */
  1599. Vector3.Up = function () {
  1600. return new Vector3(0.0, 1.0, 0.0);
  1601. };
  1602. /**
  1603. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1604. */
  1605. Vector3.Forward = function () {
  1606. return new Vector3(0.0, 0.0, 1.0);
  1607. };
  1608. /**
  1609. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1610. */
  1611. Vector3.Right = function () {
  1612. return new Vector3(1.0, 0.0, 0.0);
  1613. };
  1614. /**
  1615. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1616. */
  1617. Vector3.Left = function () {
  1618. return new Vector3(-1.0, 0.0, 0.0);
  1619. };
  1620. /**
  1621. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1622. * This method computes tranformed coordinates only, not transformed direction vectors.
  1623. */
  1624. Vector3.TransformCoordinates = function (vector, transformation) {
  1625. var result = Vector3.Zero();
  1626. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1627. return result;
  1628. };
  1629. /**
  1630. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1631. * This method computes tranformed coordinates only, not transformed direction vectors.
  1632. */
  1633. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1634. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1635. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1636. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1637. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1638. result.x = x / w;
  1639. result.y = y / w;
  1640. result.z = z / w;
  1641. };
  1642. /**
  1643. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1644. * This method computes tranformed coordinates only, not transformed direction vectors.
  1645. */
  1646. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1647. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1648. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1649. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1650. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1651. result.x = rx / rw;
  1652. result.y = ry / rw;
  1653. result.z = rz / rw;
  1654. };
  1655. /**
  1656. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1657. * This methods computes transformed normalized direction vectors only.
  1658. */
  1659. Vector3.TransformNormal = function (vector, transformation) {
  1660. var result = Vector3.Zero();
  1661. Vector3.TransformNormalToRef(vector, transformation, result);
  1662. return result;
  1663. };
  1664. /**
  1665. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1666. * This methods computes transformed normalized direction vectors only.
  1667. */
  1668. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1669. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1670. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1671. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1672. result.x = x;
  1673. result.y = y;
  1674. result.z = z;
  1675. };
  1676. /**
  1677. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1678. * This methods computes transformed normalized direction vectors only.
  1679. */
  1680. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1681. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1682. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1683. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1684. };
  1685. /**
  1686. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1687. */
  1688. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1689. var squared = amount * amount;
  1690. var cubed = amount * squared;
  1691. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1692. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1693. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1694. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1695. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1696. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1697. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1698. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1699. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1700. return new Vector3(x, y, z);
  1701. };
  1702. /**
  1703. * 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".
  1704. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1705. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1706. */
  1707. Vector3.Clamp = function (value, min, max) {
  1708. var x = value.x;
  1709. x = (x > max.x) ? max.x : x;
  1710. x = (x < min.x) ? min.x : x;
  1711. var y = value.y;
  1712. y = (y > max.y) ? max.y : y;
  1713. y = (y < min.y) ? min.y : y;
  1714. var z = value.z;
  1715. z = (z > max.z) ? max.z : z;
  1716. z = (z < min.z) ? min.z : z;
  1717. return new Vector3(x, y, z);
  1718. };
  1719. /**
  1720. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1721. */
  1722. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1723. var squared = amount * amount;
  1724. var cubed = amount * squared;
  1725. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1726. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1727. var part3 = (cubed - (2.0 * squared)) + amount;
  1728. var part4 = cubed - squared;
  1729. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1730. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1731. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1732. return new Vector3(x, y, z);
  1733. };
  1734. /**
  1735. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1736. */
  1737. Vector3.Lerp = function (start, end, amount) {
  1738. var result = new Vector3(0, 0, 0);
  1739. Vector3.LerpToRef(start, end, amount, result);
  1740. return result;
  1741. };
  1742. /**
  1743. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1744. */
  1745. Vector3.LerpToRef = function (start, end, amount, result) {
  1746. result.x = start.x + ((end.x - start.x) * amount);
  1747. result.y = start.y + ((end.y - start.y) * amount);
  1748. result.z = start.z + ((end.z - start.z) * amount);
  1749. };
  1750. /**
  1751. * Returns the dot product (float) between the vectors "left" and "right".
  1752. */
  1753. Vector3.Dot = function (left, right) {
  1754. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1755. };
  1756. /**
  1757. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1758. * The cross product is then orthogonal to both "left" and "right".
  1759. */
  1760. Vector3.Cross = function (left, right) {
  1761. var result = Vector3.Zero();
  1762. Vector3.CrossToRef(left, right, result);
  1763. return result;
  1764. };
  1765. /**
  1766. * Sets the passed vector "result" with the cross product of "left" and "right".
  1767. * The cross product is then orthogonal to both "left" and "right".
  1768. */
  1769. Vector3.CrossToRef = function (left, right, result) {
  1770. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1771. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1772. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1773. result.copyFrom(MathTmp.Vector3[0]);
  1774. };
  1775. /**
  1776. * Returns a new Vector3 as the normalization of the passed vector.
  1777. */
  1778. Vector3.Normalize = function (vector) {
  1779. var result = Vector3.Zero();
  1780. Vector3.NormalizeToRef(vector, result);
  1781. return result;
  1782. };
  1783. /**
  1784. * Sets the passed vector "result" with the normalization of the passed first vector.
  1785. */
  1786. Vector3.NormalizeToRef = function (vector, result) {
  1787. result.copyFrom(vector);
  1788. result.normalize();
  1789. };
  1790. Vector3.Project = function (vector, world, transform, viewport) {
  1791. var cw = viewport.width;
  1792. var ch = viewport.height;
  1793. var cx = viewport.x;
  1794. var cy = viewport.y;
  1795. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1796. 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);
  1797. var matrix = MathTmp.Matrix[0];
  1798. world.multiplyToRef(transform, matrix);
  1799. matrix.multiplyToRef(viewportMatrix, matrix);
  1800. return Vector3.TransformCoordinates(vector, matrix);
  1801. };
  1802. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1803. var matrix = MathTmp.Matrix[0];
  1804. world.multiplyToRef(transform, matrix);
  1805. matrix.invert();
  1806. source.x = source.x / viewportWidth * 2 - 1;
  1807. source.y = -(source.y / viewportHeight * 2 - 1);
  1808. var vector = Vector3.TransformCoordinates(source, matrix);
  1809. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1810. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1811. vector = vector.scale(1.0 / num);
  1812. }
  1813. return vector;
  1814. };
  1815. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1816. var matrix = MathTmp.Matrix[0];
  1817. world.multiplyToRef(view, matrix);
  1818. matrix.multiplyToRef(projection, matrix);
  1819. matrix.invert();
  1820. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1821. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1822. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1823. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1824. vector = vector.scale(1.0 / num);
  1825. }
  1826. return vector;
  1827. };
  1828. Vector3.Minimize = function (left, right) {
  1829. var min = left.clone();
  1830. min.MinimizeInPlace(right);
  1831. return min;
  1832. };
  1833. Vector3.Maximize = function (left, right) {
  1834. var max = left.clone();
  1835. max.MaximizeInPlace(right);
  1836. return max;
  1837. };
  1838. /**
  1839. * Returns the distance (float) between the vectors "value1" and "value2".
  1840. */
  1841. Vector3.Distance = function (value1, value2) {
  1842. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1843. };
  1844. /**
  1845. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1846. */
  1847. Vector3.DistanceSquared = function (value1, value2) {
  1848. var x = value1.x - value2.x;
  1849. var y = value1.y - value2.y;
  1850. var z = value1.z - value2.z;
  1851. return (x * x) + (y * y) + (z * z);
  1852. };
  1853. /**
  1854. * Returns a new Vector3 located at the center between "value1" and "value2".
  1855. */
  1856. Vector3.Center = function (value1, value2) {
  1857. var center = value1.add(value2);
  1858. center.scaleInPlace(0.5);
  1859. return center;
  1860. };
  1861. /**
  1862. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1863. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1864. * to something in order to rotate it from its local system to the given target system.
  1865. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1866. * Returns a new Vector3.
  1867. */
  1868. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1869. var rotation = Vector3.Zero();
  1870. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1871. return rotation;
  1872. };
  1873. /**
  1874. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1875. */
  1876. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1877. var quat = MathTmp.Quaternion[0];
  1878. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1879. quat.toEulerAnglesToRef(ref);
  1880. };
  1881. return Vector3;
  1882. }());
  1883. BABYLON.Vector3 = Vector3;
  1884. //Vector4 class created for EulerAngle class conversion to Quaternion
  1885. var Vector4 = (function () {
  1886. /**
  1887. * Creates a Vector4 object from the passed floats.
  1888. */
  1889. function Vector4(x, y, z, w) {
  1890. this.x = x;
  1891. this.y = y;
  1892. this.z = z;
  1893. this.w = w;
  1894. }
  1895. /**
  1896. * Returns the string with the Vector4 coordinates.
  1897. */
  1898. Vector4.prototype.toString = function () {
  1899. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1900. };
  1901. /**
  1902. * Returns the string "Vector4".
  1903. */
  1904. Vector4.prototype.getClassName = function () {
  1905. return "Vector4";
  1906. };
  1907. /**
  1908. * Returns the Vector4 hash code.
  1909. */
  1910. Vector4.prototype.getHashCode = function () {
  1911. var hash = this.x || 0;
  1912. hash = (hash * 397) ^ (this.y || 0);
  1913. hash = (hash * 397) ^ (this.z || 0);
  1914. hash = (hash * 397) ^ (this.w || 0);
  1915. return hash;
  1916. };
  1917. // Operators
  1918. /**
  1919. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1920. */
  1921. Vector4.prototype.asArray = function () {
  1922. var result = new Array();
  1923. this.toArray(result, 0);
  1924. return result;
  1925. };
  1926. /**
  1927. * Populates the passed array from the passed index with the Vector4 coordinates.
  1928. * Returns the Vector4.
  1929. */
  1930. Vector4.prototype.toArray = function (array, index) {
  1931. if (index === undefined) {
  1932. index = 0;
  1933. }
  1934. array[index] = this.x;
  1935. array[index + 1] = this.y;
  1936. array[index + 2] = this.z;
  1937. array[index + 3] = this.w;
  1938. return this;
  1939. };
  1940. /**
  1941. * Adds the passed vector to the current Vector4.
  1942. * Returns the updated Vector4.
  1943. */
  1944. Vector4.prototype.addInPlace = function (otherVector) {
  1945. this.x += otherVector.x;
  1946. this.y += otherVector.y;
  1947. this.z += otherVector.z;
  1948. this.w += otherVector.w;
  1949. return this;
  1950. };
  1951. /**
  1952. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1953. */
  1954. Vector4.prototype.add = function (otherVector) {
  1955. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1956. };
  1957. /**
  1958. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1959. * Returns the current Vector4.
  1960. */
  1961. Vector4.prototype.addToRef = function (otherVector, result) {
  1962. result.x = this.x + otherVector.x;
  1963. result.y = this.y + otherVector.y;
  1964. result.z = this.z + otherVector.z;
  1965. result.w = this.w + otherVector.w;
  1966. return this;
  1967. };
  1968. /**
  1969. * Subtract in place the passed vector from the current Vector4.
  1970. * Returns the updated Vector4.
  1971. */
  1972. Vector4.prototype.subtractInPlace = function (otherVector) {
  1973. this.x -= otherVector.x;
  1974. this.y -= otherVector.y;
  1975. this.z -= otherVector.z;
  1976. this.w -= otherVector.w;
  1977. return this;
  1978. };
  1979. /**
  1980. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1981. */
  1982. Vector4.prototype.subtract = function (otherVector) {
  1983. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1984. };
  1985. /**
  1986. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1987. * Returns the current Vector4.
  1988. */
  1989. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1990. result.x = this.x - otherVector.x;
  1991. result.y = this.y - otherVector.y;
  1992. result.z = this.z - otherVector.z;
  1993. result.w = this.w - otherVector.w;
  1994. return this;
  1995. };
  1996. /**
  1997. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1998. */
  1999. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  2000. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  2001. };
  2002. /**
  2003. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2004. * Returns the current Vector4.
  2005. */
  2006. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  2007. result.x = this.x - x;
  2008. result.y = this.y - y;
  2009. result.z = this.z - z;
  2010. result.w = this.w - w;
  2011. return this;
  2012. };
  2013. /**
  2014. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  2015. */
  2016. Vector4.prototype.negate = function () {
  2017. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  2018. };
  2019. /**
  2020. * Multiplies the current Vector4 coordinates by scale (float).
  2021. * Returns the updated Vector4.
  2022. */
  2023. Vector4.prototype.scaleInPlace = function (scale) {
  2024. this.x *= scale;
  2025. this.y *= scale;
  2026. this.z *= scale;
  2027. this.w *= scale;
  2028. return this;
  2029. };
  2030. /**
  2031. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  2032. */
  2033. Vector4.prototype.scale = function (scale) {
  2034. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  2035. };
  2036. /**
  2037. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  2038. * Returns the current Vector4.
  2039. */
  2040. Vector4.prototype.scaleToRef = function (scale, result) {
  2041. result.x = this.x * scale;
  2042. result.y = this.y * scale;
  2043. result.z = this.z * scale;
  2044. result.w = this.w * scale;
  2045. return this;
  2046. };
  2047. /**
  2048. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2049. */
  2050. Vector4.prototype.equals = function (otherVector) {
  2051. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2052. };
  2053. /**
  2054. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2055. */
  2056. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2057. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2058. return otherVector
  2059. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2060. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2061. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2062. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2063. };
  2064. /**
  2065. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2066. */
  2067. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2068. return this.x === x && this.y === y && this.z === z && this.w === w;
  2069. };
  2070. /**
  2071. * Multiplies in place the current Vector4 by the passed one.
  2072. * Returns the updated Vector4.
  2073. */
  2074. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2075. this.x *= otherVector.x;
  2076. this.y *= otherVector.y;
  2077. this.z *= otherVector.z;
  2078. this.w *= otherVector.w;
  2079. return this;
  2080. };
  2081. /**
  2082. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2083. */
  2084. Vector4.prototype.multiply = function (otherVector) {
  2085. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2086. };
  2087. /**
  2088. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2089. * Returns the current Vector4.
  2090. */
  2091. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2092. result.x = this.x * otherVector.x;
  2093. result.y = this.y * otherVector.y;
  2094. result.z = this.z * otherVector.z;
  2095. result.w = this.w * otherVector.w;
  2096. return this;
  2097. };
  2098. /**
  2099. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2100. */
  2101. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2102. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2103. };
  2104. /**
  2105. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2106. */
  2107. Vector4.prototype.divide = function (otherVector) {
  2108. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2109. };
  2110. /**
  2111. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2112. * Returns the current Vector4.
  2113. */
  2114. Vector4.prototype.divideToRef = function (otherVector, result) {
  2115. result.x = this.x / otherVector.x;
  2116. result.y = this.y / otherVector.y;
  2117. result.z = this.z / otherVector.z;
  2118. result.w = this.w / otherVector.w;
  2119. return this;
  2120. };
  2121. /**
  2122. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2123. */
  2124. Vector4.prototype.MinimizeInPlace = function (other) {
  2125. if (other.x < this.x)
  2126. this.x = other.x;
  2127. if (other.y < this.y)
  2128. this.y = other.y;
  2129. if (other.z < this.z)
  2130. this.z = other.z;
  2131. if (other.w < this.w)
  2132. this.w = other.w;
  2133. return this;
  2134. };
  2135. /**
  2136. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2137. */
  2138. Vector4.prototype.MaximizeInPlace = function (other) {
  2139. if (other.x > this.x)
  2140. this.x = other.x;
  2141. if (other.y > this.y)
  2142. this.y = other.y;
  2143. if (other.z > this.z)
  2144. this.z = other.z;
  2145. if (other.w > this.w)
  2146. this.w = other.w;
  2147. return this;
  2148. };
  2149. // Properties
  2150. /**
  2151. * Returns the Vector4 length (float).
  2152. */
  2153. Vector4.prototype.length = function () {
  2154. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2155. };
  2156. /**
  2157. * Returns the Vector4 squared length (float).
  2158. */
  2159. Vector4.prototype.lengthSquared = function () {
  2160. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2161. };
  2162. // Methods
  2163. /**
  2164. * Normalizes in place the Vector4.
  2165. * Returns the updated Vector4.
  2166. */
  2167. Vector4.prototype.normalize = function () {
  2168. var len = this.length();
  2169. if (len === 0)
  2170. return this;
  2171. var num = 1.0 / len;
  2172. this.x *= num;
  2173. this.y *= num;
  2174. this.z *= num;
  2175. this.w *= num;
  2176. return this;
  2177. };
  2178. /**
  2179. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2180. */
  2181. Vector4.prototype.toVector3 = function () {
  2182. return new Vector3(this.x, this.y, this.z);
  2183. };
  2184. /**
  2185. * Returns a new Vector4 copied from the current one.
  2186. */
  2187. Vector4.prototype.clone = function () {
  2188. return new Vector4(this.x, this.y, this.z, this.w);
  2189. };
  2190. /**
  2191. * Updates the current Vector4 with the passed one coordinates.
  2192. * Returns the updated Vector4.
  2193. */
  2194. Vector4.prototype.copyFrom = function (source) {
  2195. this.x = source.x;
  2196. this.y = source.y;
  2197. this.z = source.z;
  2198. this.w = source.w;
  2199. return this;
  2200. };
  2201. /**
  2202. * Updates the current Vector4 coordinates with the passed floats.
  2203. * Returns the updated Vector4.
  2204. */
  2205. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2206. this.x = x;
  2207. this.y = y;
  2208. this.z = z;
  2209. this.w = w;
  2210. return this;
  2211. };
  2212. /**
  2213. * Updates the current Vector4 coordinates with the passed floats.
  2214. * Returns the updated Vector4.
  2215. */
  2216. Vector4.prototype.set = function (x, y, z, w) {
  2217. return this.copyFromFloats(x, y, z, w);
  2218. };
  2219. // Statics
  2220. /**
  2221. * Returns a new Vector4 set from the starting index of the passed array.
  2222. */
  2223. Vector4.FromArray = function (array, offset) {
  2224. if (!offset) {
  2225. offset = 0;
  2226. }
  2227. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2228. };
  2229. /**
  2230. * Updates the passed vector "result" from the starting index of the passed array.
  2231. */
  2232. Vector4.FromArrayToRef = function (array, offset, result) {
  2233. result.x = array[offset];
  2234. result.y = array[offset + 1];
  2235. result.z = array[offset + 2];
  2236. result.w = array[offset + 3];
  2237. };
  2238. /**
  2239. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2240. */
  2241. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2242. Vector4.FromArrayToRef(array, offset, result);
  2243. };
  2244. /**
  2245. * Updates the passed vector "result" coordinates from the passed floats.
  2246. */
  2247. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2248. result.x = x;
  2249. result.y = y;
  2250. result.z = z;
  2251. result.w = w;
  2252. };
  2253. /**
  2254. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2255. */
  2256. Vector4.Zero = function () {
  2257. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2258. };
  2259. /**
  2260. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2261. */
  2262. Vector4.One = function () {
  2263. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2264. };
  2265. /**
  2266. * Returns a new normalized Vector4 from the passed one.
  2267. */
  2268. Vector4.Normalize = function (vector) {
  2269. var result = Vector4.Zero();
  2270. Vector4.NormalizeToRef(vector, result);
  2271. return result;
  2272. };
  2273. /**
  2274. * Updates the passed vector "result" from the normalization of the passed one.
  2275. */
  2276. Vector4.NormalizeToRef = function (vector, result) {
  2277. result.copyFrom(vector);
  2278. result.normalize();
  2279. };
  2280. Vector4.Minimize = function (left, right) {
  2281. var min = left.clone();
  2282. min.MinimizeInPlace(right);
  2283. return min;
  2284. };
  2285. Vector4.Maximize = function (left, right) {
  2286. var max = left.clone();
  2287. max.MaximizeInPlace(right);
  2288. return max;
  2289. };
  2290. /**
  2291. * Returns the distance (float) between the vectors "value1" and "value2".
  2292. */
  2293. Vector4.Distance = function (value1, value2) {
  2294. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2295. };
  2296. /**
  2297. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2298. */
  2299. Vector4.DistanceSquared = function (value1, value2) {
  2300. var x = value1.x - value2.x;
  2301. var y = value1.y - value2.y;
  2302. var z = value1.z - value2.z;
  2303. var w = value1.w - value2.w;
  2304. return (x * x) + (y * y) + (z * z) + (w * w);
  2305. };
  2306. /**
  2307. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2308. */
  2309. Vector4.Center = function (value1, value2) {
  2310. var center = value1.add(value2);
  2311. center.scaleInPlace(0.5);
  2312. return center;
  2313. };
  2314. /**
  2315. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2316. * This methods computes transformed normalized direction vectors only.
  2317. */
  2318. Vector4.TransformNormal = function (vector, transformation) {
  2319. var result = Vector4.Zero();
  2320. Vector4.TransformNormalToRef(vector, transformation, result);
  2321. return result;
  2322. };
  2323. /**
  2324. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2325. * This methods computes transformed normalized direction vectors only.
  2326. */
  2327. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2328. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2329. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2330. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2331. result.x = x;
  2332. result.y = y;
  2333. result.z = z;
  2334. result.w = vector.w;
  2335. };
  2336. /**
  2337. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2338. * This methods computes transformed normalized direction vectors only.
  2339. */
  2340. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2341. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2342. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2343. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2344. result.w = w;
  2345. };
  2346. return Vector4;
  2347. }());
  2348. BABYLON.Vector4 = Vector4;
  2349. var Size = (function () {
  2350. /**
  2351. * Creates a Size object from the passed width and height (floats).
  2352. */
  2353. function Size(width, height) {
  2354. this.width = width;
  2355. this.height = height;
  2356. }
  2357. // Returns a string with the Size width and height.
  2358. Size.prototype.toString = function () {
  2359. return "{W: " + this.width + ", H: " + this.height + "}";
  2360. };
  2361. /**
  2362. * Returns the string "Size"
  2363. */
  2364. Size.prototype.getClassName = function () {
  2365. return "Size";
  2366. };
  2367. /**
  2368. * Returns the Size hash code.
  2369. */
  2370. Size.prototype.getHashCode = function () {
  2371. var hash = this.width || 0;
  2372. hash = (hash * 397) ^ (this.height || 0);
  2373. return hash;
  2374. };
  2375. /**
  2376. * Updates the current size from the passed one.
  2377. * Returns the updated Size.
  2378. */
  2379. Size.prototype.copyFrom = function (src) {
  2380. this.width = src.width;
  2381. this.height = src.height;
  2382. };
  2383. /**
  2384. * Updates in place the current Size from the passed floats.
  2385. * Returns the updated Size.
  2386. */
  2387. Size.prototype.copyFromFloats = function (width, height) {
  2388. this.width = width;
  2389. this.height = height;
  2390. return this;
  2391. };
  2392. /**
  2393. * Updates in place the current Size from the passed floats.
  2394. * Returns the updated Size.
  2395. */
  2396. Size.prototype.set = function (width, height) {
  2397. return this.copyFromFloats(width, height);
  2398. };
  2399. /**
  2400. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2401. */
  2402. Size.prototype.multiplyByFloats = function (w, h) {
  2403. return new Size(this.width * w, this.height * h);
  2404. };
  2405. /**
  2406. * Returns a new Size copied from the passed one.
  2407. */
  2408. Size.prototype.clone = function () {
  2409. return new Size(this.width, this.height);
  2410. };
  2411. /**
  2412. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2413. */
  2414. Size.prototype.equals = function (other) {
  2415. if (!other) {
  2416. return false;
  2417. }
  2418. return (this.width === other.width) && (this.height === other.height);
  2419. };
  2420. Object.defineProperty(Size.prototype, "surface", {
  2421. /**
  2422. * Returns the surface of the Size : width * height (float).
  2423. */
  2424. get: function () {
  2425. return this.width * this.height;
  2426. },
  2427. enumerable: true,
  2428. configurable: true
  2429. });
  2430. /**
  2431. * Returns a new Size set to (0.0, 0.0)
  2432. */
  2433. Size.Zero = function () {
  2434. return new Size(0.0, 0.0);
  2435. };
  2436. /**
  2437. * Returns a new Size set as the addition result of the current Size and the passed one.
  2438. */
  2439. Size.prototype.add = function (otherSize) {
  2440. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2441. return r;
  2442. };
  2443. /**
  2444. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2445. */
  2446. Size.prototype.subtract = function (otherSize) {
  2447. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2448. return r;
  2449. };
  2450. /**
  2451. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2452. */
  2453. Size.Lerp = function (start, end, amount) {
  2454. var w = start.width + ((end.width - start.width) * amount);
  2455. var h = start.height + ((end.height - start.height) * amount);
  2456. return new Size(w, h);
  2457. };
  2458. return Size;
  2459. }());
  2460. BABYLON.Size = Size;
  2461. var Quaternion = (function () {
  2462. /**
  2463. * Creates a new Quaternion from the passed floats.
  2464. */
  2465. function Quaternion(x, y, z, w) {
  2466. if (x === void 0) { x = 0.0; }
  2467. if (y === void 0) { y = 0.0; }
  2468. if (z === void 0) { z = 0.0; }
  2469. if (w === void 0) { w = 1.0; }
  2470. this.x = x;
  2471. this.y = y;
  2472. this.z = z;
  2473. this.w = w;
  2474. }
  2475. /**
  2476. * Returns a string with the Quaternion coordinates.
  2477. */
  2478. Quaternion.prototype.toString = function () {
  2479. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2480. };
  2481. /**
  2482. * Returns the string "Quaternion".
  2483. */
  2484. Quaternion.prototype.getClassName = function () {
  2485. return "Quaternion";
  2486. };
  2487. /**
  2488. * Returns the Quaternion hash code.
  2489. */
  2490. Quaternion.prototype.getHashCode = function () {
  2491. var hash = this.x || 0;
  2492. hash = (hash * 397) ^ (this.y || 0);
  2493. hash = (hash * 397) ^ (this.z || 0);
  2494. hash = (hash * 397) ^ (this.w || 0);
  2495. return hash;
  2496. };
  2497. /**
  2498. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2499. */
  2500. Quaternion.prototype.asArray = function () {
  2501. return [this.x, this.y, this.z, this.w];
  2502. };
  2503. /**
  2504. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2505. */
  2506. Quaternion.prototype.equals = function (otherQuaternion) {
  2507. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2508. };
  2509. /**
  2510. * Returns a new Quaternion copied from the current one.
  2511. */
  2512. Quaternion.prototype.clone = function () {
  2513. return new Quaternion(this.x, this.y, this.z, this.w);
  2514. };
  2515. /**
  2516. * Updates the current Quaternion from the passed one coordinates.
  2517. * Returns the updated Quaterion.
  2518. */
  2519. Quaternion.prototype.copyFrom = function (other) {
  2520. this.x = other.x;
  2521. this.y = other.y;
  2522. this.z = other.z;
  2523. this.w = other.w;
  2524. return this;
  2525. };
  2526. /**
  2527. * Updates the current Quaternion from the passed float coordinates.
  2528. * Returns the updated Quaterion.
  2529. */
  2530. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2531. this.x = x;
  2532. this.y = y;
  2533. this.z = z;
  2534. this.w = w;
  2535. return this;
  2536. };
  2537. /**
  2538. * Updates the current Quaternion from the passed float coordinates.
  2539. * Returns the updated Quaterion.
  2540. */
  2541. Quaternion.prototype.set = function (x, y, z, w) {
  2542. return this.copyFromFloats(x, y, z, w);
  2543. };
  2544. /**
  2545. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2546. */
  2547. Quaternion.prototype.add = function (other) {
  2548. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2549. };
  2550. /**
  2551. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2552. */
  2553. Quaternion.prototype.subtract = function (other) {
  2554. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2555. };
  2556. /**
  2557. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2558. */
  2559. Quaternion.prototype.scale = function (value) {
  2560. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2561. };
  2562. /**
  2563. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2564. */
  2565. Quaternion.prototype.multiply = function (q1) {
  2566. var result = new Quaternion(0, 0, 0, 1.0);
  2567. this.multiplyToRef(q1, result);
  2568. return result;
  2569. };
  2570. /**
  2571. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2572. * Returns the current Quaternion.
  2573. */
  2574. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2575. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2576. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2577. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2578. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2579. result.copyFromFloats(x, y, z, w);
  2580. return this;
  2581. };
  2582. /**
  2583. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2584. * Returns the updated Quaternion.
  2585. */
  2586. Quaternion.prototype.multiplyInPlace = function (q1) {
  2587. this.multiplyToRef(q1, this);
  2588. return this;
  2589. };
  2590. /**
  2591. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2592. * Returns the current Quaternion.
  2593. */
  2594. Quaternion.prototype.conjugateToRef = function (ref) {
  2595. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2596. return this;
  2597. };
  2598. /**
  2599. * Conjugates in place the current Quaternion.
  2600. * Returns the updated Quaternion.
  2601. */
  2602. Quaternion.prototype.conjugateInPlace = function () {
  2603. this.x *= -1;
  2604. this.y *= -1;
  2605. this.z *= -1;
  2606. return this;
  2607. };
  2608. /**
  2609. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2610. */
  2611. Quaternion.prototype.conjugate = function () {
  2612. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2613. return result;
  2614. };
  2615. /**
  2616. * Returns the Quaternion length (float).
  2617. */
  2618. Quaternion.prototype.length = function () {
  2619. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2620. };
  2621. /**
  2622. * Normalize in place the current Quaternion.
  2623. * Returns the updated Quaternion.
  2624. */
  2625. Quaternion.prototype.normalize = function () {
  2626. var length = 1.0 / this.length();
  2627. this.x *= length;
  2628. this.y *= length;
  2629. this.z *= length;
  2630. this.w *= length;
  2631. return this;
  2632. };
  2633. /**
  2634. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2635. */
  2636. Quaternion.prototype.toEulerAngles = function (order) {
  2637. if (order === void 0) { order = "YZX"; }
  2638. var result = Vector3.Zero();
  2639. this.toEulerAnglesToRef(result, order);
  2640. return result;
  2641. };
  2642. /**
  2643. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2644. * Returns the current Quaternion.
  2645. */
  2646. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2647. if (order === void 0) { order = "YZX"; }
  2648. var qz = this.z;
  2649. var qx = this.x;
  2650. var qy = this.y;
  2651. var qw = this.w;
  2652. var sqw = qw * qw;
  2653. var sqz = qz * qz;
  2654. var sqx = qx * qx;
  2655. var sqy = qy * qy;
  2656. var zAxisY = qy * qz - qx * qw;
  2657. var limit = .4999999;
  2658. if (zAxisY < -limit) {
  2659. result.y = 2 * Math.atan2(qy, qw);
  2660. result.x = Math.PI / 2;
  2661. result.z = 0;
  2662. }
  2663. else if (zAxisY > limit) {
  2664. result.y = 2 * Math.atan2(qy, qw);
  2665. result.x = -Math.PI / 2;
  2666. result.z = 0;
  2667. }
  2668. else {
  2669. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2670. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2671. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2672. }
  2673. return this;
  2674. };
  2675. /**
  2676. * Updates the passed rotation matrix with the current Quaternion values.
  2677. * Returns the current Quaternion.
  2678. */
  2679. Quaternion.prototype.toRotationMatrix = function (result) {
  2680. var xx = this.x * this.x;
  2681. var yy = this.y * this.y;
  2682. var zz = this.z * this.z;
  2683. var xy = this.x * this.y;
  2684. var zw = this.z * this.w;
  2685. var zx = this.z * this.x;
  2686. var yw = this.y * this.w;
  2687. var yz = this.y * this.z;
  2688. var xw = this.x * this.w;
  2689. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2690. result.m[1] = 2.0 * (xy + zw);
  2691. result.m[2] = 2.0 * (zx - yw);
  2692. result.m[3] = 0;
  2693. result.m[4] = 2.0 * (xy - zw);
  2694. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2695. result.m[6] = 2.0 * (yz + xw);
  2696. result.m[7] = 0;
  2697. result.m[8] = 2.0 * (zx + yw);
  2698. result.m[9] = 2.0 * (yz - xw);
  2699. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2700. result.m[11] = 0;
  2701. result.m[12] = 0;
  2702. result.m[13] = 0;
  2703. result.m[14] = 0;
  2704. result.m[15] = 1.0;
  2705. result._markAsUpdated();
  2706. return this;
  2707. };
  2708. /**
  2709. * Updates the current Quaternion from the passed rotation matrix values.
  2710. * Returns the updated Quaternion.
  2711. */
  2712. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2713. Quaternion.FromRotationMatrixToRef(matrix, this);
  2714. return this;
  2715. };
  2716. // Statics
  2717. /**
  2718. * Returns a new Quaternion set from the passed rotation matrix values.
  2719. */
  2720. Quaternion.FromRotationMatrix = function (matrix) {
  2721. var result = new Quaternion();
  2722. Quaternion.FromRotationMatrixToRef(matrix, result);
  2723. return result;
  2724. };
  2725. /**
  2726. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2727. */
  2728. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2729. var data = matrix.m;
  2730. var m11 = data[0], m12 = data[4], m13 = data[8];
  2731. var m21 = data[1], m22 = data[5], m23 = data[9];
  2732. var m31 = data[2], m32 = data[6], m33 = data[10];
  2733. var trace = m11 + m22 + m33;
  2734. var s;
  2735. if (trace > 0) {
  2736. s = 0.5 / Math.sqrt(trace + 1.0);
  2737. result.w = 0.25 / s;
  2738. result.x = (m32 - m23) * s;
  2739. result.y = (m13 - m31) * s;
  2740. result.z = (m21 - m12) * s;
  2741. }
  2742. else if (m11 > m22 && m11 > m33) {
  2743. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2744. result.w = (m32 - m23) / s;
  2745. result.x = 0.25 * s;
  2746. result.y = (m12 + m21) / s;
  2747. result.z = (m13 + m31) / s;
  2748. }
  2749. else if (m22 > m33) {
  2750. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2751. result.w = (m13 - m31) / s;
  2752. result.x = (m12 + m21) / s;
  2753. result.y = 0.25 * s;
  2754. result.z = (m23 + m32) / s;
  2755. }
  2756. else {
  2757. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2758. result.w = (m21 - m12) / s;
  2759. result.x = (m13 + m31) / s;
  2760. result.y = (m23 + m32) / s;
  2761. result.z = 0.25 * s;
  2762. }
  2763. };
  2764. /**
  2765. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2766. */
  2767. Quaternion.Zero = function () {
  2768. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2769. };
  2770. /**
  2771. * Returns a new Quaternion as the inverted current Quaternion.
  2772. */
  2773. Quaternion.Inverse = function (q) {
  2774. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2775. };
  2776. /**
  2777. * Returns the identity Quaternion.
  2778. */
  2779. Quaternion.Identity = function () {
  2780. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2781. };
  2782. Quaternion.IsIdentity = function (quaternion) {
  2783. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2784. };
  2785. /**
  2786. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2787. */
  2788. Quaternion.RotationAxis = function (axis, angle) {
  2789. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2790. };
  2791. /**
  2792. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2793. */
  2794. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2795. var sin = Math.sin(angle / 2);
  2796. axis.normalize();
  2797. result.w = Math.cos(angle / 2);
  2798. result.x = axis.x * sin;
  2799. result.y = axis.y * sin;
  2800. result.z = axis.z * sin;
  2801. return result;
  2802. };
  2803. /**
  2804. * Retuns a new Quaternion set from the starting index of the passed array.
  2805. */
  2806. Quaternion.FromArray = function (array, offset) {
  2807. if (!offset) {
  2808. offset = 0;
  2809. }
  2810. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2811. };
  2812. /**
  2813. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2814. */
  2815. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2816. var q = new Quaternion();
  2817. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2818. return q;
  2819. };
  2820. /**
  2821. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2822. */
  2823. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2824. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2825. var halfRoll = roll * 0.5;
  2826. var halfPitch = pitch * 0.5;
  2827. var halfYaw = yaw * 0.5;
  2828. var sinRoll = Math.sin(halfRoll);
  2829. var cosRoll = Math.cos(halfRoll);
  2830. var sinPitch = Math.sin(halfPitch);
  2831. var cosPitch = Math.cos(halfPitch);
  2832. var sinYaw = Math.sin(halfYaw);
  2833. var cosYaw = Math.cos(halfYaw);
  2834. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2835. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2836. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2837. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2838. };
  2839. /**
  2840. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2841. */
  2842. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2843. var result = new Quaternion();
  2844. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2845. return result;
  2846. };
  2847. /**
  2848. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2849. */
  2850. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2851. // Produces a quaternion from Euler angles in the z-x-z orientation
  2852. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2853. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2854. var halfBeta = beta * 0.5;
  2855. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2856. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2857. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2858. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2859. };
  2860. /**
  2861. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2862. * cf to Vector3.RotationFromAxis() documentation.
  2863. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2864. */
  2865. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2866. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2867. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2868. return quat;
  2869. };
  2870. /**
  2871. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2872. * cf to Vector3.RotationFromAxis() documentation.
  2873. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2874. */
  2875. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2876. var rotMat = MathTmp.Matrix[0];
  2877. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2878. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2879. };
  2880. Quaternion.Slerp = function (left, right, amount) {
  2881. var result = Quaternion.Identity();
  2882. Quaternion.SlerpToRef(left, right, amount, result);
  2883. return result;
  2884. };
  2885. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2886. var num2;
  2887. var num3;
  2888. var num = amount;
  2889. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2890. var flag = false;
  2891. if (num4 < 0) {
  2892. flag = true;
  2893. num4 = -num4;
  2894. }
  2895. if (num4 > 0.999999) {
  2896. num3 = 1 - num;
  2897. num2 = flag ? -num : num;
  2898. }
  2899. else {
  2900. var num5 = Math.acos(num4);
  2901. var num6 = (1.0 / Math.sin(num5));
  2902. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2903. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2904. }
  2905. result.x = (num3 * left.x) + (num2 * right.x);
  2906. result.y = (num3 * left.y) + (num2 * right.y);
  2907. result.z = (num3 * left.z) + (num2 * right.z);
  2908. result.w = (num3 * left.w) + (num2 * right.w);
  2909. };
  2910. /**
  2911. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2912. */
  2913. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2914. var squared = amount * amount;
  2915. var cubed = amount * squared;
  2916. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2917. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2918. var part3 = (cubed - (2.0 * squared)) + amount;
  2919. var part4 = cubed - squared;
  2920. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2921. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2922. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2923. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2924. return new Quaternion(x, y, z, w);
  2925. };
  2926. return Quaternion;
  2927. }());
  2928. BABYLON.Quaternion = Quaternion;
  2929. var Matrix = (function () {
  2930. function Matrix() {
  2931. this._isIdentity = false;
  2932. this._isIdentityDirty = true;
  2933. this.m = new Float32Array(16);
  2934. this._markAsUpdated();
  2935. }
  2936. Matrix.prototype._markAsUpdated = function () {
  2937. this.updateFlag = Matrix._updateFlagSeed++;
  2938. this._isIdentityDirty = true;
  2939. };
  2940. // Properties
  2941. /**
  2942. * Boolean : True is the matrix is the identity matrix
  2943. */
  2944. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2945. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2946. if (this._isIdentityDirty) {
  2947. this._isIdentityDirty = false;
  2948. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2949. this._isIdentity = false;
  2950. }
  2951. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2952. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2953. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2954. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2955. this._isIdentity = false;
  2956. }
  2957. else {
  2958. this._isIdentity = true;
  2959. }
  2960. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2961. this._isIdentity = false;
  2962. }
  2963. }
  2964. return this._isIdentity;
  2965. };
  2966. /**
  2967. * Returns the matrix determinant (float).
  2968. */
  2969. Matrix.prototype.determinant = function () {
  2970. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2971. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2972. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2973. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2974. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2975. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2976. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2977. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2978. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2979. };
  2980. // Methods
  2981. /**
  2982. * Returns the matrix underlying array.
  2983. */
  2984. Matrix.prototype.toArray = function () {
  2985. return this.m;
  2986. };
  2987. /**
  2988. * Returns the matrix underlying array.
  2989. */
  2990. Matrix.prototype.asArray = function () {
  2991. return this.toArray();
  2992. };
  2993. /**
  2994. * Inverts in place the Matrix.
  2995. * Returns the Matrix inverted.
  2996. */
  2997. Matrix.prototype.invert = function () {
  2998. this.invertToRef(this);
  2999. return this;
  3000. };
  3001. /**
  3002. * Sets all the matrix elements to zero.
  3003. * Returns the Matrix.
  3004. */
  3005. Matrix.prototype.reset = function () {
  3006. for (var index = 0; index < 16; index++) {
  3007. this.m[index] = 0.0;
  3008. }
  3009. this._markAsUpdated();
  3010. return this;
  3011. };
  3012. /**
  3013. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  3014. */
  3015. Matrix.prototype.add = function (other) {
  3016. var result = new Matrix();
  3017. this.addToRef(other, result);
  3018. return result;
  3019. };
  3020. /**
  3021. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  3022. * Returns the Matrix.
  3023. */
  3024. Matrix.prototype.addToRef = function (other, result) {
  3025. for (var index = 0; index < 16; index++) {
  3026. result.m[index] = this.m[index] + other.m[index];
  3027. }
  3028. result._markAsUpdated();
  3029. return this;
  3030. };
  3031. /**
  3032. * Adds in place the passed matrix to the current Matrix.
  3033. * Returns the updated Matrix.
  3034. */
  3035. Matrix.prototype.addToSelf = function (other) {
  3036. for (var index = 0; index < 16; index++) {
  3037. this.m[index] += other.m[index];
  3038. }
  3039. this._markAsUpdated();
  3040. return this;
  3041. };
  3042. /**
  3043. * Sets the passed matrix with the current inverted Matrix.
  3044. * Returns the unmodified current Matrix.
  3045. */
  3046. Matrix.prototype.invertToRef = function (other) {
  3047. var l1 = this.m[0];
  3048. var l2 = this.m[1];
  3049. var l3 = this.m[2];
  3050. var l4 = this.m[3];
  3051. var l5 = this.m[4];
  3052. var l6 = this.m[5];
  3053. var l7 = this.m[6];
  3054. var l8 = this.m[7];
  3055. var l9 = this.m[8];
  3056. var l10 = this.m[9];
  3057. var l11 = this.m[10];
  3058. var l12 = this.m[11];
  3059. var l13 = this.m[12];
  3060. var l14 = this.m[13];
  3061. var l15 = this.m[14];
  3062. var l16 = this.m[15];
  3063. var l17 = (l11 * l16) - (l12 * l15);
  3064. var l18 = (l10 * l16) - (l12 * l14);
  3065. var l19 = (l10 * l15) - (l11 * l14);
  3066. var l20 = (l9 * l16) - (l12 * l13);
  3067. var l21 = (l9 * l15) - (l11 * l13);
  3068. var l22 = (l9 * l14) - (l10 * l13);
  3069. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3070. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3071. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3072. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3073. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3074. var l28 = (l7 * l16) - (l8 * l15);
  3075. var l29 = (l6 * l16) - (l8 * l14);
  3076. var l30 = (l6 * l15) - (l7 * l14);
  3077. var l31 = (l5 * l16) - (l8 * l13);
  3078. var l32 = (l5 * l15) - (l7 * l13);
  3079. var l33 = (l5 * l14) - (l6 * l13);
  3080. var l34 = (l7 * l12) - (l8 * l11);
  3081. var l35 = (l6 * l12) - (l8 * l10);
  3082. var l36 = (l6 * l11) - (l7 * l10);
  3083. var l37 = (l5 * l12) - (l8 * l9);
  3084. var l38 = (l5 * l11) - (l7 * l9);
  3085. var l39 = (l5 * l10) - (l6 * l9);
  3086. other.m[0] = l23 * l27;
  3087. other.m[4] = l24 * l27;
  3088. other.m[8] = l25 * l27;
  3089. other.m[12] = l26 * l27;
  3090. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3091. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3092. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3093. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3094. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3095. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3096. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3097. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3098. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3099. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3100. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3101. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3102. other._markAsUpdated();
  3103. return this;
  3104. };
  3105. /**
  3106. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3107. * Returns the updated Matrix.
  3108. */
  3109. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3110. this.m[12] = x;
  3111. this.m[13] = y;
  3112. this.m[14] = z;
  3113. this._markAsUpdated();
  3114. return this;
  3115. };
  3116. /**
  3117. * Inserts the translation vector in the current Matrix.
  3118. * Returns the updated Matrix.
  3119. */
  3120. Matrix.prototype.setTranslation = function (vector3) {
  3121. this.m[12] = vector3.x;
  3122. this.m[13] = vector3.y;
  3123. this.m[14] = vector3.z;
  3124. this._markAsUpdated();
  3125. return this;
  3126. };
  3127. /**
  3128. * Returns a new Vector3 as the extracted translation from the Matrix.
  3129. */
  3130. Matrix.prototype.getTranslation = function () {
  3131. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3132. };
  3133. /**
  3134. * Fill a Vector3 with the extracted translation from the Matrix.
  3135. */
  3136. Matrix.prototype.getTranslationToRef = function (result) {
  3137. result.x = this.m[12];
  3138. result.y = this.m[13];
  3139. result.z = this.m[14];
  3140. return this;
  3141. };
  3142. /**
  3143. * Remove rotation and scaling part from the Matrix.
  3144. * Returns the updated Matrix.
  3145. */
  3146. Matrix.prototype.removeRotationAndScaling = function () {
  3147. this.setRowFromFloats(0, 1, 0, 0, 0);
  3148. this.setRowFromFloats(1, 0, 1, 0, 0);
  3149. this.setRowFromFloats(2, 0, 0, 1, 0);
  3150. return this;
  3151. };
  3152. /**
  3153. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3154. */
  3155. Matrix.prototype.multiply = function (other) {
  3156. var result = new Matrix();
  3157. this.multiplyToRef(other, result);
  3158. return result;
  3159. };
  3160. /**
  3161. * Updates the current Matrix from the passed one values.
  3162. * Returns the updated Matrix.
  3163. */
  3164. Matrix.prototype.copyFrom = function (other) {
  3165. for (var index = 0; index < 16; index++) {
  3166. this.m[index] = other.m[index];
  3167. }
  3168. this._markAsUpdated();
  3169. return this;
  3170. };
  3171. /**
  3172. * Populates the passed array from the starting index with the Matrix values.
  3173. * Returns the Matrix.
  3174. */
  3175. Matrix.prototype.copyToArray = function (array, offset) {
  3176. if (offset === void 0) { offset = 0; }
  3177. for (var index = 0; index < 16; index++) {
  3178. array[offset + index] = this.m[index];
  3179. }
  3180. return this;
  3181. };
  3182. /**
  3183. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3184. */
  3185. Matrix.prototype.multiplyToRef = function (other, result) {
  3186. this.multiplyToArray(other, result.m, 0);
  3187. result._markAsUpdated();
  3188. return this;
  3189. };
  3190. /**
  3191. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3192. */
  3193. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3194. var tm0 = this.m[0];
  3195. var tm1 = this.m[1];
  3196. var tm2 = this.m[2];
  3197. var tm3 = this.m[3];
  3198. var tm4 = this.m[4];
  3199. var tm5 = this.m[5];
  3200. var tm6 = this.m[6];
  3201. var tm7 = this.m[7];
  3202. var tm8 = this.m[8];
  3203. var tm9 = this.m[9];
  3204. var tm10 = this.m[10];
  3205. var tm11 = this.m[11];
  3206. var tm12 = this.m[12];
  3207. var tm13 = this.m[13];
  3208. var tm14 = this.m[14];
  3209. var tm15 = this.m[15];
  3210. var om0 = other.m[0];
  3211. var om1 = other.m[1];
  3212. var om2 = other.m[2];
  3213. var om3 = other.m[3];
  3214. var om4 = other.m[4];
  3215. var om5 = other.m[5];
  3216. var om6 = other.m[6];
  3217. var om7 = other.m[7];
  3218. var om8 = other.m[8];
  3219. var om9 = other.m[9];
  3220. var om10 = other.m[10];
  3221. var om11 = other.m[11];
  3222. var om12 = other.m[12];
  3223. var om13 = other.m[13];
  3224. var om14 = other.m[14];
  3225. var om15 = other.m[15];
  3226. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3227. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3228. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3229. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3230. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3231. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3232. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3233. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3234. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3235. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3236. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3237. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3238. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3239. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3240. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3241. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3242. return this;
  3243. };
  3244. /**
  3245. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3246. */
  3247. Matrix.prototype.equals = function (value) {
  3248. return value &&
  3249. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3250. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3251. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3252. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3253. };
  3254. /**
  3255. * Returns a new Matrix from the current Matrix.
  3256. */
  3257. Matrix.prototype.clone = function () {
  3258. 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]);
  3259. };
  3260. /**
  3261. * Returns the string "Matrix"
  3262. */
  3263. Matrix.prototype.getClassName = function () {
  3264. return "Matrix";
  3265. };
  3266. /**
  3267. * Returns the Matrix hash code.
  3268. */
  3269. Matrix.prototype.getHashCode = function () {
  3270. var hash = this.m[0] || 0;
  3271. for (var i = 1; i < 16; i++) {
  3272. hash = (hash * 397) ^ (this.m[i] || 0);
  3273. }
  3274. return hash;
  3275. };
  3276. /**
  3277. * Decomposes the current Matrix into :
  3278. * - a scale vector3 passed as a reference to update,
  3279. * - a rotation quaternion passed as a reference to update,
  3280. * - a translation vector3 passed as a reference to update.
  3281. * Returns the boolean `true`.
  3282. */
  3283. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3284. translation.x = this.m[12];
  3285. translation.y = this.m[13];
  3286. translation.z = this.m[14];
  3287. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3288. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3289. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3290. if (this.determinant() <= 0) {
  3291. scale.y *= -1;
  3292. }
  3293. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3294. rotation.x = 0;
  3295. rotation.y = 0;
  3296. rotation.z = 0;
  3297. rotation.w = 1;
  3298. return false;
  3299. }
  3300. 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]);
  3301. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3302. return true;
  3303. };
  3304. /**
  3305. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3306. */
  3307. Matrix.prototype.getRotationMatrix = function () {
  3308. var result = Matrix.Identity();
  3309. this.getRotationMatrixToRef(result);
  3310. return result;
  3311. };
  3312. /**
  3313. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3314. * Returns the current Matrix.
  3315. */
  3316. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3317. var m = this.m;
  3318. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3319. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3320. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3321. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3322. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3323. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3324. 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);
  3325. return this;
  3326. };
  3327. // Statics
  3328. /**
  3329. * Returns a new Matrix set from the starting index of the passed array.
  3330. */
  3331. Matrix.FromArray = function (array, offset) {
  3332. var result = new Matrix();
  3333. if (!offset) {
  3334. offset = 0;
  3335. }
  3336. Matrix.FromArrayToRef(array, offset, result);
  3337. return result;
  3338. };
  3339. /**
  3340. * Sets the passed "result" matrix from the starting index of the passed array.
  3341. */
  3342. Matrix.FromArrayToRef = function (array, offset, result) {
  3343. for (var index = 0; index < 16; index++) {
  3344. result.m[index] = array[index + offset];
  3345. }
  3346. result._markAsUpdated();
  3347. };
  3348. /**
  3349. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3350. */
  3351. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3352. for (var index = 0; index < 16; index++) {
  3353. result.m[index] = array[index + offset] * scale;
  3354. }
  3355. result._markAsUpdated();
  3356. };
  3357. /**
  3358. * Sets the passed matrix "result" with the 16 passed floats.
  3359. */
  3360. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3361. result.m[0] = initialM11;
  3362. result.m[1] = initialM12;
  3363. result.m[2] = initialM13;
  3364. result.m[3] = initialM14;
  3365. result.m[4] = initialM21;
  3366. result.m[5] = initialM22;
  3367. result.m[6] = initialM23;
  3368. result.m[7] = initialM24;
  3369. result.m[8] = initialM31;
  3370. result.m[9] = initialM32;
  3371. result.m[10] = initialM33;
  3372. result.m[11] = initialM34;
  3373. result.m[12] = initialM41;
  3374. result.m[13] = initialM42;
  3375. result.m[14] = initialM43;
  3376. result.m[15] = initialM44;
  3377. result._markAsUpdated();
  3378. };
  3379. /**
  3380. * Returns the index-th row of the current matrix as a new Vector4.
  3381. */
  3382. Matrix.prototype.getRow = function (index) {
  3383. if (index < 0 || index > 3) {
  3384. return null;
  3385. }
  3386. var i = index * 4;
  3387. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3388. };
  3389. /**
  3390. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3391. * Returns the updated Matrix.
  3392. */
  3393. Matrix.prototype.setRow = function (index, row) {
  3394. if (index < 0 || index > 3) {
  3395. return this;
  3396. }
  3397. var i = index * 4;
  3398. this.m[i + 0] = row.x;
  3399. this.m[i + 1] = row.y;
  3400. this.m[i + 2] = row.z;
  3401. this.m[i + 3] = row.w;
  3402. this._markAsUpdated();
  3403. return this;
  3404. };
  3405. /**
  3406. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3407. * Returns the updated Matrix.
  3408. */
  3409. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3410. if (index < 0 || index > 3) {
  3411. return this;
  3412. }
  3413. var i = index * 4;
  3414. this.m[i + 0] = x;
  3415. this.m[i + 1] = y;
  3416. this.m[i + 2] = z;
  3417. this.m[i + 3] = w;
  3418. this._markAsUpdated();
  3419. return this;
  3420. };
  3421. /**
  3422. * Returns a new Matrix set from the 16 passed floats.
  3423. */
  3424. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3425. var result = new Matrix();
  3426. result.m[0] = initialM11;
  3427. result.m[1] = initialM12;
  3428. result.m[2] = initialM13;
  3429. result.m[3] = initialM14;
  3430. result.m[4] = initialM21;
  3431. result.m[5] = initialM22;
  3432. result.m[6] = initialM23;
  3433. result.m[7] = initialM24;
  3434. result.m[8] = initialM31;
  3435. result.m[9] = initialM32;
  3436. result.m[10] = initialM33;
  3437. result.m[11] = initialM34;
  3438. result.m[12] = initialM41;
  3439. result.m[13] = initialM42;
  3440. result.m[14] = initialM43;
  3441. result.m[15] = initialM44;
  3442. return result;
  3443. };
  3444. /**
  3445. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3446. */
  3447. Matrix.Compose = function (scale, rotation, translation) {
  3448. var result = Matrix.Identity();
  3449. Matrix.ComposeToRef(scale, rotation, translation, result);
  3450. return result;
  3451. };
  3452. /**
  3453. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3454. */
  3455. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3456. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3457. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3458. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3459. result.setTranslation(translation);
  3460. };
  3461. /**
  3462. * Returns a new indentity Matrix.
  3463. */
  3464. Matrix.Identity = function () {
  3465. 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);
  3466. };
  3467. /**
  3468. * Sets the passed "result" as an identity matrix.
  3469. */
  3470. Matrix.IdentityToRef = function (result) {
  3471. 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);
  3472. };
  3473. /**
  3474. * Returns a new zero Matrix.
  3475. */
  3476. Matrix.Zero = function () {
  3477. 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);
  3478. };
  3479. /**
  3480. * Returns a new rotation matrix for "angle" radians around the X axis.
  3481. */
  3482. Matrix.RotationX = function (angle) {
  3483. var result = new Matrix();
  3484. Matrix.RotationXToRef(angle, result);
  3485. return result;
  3486. };
  3487. /**
  3488. * Returns a new Matrix as the passed inverted one.
  3489. */
  3490. Matrix.Invert = function (source) {
  3491. var result = new Matrix();
  3492. source.invertToRef(result);
  3493. return result;
  3494. };
  3495. /**
  3496. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3497. */
  3498. Matrix.RotationXToRef = function (angle, result) {
  3499. var s = Math.sin(angle);
  3500. var c = Math.cos(angle);
  3501. result.m[0] = 1.0;
  3502. result.m[15] = 1.0;
  3503. result.m[5] = c;
  3504. result.m[10] = c;
  3505. result.m[9] = -s;
  3506. result.m[6] = s;
  3507. result.m[1] = 0.0;
  3508. result.m[2] = 0.0;
  3509. result.m[3] = 0.0;
  3510. result.m[4] = 0.0;
  3511. result.m[7] = 0.0;
  3512. result.m[8] = 0.0;
  3513. result.m[11] = 0.0;
  3514. result.m[12] = 0.0;
  3515. result.m[13] = 0.0;
  3516. result.m[14] = 0.0;
  3517. result._markAsUpdated();
  3518. };
  3519. /**
  3520. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3521. */
  3522. Matrix.RotationY = function (angle) {
  3523. var result = new Matrix();
  3524. Matrix.RotationYToRef(angle, result);
  3525. return result;
  3526. };
  3527. /**
  3528. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3529. */
  3530. Matrix.RotationYToRef = function (angle, result) {
  3531. var s = Math.sin(angle);
  3532. var c = Math.cos(angle);
  3533. result.m[5] = 1.0;
  3534. result.m[15] = 1.0;
  3535. result.m[0] = c;
  3536. result.m[2] = -s;
  3537. result.m[8] = s;
  3538. result.m[10] = c;
  3539. result.m[1] = 0.0;
  3540. result.m[3] = 0.0;
  3541. result.m[4] = 0.0;
  3542. result.m[6] = 0.0;
  3543. result.m[7] = 0.0;
  3544. result.m[9] = 0.0;
  3545. result.m[11] = 0.0;
  3546. result.m[12] = 0.0;
  3547. result.m[13] = 0.0;
  3548. result.m[14] = 0.0;
  3549. result._markAsUpdated();
  3550. };
  3551. /**
  3552. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3553. */
  3554. Matrix.RotationZ = function (angle) {
  3555. var result = new Matrix();
  3556. Matrix.RotationZToRef(angle, result);
  3557. return result;
  3558. };
  3559. /**
  3560. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3561. */
  3562. Matrix.RotationZToRef = function (angle, result) {
  3563. var s = Math.sin(angle);
  3564. var c = Math.cos(angle);
  3565. result.m[10] = 1.0;
  3566. result.m[15] = 1.0;
  3567. result.m[0] = c;
  3568. result.m[1] = s;
  3569. result.m[4] = -s;
  3570. result.m[5] = c;
  3571. result.m[2] = 0.0;
  3572. result.m[3] = 0.0;
  3573. result.m[6] = 0.0;
  3574. result.m[7] = 0.0;
  3575. result.m[8] = 0.0;
  3576. result.m[9] = 0.0;
  3577. result.m[11] = 0.0;
  3578. result.m[12] = 0.0;
  3579. result.m[13] = 0.0;
  3580. result.m[14] = 0.0;
  3581. result._markAsUpdated();
  3582. };
  3583. /**
  3584. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3585. */
  3586. Matrix.RotationAxis = function (axis, angle) {
  3587. var result = Matrix.Zero();
  3588. Matrix.RotationAxisToRef(axis, angle, result);
  3589. return result;
  3590. };
  3591. /**
  3592. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3593. */
  3594. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3595. var s = Math.sin(-angle);
  3596. var c = Math.cos(-angle);
  3597. var c1 = 1 - c;
  3598. axis.normalize();
  3599. result.m[0] = (axis.x * axis.x) * c1 + c;
  3600. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3601. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3602. result.m[3] = 0.0;
  3603. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3604. result.m[5] = (axis.y * axis.y) * c1 + c;
  3605. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3606. result.m[7] = 0.0;
  3607. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3608. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3609. result.m[10] = (axis.z * axis.z) * c1 + c;
  3610. result.m[11] = 0.0;
  3611. result.m[15] = 1.0;
  3612. result._markAsUpdated();
  3613. };
  3614. /**
  3615. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3616. */
  3617. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3618. var result = new Matrix();
  3619. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3620. return result;
  3621. };
  3622. /**
  3623. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3624. */
  3625. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3626. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3627. this._tempQuaternion.toRotationMatrix(result);
  3628. };
  3629. /**
  3630. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3631. */
  3632. Matrix.Scaling = function (x, y, z) {
  3633. var result = Matrix.Zero();
  3634. Matrix.ScalingToRef(x, y, z, result);
  3635. return result;
  3636. };
  3637. /**
  3638. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3639. */
  3640. Matrix.ScalingToRef = function (x, y, z, result) {
  3641. result.m[0] = x;
  3642. result.m[1] = 0.0;
  3643. result.m[2] = 0.0;
  3644. result.m[3] = 0.0;
  3645. result.m[4] = 0.0;
  3646. result.m[5] = y;
  3647. result.m[6] = 0.0;
  3648. result.m[7] = 0.0;
  3649. result.m[8] = 0.0;
  3650. result.m[9] = 0.0;
  3651. result.m[10] = z;
  3652. result.m[11] = 0.0;
  3653. result.m[12] = 0.0;
  3654. result.m[13] = 0.0;
  3655. result.m[14] = 0.0;
  3656. result.m[15] = 1.0;
  3657. result._markAsUpdated();
  3658. };
  3659. /**
  3660. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3661. */
  3662. Matrix.Translation = function (x, y, z) {
  3663. var result = Matrix.Identity();
  3664. Matrix.TranslationToRef(x, y, z, result);
  3665. return result;
  3666. };
  3667. /**
  3668. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3669. */
  3670. Matrix.TranslationToRef = function (x, y, z, result) {
  3671. 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);
  3672. };
  3673. /**
  3674. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3675. */
  3676. Matrix.Lerp = function (startValue, endValue, gradient) {
  3677. var result = Matrix.Zero();
  3678. for (var index = 0; index < 16; index++) {
  3679. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3680. }
  3681. result._markAsUpdated();
  3682. return result;
  3683. };
  3684. /**
  3685. * Returns a new Matrix whose values are computed by :
  3686. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3687. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3688. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3689. */
  3690. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3691. var startScale = new Vector3(0, 0, 0);
  3692. var startRotation = new Quaternion();
  3693. var startTranslation = new Vector3(0, 0, 0);
  3694. startValue.decompose(startScale, startRotation, startTranslation);
  3695. var endScale = new Vector3(0, 0, 0);
  3696. var endRotation = new Quaternion();
  3697. var endTranslation = new Vector3(0, 0, 0);
  3698. endValue.decompose(endScale, endRotation, endTranslation);
  3699. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3700. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3701. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3702. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3703. };
  3704. /**
  3705. * 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".
  3706. * This methods works for a Left-Handed system.
  3707. */
  3708. Matrix.LookAtLH = function (eye, target, up) {
  3709. var result = Matrix.Zero();
  3710. Matrix.LookAtLHToRef(eye, target, up, result);
  3711. return result;
  3712. };
  3713. /**
  3714. * 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".
  3715. * This methods works for a Left-Handed system.
  3716. */
  3717. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3718. // Z axis
  3719. target.subtractToRef(eye, this._zAxis);
  3720. this._zAxis.normalize();
  3721. // X axis
  3722. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3723. if (this._xAxis.lengthSquared() === 0) {
  3724. this._xAxis.x = 1.0;
  3725. }
  3726. else {
  3727. this._xAxis.normalize();
  3728. }
  3729. // Y axis
  3730. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3731. this._yAxis.normalize();
  3732. // Eye angles
  3733. var ex = -Vector3.Dot(this._xAxis, eye);
  3734. var ey = -Vector3.Dot(this._yAxis, eye);
  3735. var ez = -Vector3.Dot(this._zAxis, eye);
  3736. 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);
  3737. };
  3738. /**
  3739. * 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".
  3740. * This methods works for a Right-Handed system.
  3741. */
  3742. Matrix.LookAtRH = function (eye, target, up) {
  3743. var result = Matrix.Zero();
  3744. Matrix.LookAtRHToRef(eye, target, up, result);
  3745. return result;
  3746. };
  3747. /**
  3748. * 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".
  3749. * This methods works for a Left-Handed system.
  3750. */
  3751. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3752. // Z axis
  3753. eye.subtractToRef(target, this._zAxis);
  3754. this._zAxis.normalize();
  3755. // X axis
  3756. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3757. if (this._xAxis.lengthSquared() === 0) {
  3758. this._xAxis.x = 1.0;
  3759. }
  3760. else {
  3761. this._xAxis.normalize();
  3762. }
  3763. // Y axis
  3764. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3765. this._yAxis.normalize();
  3766. // Eye angles
  3767. var ex = -Vector3.Dot(this._xAxis, eye);
  3768. var ey = -Vector3.Dot(this._yAxis, eye);
  3769. var ez = -Vector3.Dot(this._zAxis, eye);
  3770. 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);
  3771. };
  3772. /**
  3773. * 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.
  3774. */
  3775. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3776. var matrix = Matrix.Zero();
  3777. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3778. return matrix;
  3779. };
  3780. /**
  3781. * 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.
  3782. */
  3783. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3784. var n = znear;
  3785. var f = zfar;
  3786. var a = 2.0 / width;
  3787. var b = 2.0 / height;
  3788. var c = 2.0 / (f - n);
  3789. var d = -(f + n) / (f - n);
  3790. 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);
  3791. };
  3792. /**
  3793. * 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.
  3794. */
  3795. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3796. var matrix = Matrix.Zero();
  3797. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3798. return matrix;
  3799. };
  3800. /**
  3801. * 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.
  3802. */
  3803. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3804. var n = znear;
  3805. var f = zfar;
  3806. var a = 2.0 / (right - left);
  3807. var b = 2.0 / (top - bottom);
  3808. var c = 2.0 / (f - n);
  3809. var d = -(f + n) / (f - n);
  3810. var i0 = (left + right) / (left - right);
  3811. var i1 = (top + bottom) / (bottom - top);
  3812. 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);
  3813. };
  3814. /**
  3815. * 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.
  3816. */
  3817. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3818. var matrix = Matrix.Zero();
  3819. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3820. return matrix;
  3821. };
  3822. /**
  3823. * 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.
  3824. */
  3825. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3826. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3827. result.m[10] *= -1.0;
  3828. };
  3829. /**
  3830. * 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.
  3831. */
  3832. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3833. var matrix = Matrix.Zero();
  3834. var n = znear;
  3835. var f = zfar;
  3836. var a = 2.0 * n / width;
  3837. var b = 2.0 * n / height;
  3838. var c = (f + n) / (f - n);
  3839. var d = -2.0 * f * n / (f - n);
  3840. 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);
  3841. return matrix;
  3842. };
  3843. /**
  3844. * 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.
  3845. */
  3846. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3847. var matrix = Matrix.Zero();
  3848. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3849. return matrix;
  3850. };
  3851. /**
  3852. * 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.
  3853. */
  3854. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3855. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3856. var n = znear;
  3857. var f = zfar;
  3858. var t = 1.0 / (Math.tan(fov * 0.5));
  3859. var a = isVerticalFovFixed ? (t / aspect) : t;
  3860. var b = isVerticalFovFixed ? t : (t * aspect);
  3861. var c = (f + n) / (f - n);
  3862. var d = -2.0 * f * n / (f - n);
  3863. 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);
  3864. };
  3865. /**
  3866. * 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.
  3867. */
  3868. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3869. var matrix = Matrix.Zero();
  3870. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3871. return matrix;
  3872. };
  3873. /**
  3874. * 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.
  3875. */
  3876. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3877. //alternatively this could be expressed as:
  3878. // m = PerspectiveFovLHToRef
  3879. // m[10] *= -1.0;
  3880. // m[11] *= -1.0;
  3881. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3882. var n = znear;
  3883. var f = zfar;
  3884. var t = 1.0 / (Math.tan(fov * 0.5));
  3885. var a = isVerticalFovFixed ? (t / aspect) : t;
  3886. var b = isVerticalFovFixed ? t : (t * aspect);
  3887. var c = -(f + n) / (f - n);
  3888. var d = -2 * f * n / (f - n);
  3889. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3890. };
  3891. /**
  3892. * 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.
  3893. */
  3894. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3895. if (rightHanded === void 0) { rightHanded = false; }
  3896. var rightHandedFactor = rightHanded ? -1 : 1;
  3897. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3898. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3899. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3900. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3901. var xScale = 2.0 / (leftTan + rightTan);
  3902. var yScale = 2.0 / (upTan + downTan);
  3903. result.m[0] = xScale;
  3904. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3905. result.m[5] = yScale;
  3906. result.m[6] = result.m[7] = 0.0;
  3907. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3908. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3909. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3910. result.m[10] = -zfar / (znear - zfar);
  3911. result.m[11] = 1.0 * rightHandedFactor;
  3912. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3913. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3914. // result.m[14] = (znear * zfar) / (znear - zfar);
  3915. result._markAsUpdated();
  3916. };
  3917. /**
  3918. * Returns the final transformation matrix : world * view * projection * viewport
  3919. */
  3920. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3921. var cw = viewport.width;
  3922. var ch = viewport.height;
  3923. var cx = viewport.x;
  3924. var cy = viewport.y;
  3925. 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);
  3926. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3927. };
  3928. /**
  3929. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3930. */
  3931. Matrix.GetAsMatrix2x2 = function (matrix) {
  3932. return new Float32Array([
  3933. matrix.m[0], matrix.m[1],
  3934. matrix.m[4], matrix.m[5]
  3935. ]);
  3936. };
  3937. /**
  3938. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3939. */
  3940. Matrix.GetAsMatrix3x3 = function (matrix) {
  3941. return new Float32Array([
  3942. matrix.m[0], matrix.m[1], matrix.m[2],
  3943. matrix.m[4], matrix.m[5], matrix.m[6],
  3944. matrix.m[8], matrix.m[9], matrix.m[10]
  3945. ]);
  3946. };
  3947. /**
  3948. * Compute the transpose of the passed Matrix.
  3949. * Returns a new Matrix.
  3950. */
  3951. Matrix.Transpose = function (matrix) {
  3952. var result = new Matrix();
  3953. result.m[0] = matrix.m[0];
  3954. result.m[1] = matrix.m[4];
  3955. result.m[2] = matrix.m[8];
  3956. result.m[3] = matrix.m[12];
  3957. result.m[4] = matrix.m[1];
  3958. result.m[5] = matrix.m[5];
  3959. result.m[6] = matrix.m[9];
  3960. result.m[7] = matrix.m[13];
  3961. result.m[8] = matrix.m[2];
  3962. result.m[9] = matrix.m[6];
  3963. result.m[10] = matrix.m[10];
  3964. result.m[11] = matrix.m[14];
  3965. result.m[12] = matrix.m[3];
  3966. result.m[13] = matrix.m[7];
  3967. result.m[14] = matrix.m[11];
  3968. result.m[15] = matrix.m[15];
  3969. return result;
  3970. };
  3971. /**
  3972. * Returns a new Matrix as the reflection matrix across the passed plane.
  3973. */
  3974. Matrix.Reflection = function (plane) {
  3975. var matrix = new Matrix();
  3976. Matrix.ReflectionToRef(plane, matrix);
  3977. return matrix;
  3978. };
  3979. /**
  3980. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3981. */
  3982. Matrix.ReflectionToRef = function (plane, result) {
  3983. plane.normalize();
  3984. var x = plane.normal.x;
  3985. var y = plane.normal.y;
  3986. var z = plane.normal.z;
  3987. var temp = -2 * x;
  3988. var temp2 = -2 * y;
  3989. var temp3 = -2 * z;
  3990. result.m[0] = (temp * x) + 1;
  3991. result.m[1] = temp2 * x;
  3992. result.m[2] = temp3 * x;
  3993. result.m[3] = 0.0;
  3994. result.m[4] = temp * y;
  3995. result.m[5] = (temp2 * y) + 1;
  3996. result.m[6] = temp3 * y;
  3997. result.m[7] = 0.0;
  3998. result.m[8] = temp * z;
  3999. result.m[9] = temp2 * z;
  4000. result.m[10] = (temp3 * z) + 1;
  4001. result.m[11] = 0.0;
  4002. result.m[12] = temp * plane.d;
  4003. result.m[13] = temp2 * plane.d;
  4004. result.m[14] = temp3 * plane.d;
  4005. result.m[15] = 1.0;
  4006. result._markAsUpdated();
  4007. };
  4008. /**
  4009. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  4010. */
  4011. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  4012. result.m[0] = xaxis.x;
  4013. result.m[1] = xaxis.y;
  4014. result.m[2] = xaxis.z;
  4015. result.m[3] = 0.0;
  4016. result.m[4] = yaxis.x;
  4017. result.m[5] = yaxis.y;
  4018. result.m[6] = yaxis.z;
  4019. result.m[7] = 0.0;
  4020. result.m[8] = zaxis.x;
  4021. result.m[9] = zaxis.y;
  4022. result.m[10] = zaxis.z;
  4023. result.m[11] = 0.0;
  4024. result.m[12] = 0.0;
  4025. result.m[13] = 0.0;
  4026. result.m[14] = 0.0;
  4027. result.m[15] = 1.0;
  4028. result._markAsUpdated();
  4029. };
  4030. /**
  4031. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4032. */
  4033. Matrix.FromQuaternionToRef = function (quat, result) {
  4034. var xx = quat.x * quat.x;
  4035. var yy = quat.y * quat.y;
  4036. var zz = quat.z * quat.z;
  4037. var xy = quat.x * quat.y;
  4038. var zw = quat.z * quat.w;
  4039. var zx = quat.z * quat.x;
  4040. var yw = quat.y * quat.w;
  4041. var yz = quat.y * quat.z;
  4042. var xw = quat.x * quat.w;
  4043. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4044. result.m[1] = 2.0 * (xy + zw);
  4045. result.m[2] = 2.0 * (zx - yw);
  4046. result.m[3] = 0.0;
  4047. result.m[4] = 2.0 * (xy - zw);
  4048. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4049. result.m[6] = 2.0 * (yz + xw);
  4050. result.m[7] = 0.0;
  4051. result.m[8] = 2.0 * (zx + yw);
  4052. result.m[9] = 2.0 * (yz - xw);
  4053. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4054. result.m[11] = 0.0;
  4055. result.m[12] = 0.0;
  4056. result.m[13] = 0.0;
  4057. result.m[14] = 0.0;
  4058. result.m[15] = 1.0;
  4059. result._markAsUpdated();
  4060. };
  4061. Matrix._tempQuaternion = new Quaternion();
  4062. Matrix._xAxis = Vector3.Zero();
  4063. Matrix._yAxis = Vector3.Zero();
  4064. Matrix._zAxis = Vector3.Zero();
  4065. Matrix._updateFlagSeed = 0;
  4066. return Matrix;
  4067. }());
  4068. BABYLON.Matrix = Matrix;
  4069. var Plane = (function () {
  4070. /**
  4071. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4072. */
  4073. function Plane(a, b, c, d) {
  4074. this.normal = new Vector3(a, b, c);
  4075. this.d = d;
  4076. }
  4077. /**
  4078. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4079. */
  4080. Plane.prototype.asArray = function () {
  4081. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4082. };
  4083. // Methods
  4084. /**
  4085. * Returns a new plane copied from the current Plane.
  4086. */
  4087. Plane.prototype.clone = function () {
  4088. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4089. };
  4090. /**
  4091. * Returns the string "Plane".
  4092. */
  4093. Plane.prototype.getClassName = function () {
  4094. return "Plane";
  4095. };
  4096. /**
  4097. * Returns the Plane hash code.
  4098. */
  4099. Plane.prototype.getHashCode = function () {
  4100. var hash = this.normal.getHashCode();
  4101. hash = (hash * 397) ^ (this.d || 0);
  4102. return hash;
  4103. };
  4104. /**
  4105. * Normalize the current Plane in place.
  4106. * Returns the updated Plane.
  4107. */
  4108. Plane.prototype.normalize = function () {
  4109. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4110. var magnitude = 0.0;
  4111. if (norm !== 0) {
  4112. magnitude = 1.0 / norm;
  4113. }
  4114. this.normal.x *= magnitude;
  4115. this.normal.y *= magnitude;
  4116. this.normal.z *= magnitude;
  4117. this.d *= magnitude;
  4118. return this;
  4119. };
  4120. /**
  4121. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4122. */
  4123. Plane.prototype.transform = function (transformation) {
  4124. var transposedMatrix = Matrix.Transpose(transformation);
  4125. var x = this.normal.x;
  4126. var y = this.normal.y;
  4127. var z = this.normal.z;
  4128. var d = this.d;
  4129. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4130. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4131. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4132. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4133. return new Plane(normalX, normalY, normalZ, finalD);
  4134. };
  4135. /**
  4136. * Returns the dot product (float) of the point coordinates and the plane normal.
  4137. */
  4138. Plane.prototype.dotCoordinate = function (point) {
  4139. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4140. };
  4141. /**
  4142. * Updates the current Plane from the plane defined by the three passed points.
  4143. * Returns the updated Plane.
  4144. */
  4145. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4146. var x1 = point2.x - point1.x;
  4147. var y1 = point2.y - point1.y;
  4148. var z1 = point2.z - point1.z;
  4149. var x2 = point3.x - point1.x;
  4150. var y2 = point3.y - point1.y;
  4151. var z2 = point3.z - point1.z;
  4152. var yz = (y1 * z2) - (z1 * y2);
  4153. var xz = (z1 * x2) - (x1 * z2);
  4154. var xy = (x1 * y2) - (y1 * x2);
  4155. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4156. var invPyth;
  4157. if (pyth !== 0) {
  4158. invPyth = 1.0 / pyth;
  4159. }
  4160. else {
  4161. invPyth = 0.0;
  4162. }
  4163. this.normal.x = yz * invPyth;
  4164. this.normal.y = xz * invPyth;
  4165. this.normal.z = xy * invPyth;
  4166. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4167. return this;
  4168. };
  4169. /**
  4170. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4171. */
  4172. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4173. var dot = Vector3.Dot(this.normal, direction);
  4174. return (dot <= epsilon);
  4175. };
  4176. /**
  4177. * Returns the signed distance (float) from the passed point to the Plane.
  4178. */
  4179. Plane.prototype.signedDistanceTo = function (point) {
  4180. return Vector3.Dot(point, this.normal) + this.d;
  4181. };
  4182. // Statics
  4183. /**
  4184. * Returns a new Plane from the passed array.
  4185. */
  4186. Plane.FromArray = function (array) {
  4187. return new Plane(array[0], array[1], array[2], array[3]);
  4188. };
  4189. /**
  4190. * Returns a new Plane defined by the three passed points.
  4191. */
  4192. Plane.FromPoints = function (point1, point2, point3) {
  4193. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4194. result.copyFromPoints(point1, point2, point3);
  4195. return result;
  4196. };
  4197. /**
  4198. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4199. * Note : the vector "normal" is updated because normalized.
  4200. */
  4201. Plane.FromPositionAndNormal = function (origin, normal) {
  4202. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4203. normal.normalize();
  4204. result.normal = normal;
  4205. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4206. return result;
  4207. };
  4208. /**
  4209. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4210. */
  4211. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4212. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4213. return Vector3.Dot(point, normal) + d;
  4214. };
  4215. return Plane;
  4216. }());
  4217. BABYLON.Plane = Plane;
  4218. var Viewport = (function () {
  4219. /**
  4220. * Creates a Viewport object located at (x, y) and sized (width, height).
  4221. */
  4222. function Viewport(x, y, width, height) {
  4223. this.x = x;
  4224. this.y = y;
  4225. this.width = width;
  4226. this.height = height;
  4227. }
  4228. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4229. if (renderWidthOrEngine.getRenderWidth) {
  4230. var engine = renderWidthOrEngine;
  4231. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4232. }
  4233. var renderWidth = renderWidthOrEngine;
  4234. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4235. };
  4236. /**
  4237. * Returns a new Viewport copied from the current one.
  4238. */
  4239. Viewport.prototype.clone = function () {
  4240. return new Viewport(this.x, this.y, this.width, this.height);
  4241. };
  4242. return Viewport;
  4243. }());
  4244. BABYLON.Viewport = Viewport;
  4245. var Frustum = (function () {
  4246. function Frustum() {
  4247. }
  4248. /**
  4249. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4250. */
  4251. Frustum.GetPlanes = function (transform) {
  4252. var frustumPlanes = [];
  4253. for (var index = 0; index < 6; index++) {
  4254. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4255. }
  4256. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4257. return frustumPlanes;
  4258. };
  4259. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  4260. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  4261. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  4262. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  4263. frustumPlane.d = transform.m[15] + transform.m[14];
  4264. frustumPlane.normalize();
  4265. };
  4266. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  4267. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  4268. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  4269. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  4270. frustumPlane.d = transform.m[15] - transform.m[14];
  4271. frustumPlane.normalize();
  4272. };
  4273. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  4274. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  4275. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  4276. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  4277. frustumPlane.d = transform.m[15] + transform.m[12];
  4278. frustumPlane.normalize();
  4279. };
  4280. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  4281. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  4282. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  4283. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  4284. frustumPlane.d = transform.m[15] - transform.m[12];
  4285. frustumPlane.normalize();
  4286. };
  4287. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  4288. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  4289. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  4290. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  4291. frustumPlane.d = transform.m[15] - transform.m[13];
  4292. frustumPlane.normalize();
  4293. };
  4294. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  4295. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  4296. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  4297. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  4298. frustumPlane.d = transform.m[15] + transform.m[13];
  4299. frustumPlane.normalize();
  4300. };
  4301. /**
  4302. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4303. */
  4304. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4305. // Near
  4306. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  4307. // Far
  4308. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  4309. // Left
  4310. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  4311. // Right
  4312. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  4313. // Top
  4314. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  4315. // Bottom
  4316. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  4317. };
  4318. return Frustum;
  4319. }());
  4320. BABYLON.Frustum = Frustum;
  4321. var Space;
  4322. (function (Space) {
  4323. Space[Space["LOCAL"] = 0] = "LOCAL";
  4324. Space[Space["WORLD"] = 1] = "WORLD";
  4325. Space[Space["BONE"] = 2] = "BONE";
  4326. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4327. var Axis = (function () {
  4328. function Axis() {
  4329. }
  4330. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4331. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4332. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4333. return Axis;
  4334. }());
  4335. BABYLON.Axis = Axis;
  4336. ;
  4337. var BezierCurve = (function () {
  4338. function BezierCurve() {
  4339. }
  4340. /**
  4341. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4342. */
  4343. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4344. // Extract X (which is equal to time here)
  4345. var f0 = 1 - 3 * x2 + 3 * x1;
  4346. var f1 = 3 * x2 - 6 * x1;
  4347. var f2 = 3 * x1;
  4348. var refinedT = t;
  4349. for (var i = 0; i < 5; i++) {
  4350. var refinedT2 = refinedT * refinedT;
  4351. var refinedT3 = refinedT2 * refinedT;
  4352. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4353. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4354. refinedT -= (x - t) * slope;
  4355. refinedT = Math.min(1, Math.max(0, refinedT));
  4356. }
  4357. // Resolve cubic bezier for the given x
  4358. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4359. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4360. Math.pow(refinedT, 3);
  4361. };
  4362. return BezierCurve;
  4363. }());
  4364. BABYLON.BezierCurve = BezierCurve;
  4365. var Orientation;
  4366. (function (Orientation) {
  4367. Orientation[Orientation["CW"] = 0] = "CW";
  4368. Orientation[Orientation["CCW"] = 1] = "CCW";
  4369. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4370. var Angle = (function () {
  4371. /**
  4372. * Creates an Angle object of "radians" radians (float).
  4373. */
  4374. function Angle(radians) {
  4375. var _this = this;
  4376. /**
  4377. * Returns the Angle value in degrees (float).
  4378. */
  4379. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4380. /**
  4381. * Returns the Angle value in radians (float).
  4382. */
  4383. this.radians = function () { return _this._radians; };
  4384. this._radians = radians;
  4385. if (this._radians < 0.0)
  4386. this._radians += (2.0 * Math.PI);
  4387. }
  4388. /**
  4389. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4390. */
  4391. Angle.BetweenTwoPoints = function (a, b) {
  4392. var delta = b.subtract(a);
  4393. var theta = Math.atan2(delta.y, delta.x);
  4394. return new Angle(theta);
  4395. };
  4396. /**
  4397. * Returns a new Angle object from the passed float in radians.
  4398. */
  4399. Angle.FromRadians = function (radians) {
  4400. return new Angle(radians);
  4401. };
  4402. /**
  4403. * Returns a new Angle object from the passed float in degrees.
  4404. */
  4405. Angle.FromDegrees = function (degrees) {
  4406. return new Angle(degrees * Math.PI / 180.0);
  4407. };
  4408. return Angle;
  4409. }());
  4410. BABYLON.Angle = Angle;
  4411. var Arc2 = (function () {
  4412. /**
  4413. * Creates an Arc object from the three passed points : start, middle and end.
  4414. */
  4415. function Arc2(startPoint, midPoint, endPoint) {
  4416. this.startPoint = startPoint;
  4417. this.midPoint = midPoint;
  4418. this.endPoint = endPoint;
  4419. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4420. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4421. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4422. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4423. 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);
  4424. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4425. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4426. var a1 = this.startAngle.degrees();
  4427. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4428. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4429. // angles correction
  4430. if (a2 - a1 > +180.0)
  4431. a2 -= 360.0;
  4432. if (a2 - a1 < -180.0)
  4433. a2 += 360.0;
  4434. if (a3 - a2 > +180.0)
  4435. a3 -= 360.0;
  4436. if (a3 - a2 < -180.0)
  4437. a3 += 360.0;
  4438. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4439. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4440. }
  4441. return Arc2;
  4442. }());
  4443. BABYLON.Arc2 = Arc2;
  4444. var Path2 = (function () {
  4445. /**
  4446. * Creates a Path2 object from the starting 2D coordinates x and y.
  4447. */
  4448. function Path2(x, y) {
  4449. this._points = new Array();
  4450. this._length = 0.0;
  4451. this.closed = false;
  4452. this._points.push(new Vector2(x, y));
  4453. }
  4454. /**
  4455. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4456. * Returns the updated Path2.
  4457. */
  4458. Path2.prototype.addLineTo = function (x, y) {
  4459. if (closed) {
  4460. //Tools.Error("cannot add lines to closed paths");
  4461. return this;
  4462. }
  4463. var newPoint = new Vector2(x, y);
  4464. var previousPoint = this._points[this._points.length - 1];
  4465. this._points.push(newPoint);
  4466. this._length += newPoint.subtract(previousPoint).length();
  4467. return this;
  4468. };
  4469. /**
  4470. * 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.
  4471. * Returns the updated Path2.
  4472. */
  4473. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4474. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4475. if (closed) {
  4476. //Tools.Error("cannot add arcs to closed paths");
  4477. return this;
  4478. }
  4479. var startPoint = this._points[this._points.length - 1];
  4480. var midPoint = new Vector2(midX, midY);
  4481. var endPoint = new Vector2(endX, endY);
  4482. var arc = new Arc2(startPoint, midPoint, endPoint);
  4483. var increment = arc.angle.radians() / numberOfSegments;
  4484. if (arc.orientation === Orientation.CW)
  4485. increment *= -1;
  4486. var currentAngle = arc.startAngle.radians() + increment;
  4487. for (var i = 0; i < numberOfSegments; i++) {
  4488. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4489. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4490. this.addLineTo(x, y);
  4491. currentAngle += increment;
  4492. }
  4493. return this;
  4494. };
  4495. /**
  4496. * Closes the Path2.
  4497. * Returns the Path2.
  4498. */
  4499. Path2.prototype.close = function () {
  4500. this.closed = true;
  4501. return this;
  4502. };
  4503. /**
  4504. * Returns the Path2 total length (float).
  4505. */
  4506. Path2.prototype.length = function () {
  4507. var result = this._length;
  4508. if (!this.closed) {
  4509. var lastPoint = this._points[this._points.length - 1];
  4510. var firstPoint = this._points[0];
  4511. result += (firstPoint.subtract(lastPoint).length());
  4512. }
  4513. return result;
  4514. };
  4515. /**
  4516. * Returns the Path2 internal array of points.
  4517. */
  4518. Path2.prototype.getPoints = function () {
  4519. return this._points;
  4520. };
  4521. /**
  4522. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4523. */
  4524. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4525. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4526. //Tools.Error("normalized length position should be between 0 and 1.");
  4527. return Vector2.Zero();
  4528. }
  4529. var lengthPosition = normalizedLengthPosition * this.length();
  4530. var previousOffset = 0;
  4531. for (var i = 0; i < this._points.length; i++) {
  4532. var j = (i + 1) % this._points.length;
  4533. var a = this._points[i];
  4534. var b = this._points[j];
  4535. var bToA = b.subtract(a);
  4536. var nextOffset = (bToA.length() + previousOffset);
  4537. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4538. var dir = bToA.normalize();
  4539. var localOffset = lengthPosition - previousOffset;
  4540. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4541. }
  4542. previousOffset = nextOffset;
  4543. }
  4544. //Tools.Error("internal error");
  4545. return Vector2.Zero();
  4546. };
  4547. /**
  4548. * Returns a new Path2 starting at the coordinates (x, y).
  4549. */
  4550. Path2.StartingAt = function (x, y) {
  4551. return new Path2(x, y);
  4552. };
  4553. return Path2;
  4554. }());
  4555. BABYLON.Path2 = Path2;
  4556. var Path3D = (function () {
  4557. /**
  4558. * new Path3D(path, normal, raw)
  4559. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4560. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4561. * path : an array of Vector3, the curve axis of the Path3D
  4562. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4563. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4564. */
  4565. function Path3D(path, firstNormal, raw) {
  4566. this.path = path;
  4567. this._curve = new Array();
  4568. this._distances = new Array();
  4569. this._tangents = new Array();
  4570. this._normals = new Array();
  4571. this._binormals = new Array();
  4572. for (var p = 0; p < path.length; p++) {
  4573. this._curve[p] = path[p].clone(); // hard copy
  4574. }
  4575. this._raw = raw || false;
  4576. this._compute(firstNormal);
  4577. }
  4578. /**
  4579. * Returns the Path3D array of successive Vector3 designing its curve.
  4580. */
  4581. Path3D.prototype.getCurve = function () {
  4582. return this._curve;
  4583. };
  4584. /**
  4585. * Returns an array populated with tangent vectors on each Path3D curve point.
  4586. */
  4587. Path3D.prototype.getTangents = function () {
  4588. return this._tangents;
  4589. };
  4590. /**
  4591. * Returns an array populated with normal vectors on each Path3D curve point.
  4592. */
  4593. Path3D.prototype.getNormals = function () {
  4594. return this._normals;
  4595. };
  4596. /**
  4597. * Returns an array populated with binormal vectors on each Path3D curve point.
  4598. */
  4599. Path3D.prototype.getBinormals = function () {
  4600. return this._binormals;
  4601. };
  4602. /**
  4603. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4604. */
  4605. Path3D.prototype.getDistances = function () {
  4606. return this._distances;
  4607. };
  4608. /**
  4609. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4610. * Returns the same object updated.
  4611. */
  4612. Path3D.prototype.update = function (path, firstNormal) {
  4613. for (var p = 0; p < path.length; p++) {
  4614. this._curve[p].x = path[p].x;
  4615. this._curve[p].y = path[p].y;
  4616. this._curve[p].z = path[p].z;
  4617. }
  4618. this._compute(firstNormal);
  4619. return this;
  4620. };
  4621. // private function compute() : computes tangents, normals and binormals
  4622. Path3D.prototype._compute = function (firstNormal) {
  4623. var l = this._curve.length;
  4624. // first and last tangents
  4625. this._tangents[0] = this._getFirstNonNullVector(0);
  4626. if (!this._raw) {
  4627. this._tangents[0].normalize();
  4628. }
  4629. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4630. if (!this._raw) {
  4631. this._tangents[l - 1].normalize();
  4632. }
  4633. // normals and binormals at first point : arbitrary vector with _normalVector()
  4634. var tg0 = this._tangents[0];
  4635. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4636. this._normals[0] = pp0;
  4637. if (!this._raw) {
  4638. this._normals[0].normalize();
  4639. }
  4640. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4641. if (!this._raw) {
  4642. this._binormals[0].normalize();
  4643. }
  4644. this._distances[0] = 0.0;
  4645. // normals and binormals : next points
  4646. var prev; // previous vector (segment)
  4647. var cur; // current vector (segment)
  4648. var curTang; // current tangent
  4649. // previous normal
  4650. var prevBinor; // previous binormal
  4651. for (var i = 1; i < l; i++) {
  4652. // tangents
  4653. prev = this._getLastNonNullVector(i);
  4654. if (i < l - 1) {
  4655. cur = this._getFirstNonNullVector(i);
  4656. this._tangents[i] = prev.add(cur);
  4657. this._tangents[i].normalize();
  4658. }
  4659. this._distances[i] = this._distances[i - 1] + prev.length();
  4660. // normals and binormals
  4661. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4662. curTang = this._tangents[i];
  4663. prevBinor = this._binormals[i - 1];
  4664. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4665. if (!this._raw) {
  4666. this._normals[i].normalize();
  4667. }
  4668. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4669. if (!this._raw) {
  4670. this._binormals[i].normalize();
  4671. }
  4672. }
  4673. };
  4674. // private function getFirstNonNullVector(index)
  4675. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4676. Path3D.prototype._getFirstNonNullVector = function (index) {
  4677. var i = 1;
  4678. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4679. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4680. i++;
  4681. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4682. }
  4683. return nNVector;
  4684. };
  4685. // private function getLastNonNullVector(index)
  4686. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4687. Path3D.prototype._getLastNonNullVector = function (index) {
  4688. var i = 1;
  4689. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4690. while (nLVector.length() === 0 && index > i + 1) {
  4691. i++;
  4692. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4693. }
  4694. return nLVector;
  4695. };
  4696. // private function normalVector(v0, vt, va) :
  4697. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4698. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4699. Path3D.prototype._normalVector = function (v0, vt, va) {
  4700. var normal0;
  4701. var tgl = vt.length();
  4702. if (tgl === 0.0) {
  4703. tgl = 1.0;
  4704. }
  4705. if (va === undefined || va === null) {
  4706. var point;
  4707. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4708. point = new Vector3(0.0, -1.0, 0.0);
  4709. }
  4710. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4711. point = new Vector3(1.0, 0.0, 0.0);
  4712. }
  4713. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4714. point = new Vector3(0.0, 0.0, 1.0);
  4715. }
  4716. normal0 = Vector3.Cross(vt, point);
  4717. }
  4718. else {
  4719. normal0 = Vector3.Cross(vt, va);
  4720. Vector3.CrossToRef(normal0, vt, normal0);
  4721. }
  4722. normal0.normalize();
  4723. return normal0;
  4724. };
  4725. return Path3D;
  4726. }());
  4727. BABYLON.Path3D = Path3D;
  4728. var Curve3 = (function () {
  4729. /**
  4730. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4731. * A Curve3 is designed from a series of successive Vector3.
  4732. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4733. */
  4734. function Curve3(points) {
  4735. this._length = 0.0;
  4736. this._points = points;
  4737. this._length = this._computeLength(points);
  4738. }
  4739. /**
  4740. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4741. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4742. * @param v1 (Vector3) the control point
  4743. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4744. * @param nbPoints (integer) the wanted number of points in the curve
  4745. */
  4746. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4747. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4748. var bez = new Array();
  4749. var equation = function (t, val0, val1, val2) {
  4750. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4751. return res;
  4752. };
  4753. for (var i = 0; i <= nbPoints; i++) {
  4754. 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)));
  4755. }
  4756. return new Curve3(bez);
  4757. };
  4758. /**
  4759. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4760. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4761. * @param v1 (Vector3) the first control point
  4762. * @param v2 (Vector3) the second control point
  4763. * @param v3 (Vector3) the end point of the Cubic Bezier
  4764. * @param nbPoints (integer) the wanted number of points in the curve
  4765. */
  4766. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4767. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4768. var bez = new Array();
  4769. var equation = function (t, val0, val1, val2, val3) {
  4770. 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;
  4771. return res;
  4772. };
  4773. for (var i = 0; i <= nbPoints; i++) {
  4774. 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)));
  4775. }
  4776. return new Curve3(bez);
  4777. };
  4778. /**
  4779. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4780. * @param p1 (Vector3) the origin point of the Hermite Spline
  4781. * @param t1 (Vector3) the tangent vector at the origin point
  4782. * @param p2 (Vector3) the end point of the Hermite Spline
  4783. * @param t2 (Vector3) the tangent vector at the end point
  4784. * @param nbPoints (integer) the wanted number of points in the curve
  4785. */
  4786. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4787. var hermite = new Array();
  4788. var step = 1.0 / nbPoints;
  4789. for (var i = 0; i <= nbPoints; i++) {
  4790. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4791. }
  4792. return new Curve3(hermite);
  4793. };
  4794. /**
  4795. * Returns a Curve3 object along a CatmullRom Spline curve :
  4796. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4797. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4798. */
  4799. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4800. var totalPoints = new Array();
  4801. totalPoints.push(points[0].clone());
  4802. Array.prototype.push.apply(totalPoints, points);
  4803. totalPoints.push(points[points.length - 1].clone());
  4804. var catmullRom = new Array();
  4805. var step = 1.0 / nbPoints;
  4806. for (var i = 0; i < totalPoints.length - 3; i++) {
  4807. var amount = 0.0;
  4808. for (var c = 0; c < nbPoints; c++) {
  4809. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4810. amount += step;
  4811. }
  4812. }
  4813. i--;
  4814. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4815. return new Curve3(catmullRom);
  4816. };
  4817. /**
  4818. * Returns the Curve3 stored array of successive Vector3
  4819. */
  4820. Curve3.prototype.getPoints = function () {
  4821. return this._points;
  4822. };
  4823. /**
  4824. * Returns the computed length (float) of the curve.
  4825. */
  4826. Curve3.prototype.length = function () {
  4827. return this._length;
  4828. };
  4829. /**
  4830. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4831. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4832. * curveA and curveB keep unchanged.
  4833. */
  4834. Curve3.prototype.continue = function (curve) {
  4835. var lastPoint = this._points[this._points.length - 1];
  4836. var continuedPoints = this._points.slice();
  4837. var curvePoints = curve.getPoints();
  4838. for (var i = 1; i < curvePoints.length; i++) {
  4839. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4840. }
  4841. var continuedCurve = new Curve3(continuedPoints);
  4842. return continuedCurve;
  4843. };
  4844. Curve3.prototype._computeLength = function (path) {
  4845. var l = 0;
  4846. for (var i = 1; i < path.length; i++) {
  4847. l += (path[i].subtract(path[i - 1])).length();
  4848. }
  4849. return l;
  4850. };
  4851. return Curve3;
  4852. }());
  4853. BABYLON.Curve3 = Curve3;
  4854. // Vertex formats
  4855. var PositionNormalVertex = (function () {
  4856. function PositionNormalVertex(position, normal) {
  4857. if (position === void 0) { position = Vector3.Zero(); }
  4858. if (normal === void 0) { normal = Vector3.Up(); }
  4859. this.position = position;
  4860. this.normal = normal;
  4861. }
  4862. PositionNormalVertex.prototype.clone = function () {
  4863. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4864. };
  4865. return PositionNormalVertex;
  4866. }());
  4867. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4868. var PositionNormalTextureVertex = (function () {
  4869. function PositionNormalTextureVertex(position, normal, uv) {
  4870. if (position === void 0) { position = Vector3.Zero(); }
  4871. if (normal === void 0) { normal = Vector3.Up(); }
  4872. if (uv === void 0) { uv = Vector2.Zero(); }
  4873. this.position = position;
  4874. this.normal = normal;
  4875. this.uv = uv;
  4876. }
  4877. PositionNormalTextureVertex.prototype.clone = function () {
  4878. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4879. };
  4880. return PositionNormalTextureVertex;
  4881. }());
  4882. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4883. // Temporary pre-allocated objects for engine internal use
  4884. // usage in any internal function :
  4885. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4886. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4887. var Tmp = (function () {
  4888. function Tmp() {
  4889. }
  4890. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4891. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4892. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4893. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4894. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4895. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4896. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4897. Matrix.Zero(), Matrix.Zero(),
  4898. Matrix.Zero(), Matrix.Zero(),
  4899. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4900. return Tmp;
  4901. }());
  4902. BABYLON.Tmp = Tmp;
  4903. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4904. var MathTmp = (function () {
  4905. function MathTmp() {
  4906. }
  4907. MathTmp.Vector3 = [Vector3.Zero()];
  4908. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4909. MathTmp.Quaternion = [Quaternion.Zero()];
  4910. return MathTmp;
  4911. }());
  4912. })(BABYLON || (BABYLON = {}));
  4913. //# sourceMappingURL=babylon.math.js.map
  4914. var BABYLON;
  4915. (function (BABYLON) {
  4916. var Scalar = (function () {
  4917. function Scalar() {
  4918. }
  4919. /**
  4920. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4921. */
  4922. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4923. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4924. var num = a - b;
  4925. return -epsilon <= num && num <= epsilon;
  4926. };
  4927. /**
  4928. * Returns a string : the upper case translation of the number i to hexadecimal.
  4929. */
  4930. Scalar.ToHex = function (i) {
  4931. var str = i.toString(16);
  4932. if (i <= 15) {
  4933. return ("0" + str).toUpperCase();
  4934. }
  4935. return str.toUpperCase();
  4936. };
  4937. /**
  4938. * Returns -1 if value is negative and +1 is value is positive.
  4939. * Returns the value itself if it's equal to zero.
  4940. */
  4941. Scalar.Sign = function (value) {
  4942. value = +value; // convert to a number
  4943. if (value === 0 || isNaN(value))
  4944. return value;
  4945. return value > 0 ? 1 : -1;
  4946. };
  4947. /**
  4948. * Returns the value itself if it's between min and max.
  4949. * Returns min if the value is lower than min.
  4950. * Returns max if the value is greater than max.
  4951. */
  4952. Scalar.Clamp = function (value, min, max) {
  4953. if (min === void 0) { min = 0; }
  4954. if (max === void 0) { max = 1; }
  4955. return Math.min(max, Math.max(min, value));
  4956. };
  4957. /**
  4958. * Returns the log2 of value.
  4959. */
  4960. Scalar.Log2 = function (value) {
  4961. return Math.log(value) * Math.LOG2E;
  4962. };
  4963. /**
  4964. * Loops the value, so that it is never larger than length and never smaller than 0.
  4965. *
  4966. * This is similar to the modulo operator but it works with floating point numbers.
  4967. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4968. * With t = 5 and length = 2.5, the result would be 0.0.
  4969. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4970. */
  4971. Scalar.Repeat = function (value, length) {
  4972. return value - Math.floor(value / length) * length;
  4973. };
  4974. /**
  4975. * Normalize the value between 0.0 and 1.0 using min and max values
  4976. */
  4977. Scalar.Normalize = function (value, min, max) {
  4978. return (value - min) / (max - min);
  4979. };
  4980. /**
  4981. * Denormalize the value from 0.0 and 1.0 using min and max values
  4982. */
  4983. Scalar.Denormalize = function (normalized, min, max) {
  4984. return (normalized * (max - min) + min);
  4985. };
  4986. /**
  4987. * Calculates the shortest difference between two given angles given in degrees.
  4988. */
  4989. Scalar.DeltaAngle = function (current, target) {
  4990. var num = Scalar.Repeat(target - current, 360.0);
  4991. if (num > 180.0) {
  4992. num -= 360.0;
  4993. }
  4994. return num;
  4995. };
  4996. /**
  4997. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4998. *
  4999. * The returned value will move back and forth between 0 and length
  5000. */
  5001. Scalar.PingPong = function (tx, length) {
  5002. var t = Scalar.Repeat(tx, length * 2.0);
  5003. return length - Math.abs(t - length);
  5004. };
  5005. /**
  5006. * Interpolates between min and max with smoothing at the limits.
  5007. *
  5008. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5009. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5010. */
  5011. Scalar.SmoothStep = function (from, to, tx) {
  5012. var t = Scalar.Clamp(tx);
  5013. t = -2.0 * t * t * t + 3.0 * t * t;
  5014. return to * t + from * (1.0 - t);
  5015. };
  5016. /**
  5017. * Moves a value current towards target.
  5018. *
  5019. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5020. * Negative values of maxDelta pushes the value away from target.
  5021. */
  5022. Scalar.MoveTowards = function (current, target, maxDelta) {
  5023. var result = 0;
  5024. if (Math.abs(target - current) <= maxDelta) {
  5025. result = target;
  5026. }
  5027. else {
  5028. result = current + Scalar.Sign(target - current) * maxDelta;
  5029. }
  5030. return result;
  5031. };
  5032. /**
  5033. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5034. *
  5035. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5036. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5037. */
  5038. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5039. var num = Scalar.DeltaAngle(current, target);
  5040. var result = 0;
  5041. if (-maxDelta < num && num < maxDelta) {
  5042. result = target;
  5043. }
  5044. else {
  5045. target = current + num;
  5046. result = Scalar.MoveTowards(current, target, maxDelta);
  5047. }
  5048. return result;
  5049. };
  5050. /**
  5051. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5052. */
  5053. Scalar.Lerp = function (start, end, amount) {
  5054. return start + ((end - start) * amount);
  5055. };
  5056. /**
  5057. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5058. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5059. */
  5060. Scalar.LerpAngle = function (start, end, amount) {
  5061. var num = Scalar.Repeat(end - start, 360.0);
  5062. if (num > 180.0) {
  5063. num -= 360.0;
  5064. }
  5065. return start + num * Scalar.Clamp(amount);
  5066. };
  5067. /**
  5068. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5069. */
  5070. Scalar.InverseLerp = function (a, b, value) {
  5071. var result = 0;
  5072. if (a != b) {
  5073. result = Scalar.Clamp((value - a) / (b - a));
  5074. }
  5075. else {
  5076. result = 0.0;
  5077. }
  5078. return result;
  5079. };
  5080. /**
  5081. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5082. */
  5083. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5084. var squared = amount * amount;
  5085. var cubed = amount * squared;
  5086. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5087. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5088. var part3 = (cubed - (2.0 * squared)) + amount;
  5089. var part4 = cubed - squared;
  5090. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5091. };
  5092. /**
  5093. * Returns a random float number between and min and max values
  5094. */
  5095. Scalar.RandomRange = function (min, max) {
  5096. if (min === max)
  5097. return min;
  5098. return ((Math.random() * (max - min)) + min);
  5099. };
  5100. /**
  5101. * This function returns percentage of a number in a given range.
  5102. *
  5103. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5104. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5105. */
  5106. Scalar.RangeToPercent = function (number, min, max) {
  5107. return ((number - min) / (max - min));
  5108. };
  5109. /**
  5110. * This function returns number that corresponds to the percentage in a given range.
  5111. *
  5112. * PercentToRange(0.34,0,100) will return 34.
  5113. */
  5114. Scalar.PercentToRange = function (percent, min, max) {
  5115. return ((max - min) * percent + min);
  5116. };
  5117. return Scalar;
  5118. }());
  5119. BABYLON.Scalar = Scalar;
  5120. })(BABYLON || (BABYLON = {}));
  5121. //# sourceMappingURL=babylon.math.scalar.js.map
  5122. //# sourceMappingURL=babylon.mixins.js.map
  5123. var BABYLON;
  5124. (function (BABYLON) {
  5125. var __decoratorInitialStore = {};
  5126. var __mergedStore = {};
  5127. var _copySource = function (creationFunction, source, instanciate) {
  5128. var destination = creationFunction();
  5129. // Tags
  5130. if (BABYLON.Tags) {
  5131. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5132. }
  5133. var classStore = getMergedStore(destination);
  5134. // Properties
  5135. for (var property in classStore) {
  5136. var propertyDescriptor = classStore[property];
  5137. var sourceProperty = source[property];
  5138. var propertyType = propertyDescriptor.type;
  5139. if (sourceProperty !== undefined && sourceProperty !== null) {
  5140. switch (propertyType) {
  5141. case 0: // Value
  5142. case 6:// Mesh reference
  5143. destination[property] = sourceProperty;
  5144. break;
  5145. case 1:// Texture
  5146. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  5147. break;
  5148. case 2: // Color3
  5149. case 3: // FresnelParameters
  5150. case 4: // Vector2
  5151. case 5: // Vector3
  5152. case 7:// Color Curves
  5153. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5154. break;
  5155. }
  5156. }
  5157. }
  5158. return destination;
  5159. };
  5160. function getDirectStore(target) {
  5161. var classKey = target.getClassName();
  5162. if (!__decoratorInitialStore[classKey]) {
  5163. __decoratorInitialStore[classKey] = {};
  5164. }
  5165. return __decoratorInitialStore[classKey];
  5166. }
  5167. /**
  5168. * Return the list of properties flagged as serializable
  5169. * @param target: host object
  5170. */
  5171. function getMergedStore(target) {
  5172. var classKey = target.getClassName();
  5173. if (__mergedStore[classKey]) {
  5174. return __mergedStore[classKey];
  5175. }
  5176. __mergedStore[classKey] = {};
  5177. var store = __mergedStore[classKey];
  5178. var currentTarget = target;
  5179. var currentKey = classKey;
  5180. while (currentKey) {
  5181. var initialStore = __decoratorInitialStore[currentKey];
  5182. for (var property in initialStore) {
  5183. store[property] = initialStore[property];
  5184. }
  5185. var parent_1 = void 0;
  5186. var done = false;
  5187. do {
  5188. parent_1 = Object.getPrototypeOf(currentTarget);
  5189. if (!parent_1.getClassName) {
  5190. done = true;
  5191. break;
  5192. }
  5193. if (parent_1.getClassName() !== currentKey) {
  5194. break;
  5195. }
  5196. currentTarget = parent_1;
  5197. } while (parent_1);
  5198. if (done) {
  5199. break;
  5200. }
  5201. currentKey = parent_1.getClassName();
  5202. currentTarget = parent_1;
  5203. }
  5204. return store;
  5205. }
  5206. function generateSerializableMember(type, sourceName) {
  5207. return function (target, propertyKey) {
  5208. var classStore = getDirectStore(target);
  5209. if (!classStore[propertyKey]) {
  5210. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5211. }
  5212. };
  5213. }
  5214. function generateExpandMember(setCallback, targetKey) {
  5215. return function (target, propertyKey) {
  5216. var key = targetKey || ("_" + propertyKey);
  5217. Object.defineProperty(target, propertyKey, {
  5218. get: function () {
  5219. return this[key];
  5220. },
  5221. set: function (value) {
  5222. if (this[key] === value) {
  5223. return;
  5224. }
  5225. this[key] = value;
  5226. target[setCallback].apply(this);
  5227. },
  5228. enumerable: true,
  5229. configurable: true
  5230. });
  5231. };
  5232. }
  5233. function expandToProperty(callback, targetKey) {
  5234. return generateExpandMember(callback, targetKey);
  5235. }
  5236. BABYLON.expandToProperty = expandToProperty;
  5237. function serialize(sourceName) {
  5238. return generateSerializableMember(0, sourceName); // value member
  5239. }
  5240. BABYLON.serialize = serialize;
  5241. function serializeAsTexture(sourceName) {
  5242. return generateSerializableMember(1, sourceName); // texture member
  5243. }
  5244. BABYLON.serializeAsTexture = serializeAsTexture;
  5245. function serializeAsColor3(sourceName) {
  5246. return generateSerializableMember(2, sourceName); // color3 member
  5247. }
  5248. BABYLON.serializeAsColor3 = serializeAsColor3;
  5249. function serializeAsFresnelParameters(sourceName) {
  5250. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5251. }
  5252. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5253. function serializeAsVector2(sourceName) {
  5254. return generateSerializableMember(4, sourceName); // vector2 member
  5255. }
  5256. BABYLON.serializeAsVector2 = serializeAsVector2;
  5257. function serializeAsVector3(sourceName) {
  5258. return generateSerializableMember(5, sourceName); // vector3 member
  5259. }
  5260. BABYLON.serializeAsVector3 = serializeAsVector3;
  5261. function serializeAsMeshReference(sourceName) {
  5262. return generateSerializableMember(6, sourceName); // mesh reference member
  5263. }
  5264. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5265. function serializeAsColorCurves(sourceName) {
  5266. return generateSerializableMember(7, sourceName); // color curves
  5267. }
  5268. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5269. function serializeAsColor4(sourceName) {
  5270. return generateSerializableMember(8, sourceName); // color 4
  5271. }
  5272. BABYLON.serializeAsColor4 = serializeAsColor4;
  5273. function serializeAsImageProcessingConfiguration(sourceName) {
  5274. return generateSerializableMember(9, sourceName); // image processing
  5275. }
  5276. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5277. var SerializationHelper = (function () {
  5278. function SerializationHelper() {
  5279. }
  5280. SerializationHelper.Serialize = function (entity, serializationObject) {
  5281. if (!serializationObject) {
  5282. serializationObject = {};
  5283. }
  5284. // Tags
  5285. if (BABYLON.Tags) {
  5286. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5287. }
  5288. var serializedProperties = getMergedStore(entity);
  5289. // Properties
  5290. for (var property in serializedProperties) {
  5291. var propertyDescriptor = serializedProperties[property];
  5292. var targetPropertyName = propertyDescriptor.sourceName || property;
  5293. var propertyType = propertyDescriptor.type;
  5294. var sourceProperty = entity[property];
  5295. if (sourceProperty !== undefined && sourceProperty !== null) {
  5296. switch (propertyType) {
  5297. case 0:// Value
  5298. serializationObject[targetPropertyName] = sourceProperty;
  5299. break;
  5300. case 1:// Texture
  5301. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5302. break;
  5303. case 2:// Color3
  5304. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5305. break;
  5306. case 3:// FresnelParameters
  5307. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5308. break;
  5309. case 4:// Vector2
  5310. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5311. break;
  5312. case 5:// Vector3
  5313. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5314. break;
  5315. case 6:// Mesh reference
  5316. serializationObject[targetPropertyName] = sourceProperty.id;
  5317. break;
  5318. case 7:// Color Curves
  5319. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5320. break;
  5321. case 8:// Color 4
  5322. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5323. break;
  5324. case 9:// Image Processing
  5325. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5326. break;
  5327. }
  5328. }
  5329. }
  5330. return serializationObject;
  5331. };
  5332. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5333. var destination = creationFunction();
  5334. // Tags
  5335. if (BABYLON.Tags) {
  5336. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5337. }
  5338. var classStore = getMergedStore(destination);
  5339. // Properties
  5340. for (var property in classStore) {
  5341. var propertyDescriptor = classStore[property];
  5342. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5343. var propertyType = propertyDescriptor.type;
  5344. if (sourceProperty !== undefined && sourceProperty !== null) {
  5345. var dest = destination;
  5346. switch (propertyType) {
  5347. case 0:// Value
  5348. dest[property] = sourceProperty;
  5349. break;
  5350. case 1:// Texture
  5351. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5352. break;
  5353. case 2:// Color3
  5354. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  5355. break;
  5356. case 3:// FresnelParameters
  5357. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5358. break;
  5359. case 4:// Vector2
  5360. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5361. break;
  5362. case 5:// Vector3
  5363. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5364. break;
  5365. case 6:// Mesh reference
  5366. dest[property] = scene.getLastMeshByID(sourceProperty);
  5367. break;
  5368. case 7:// Color Curves
  5369. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5370. break;
  5371. case 8:// Color 4
  5372. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  5373. break;
  5374. case 9:// Image Processing
  5375. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5376. break;
  5377. }
  5378. }
  5379. }
  5380. return destination;
  5381. };
  5382. SerializationHelper.Clone = function (creationFunction, source) {
  5383. return _copySource(creationFunction, source, false);
  5384. };
  5385. SerializationHelper.Instanciate = function (creationFunction, source) {
  5386. return _copySource(creationFunction, source, true);
  5387. };
  5388. return SerializationHelper;
  5389. }());
  5390. BABYLON.SerializationHelper = SerializationHelper;
  5391. })(BABYLON || (BABYLON = {}));
  5392. //# sourceMappingURL=babylon.decorators.js.map
  5393. var BABYLON;
  5394. (function (BABYLON) {
  5395. /**
  5396. * A class serves as a medium between the observable and its observers
  5397. */
  5398. var EventState = (function () {
  5399. /**
  5400. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5401. */
  5402. function EventState(mask, skipNextObservers, target, currentTarget) {
  5403. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5404. this.initalize(mask, skipNextObservers, target, currentTarget);
  5405. }
  5406. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  5407. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5408. this.mask = mask;
  5409. this.skipNextObservers = skipNextObservers;
  5410. this.target = target;
  5411. this.currentTarget = currentTarget;
  5412. return this;
  5413. };
  5414. return EventState;
  5415. }());
  5416. BABYLON.EventState = EventState;
  5417. /**
  5418. * Represent an Observer registered to a given Observable object.
  5419. */
  5420. var Observer = (function () {
  5421. function Observer(callback, mask, scope) {
  5422. if (scope === void 0) { scope = null; }
  5423. this.callback = callback;
  5424. this.mask = mask;
  5425. this.scope = scope;
  5426. }
  5427. return Observer;
  5428. }());
  5429. BABYLON.Observer = Observer;
  5430. /**
  5431. * Represent a list of observers registered to multiple Observables object.
  5432. */
  5433. var MultiObserver = (function () {
  5434. function MultiObserver() {
  5435. }
  5436. MultiObserver.prototype.dispose = function () {
  5437. for (var index = 0; index < this._observers.length; index++) {
  5438. this._observables[index].remove(this._observers[index]);
  5439. }
  5440. this._observers = null;
  5441. this._observables = null;
  5442. };
  5443. MultiObserver.Watch = function (observables, callback, mask, scope) {
  5444. if (mask === void 0) { mask = -1; }
  5445. if (scope === void 0) { scope = null; }
  5446. var result = new MultiObserver();
  5447. result._observers = new Array();
  5448. result._observables = observables;
  5449. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  5450. var observable = observables_1[_i];
  5451. result._observers.push(observable.add(callback, mask, false, scope));
  5452. }
  5453. return result;
  5454. };
  5455. return MultiObserver;
  5456. }());
  5457. BABYLON.MultiObserver = MultiObserver;
  5458. /**
  5459. * The Observable class is a simple implementation of the Observable pattern.
  5460. * 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.
  5461. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5462. * 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).
  5463. * 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.
  5464. */
  5465. var Observable = (function () {
  5466. function Observable(onObserverAdded) {
  5467. this._observers = new Array();
  5468. this._eventState = new EventState(0);
  5469. this._onObserverAdded = onObserverAdded;
  5470. }
  5471. /**
  5472. * Create a new Observer with the specified callback
  5473. * @param callback the callback that will be executed for that Observer
  5474. * @param mask the mask used to filter observers
  5475. * @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.
  5476. * @param scope optional scope for the callback to be called from
  5477. */
  5478. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  5479. if (mask === void 0) { mask = -1; }
  5480. if (insertFirst === void 0) { insertFirst = false; }
  5481. if (scope === void 0) { scope = null; }
  5482. if (!callback) {
  5483. return null;
  5484. }
  5485. var observer = new Observer(callback, mask, scope);
  5486. if (insertFirst) {
  5487. this._observers.unshift(observer);
  5488. }
  5489. else {
  5490. this._observers.push(observer);
  5491. }
  5492. if (this._onObserverAdded) {
  5493. this._onObserverAdded(observer);
  5494. }
  5495. return observer;
  5496. };
  5497. /**
  5498. * Remove an Observer from the Observable object
  5499. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5500. */
  5501. Observable.prototype.remove = function (observer) {
  5502. var index = this._observers.indexOf(observer);
  5503. if (index !== -1) {
  5504. this._observers.splice(index, 1);
  5505. return true;
  5506. }
  5507. return false;
  5508. };
  5509. /**
  5510. * Remove a callback from the Observable object
  5511. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5512. */
  5513. Observable.prototype.removeCallback = function (callback) {
  5514. for (var index = 0; index < this._observers.length; index++) {
  5515. if (this._observers[index].callback === callback) {
  5516. this._observers.splice(index, 1);
  5517. return true;
  5518. }
  5519. }
  5520. return false;
  5521. };
  5522. /**
  5523. * Notify all Observers by calling their respective callback with the given data
  5524. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5525. * @param eventData
  5526. * @param mask
  5527. */
  5528. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  5529. if (mask === void 0) { mask = -1; }
  5530. var state = this._eventState;
  5531. state.mask = mask;
  5532. state.target = target;
  5533. state.currentTarget = currentTarget;
  5534. state.skipNextObservers = false;
  5535. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5536. var obs = _a[_i];
  5537. if (obs.mask & mask) {
  5538. if (obs.scope) {
  5539. obs.callback.apply(obs.scope, [eventData, state]);
  5540. }
  5541. else {
  5542. obs.callback(eventData, state);
  5543. }
  5544. }
  5545. if (state.skipNextObservers) {
  5546. return false;
  5547. }
  5548. }
  5549. return true;
  5550. };
  5551. /**
  5552. * Notify a specific observer
  5553. * @param eventData
  5554. * @param mask
  5555. */
  5556. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  5557. if (mask === void 0) { mask = -1; }
  5558. var state = this._eventState;
  5559. state.mask = mask;
  5560. state.skipNextObservers = false;
  5561. observer.callback(eventData, state);
  5562. };
  5563. /**
  5564. * return true is the Observable has at least one Observer registered
  5565. */
  5566. Observable.prototype.hasObservers = function () {
  5567. return this._observers.length > 0;
  5568. };
  5569. /**
  5570. * Clear the list of observers
  5571. */
  5572. Observable.prototype.clear = function () {
  5573. this._observers = new Array();
  5574. this._onObserverAdded = null;
  5575. };
  5576. /**
  5577. * Clone the current observable
  5578. */
  5579. Observable.prototype.clone = function () {
  5580. var result = new Observable();
  5581. result._observers = this._observers.slice(0);
  5582. return result;
  5583. };
  5584. /**
  5585. * Does this observable handles observer registered with a given mask
  5586. * @param {number} trigger - the mask to be tested
  5587. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5588. **/
  5589. Observable.prototype.hasSpecificMask = function (mask) {
  5590. if (mask === void 0) { mask = -1; }
  5591. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5592. var obs = _a[_i];
  5593. if (obs.mask & mask || obs.mask === mask) {
  5594. return true;
  5595. }
  5596. }
  5597. return false;
  5598. };
  5599. return Observable;
  5600. }());
  5601. BABYLON.Observable = Observable;
  5602. })(BABYLON || (BABYLON = {}));
  5603. //# sourceMappingURL=babylon.observable.js.map
  5604. var BABYLON;
  5605. (function (BABYLON) {
  5606. var SmartArray = (function () {
  5607. function SmartArray(capacity) {
  5608. this.length = 0;
  5609. this._duplicateId = 0;
  5610. this.data = new Array(capacity);
  5611. this._id = SmartArray._GlobalId++;
  5612. }
  5613. SmartArray.prototype.push = function (value) {
  5614. this.data[this.length++] = value;
  5615. if (this.length > this.data.length) {
  5616. this.data.length *= 2;
  5617. }
  5618. if (!value.__smartArrayFlags) {
  5619. value.__smartArrayFlags = {};
  5620. }
  5621. value.__smartArrayFlags[this._id] = this._duplicateId;
  5622. };
  5623. SmartArray.prototype.forEach = function (func) {
  5624. for (var index = 0; index < this.length; index++) {
  5625. func(this.data[index]);
  5626. }
  5627. };
  5628. SmartArray.prototype.pushNoDuplicate = function (value) {
  5629. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5630. return false;
  5631. }
  5632. this.push(value);
  5633. return true;
  5634. };
  5635. SmartArray.prototype.sort = function (compareFn) {
  5636. this.data.sort(compareFn);
  5637. };
  5638. SmartArray.prototype.reset = function () {
  5639. this.length = 0;
  5640. this._duplicateId++;
  5641. };
  5642. SmartArray.prototype.dispose = function () {
  5643. this.reset();
  5644. if (this.data) {
  5645. this.data.length = 0;
  5646. this.data = null;
  5647. }
  5648. };
  5649. SmartArray.prototype.concat = function (array) {
  5650. if (array.length === 0) {
  5651. return;
  5652. }
  5653. if (this.length + array.length > this.data.length) {
  5654. this.data.length = (this.length + array.length) * 2;
  5655. }
  5656. for (var index = 0; index < array.length; index++) {
  5657. this.data[this.length++] = (array.data || array)[index];
  5658. }
  5659. };
  5660. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5661. if (array.length === 0) {
  5662. return;
  5663. }
  5664. if (this.length + array.length > this.data.length) {
  5665. this.data.length = (this.length + array.length) * 2;
  5666. }
  5667. for (var index = 0; index < array.length; index++) {
  5668. var item = (array.data || array)[index];
  5669. this.pushNoDuplicate(item);
  5670. }
  5671. };
  5672. SmartArray.prototype.indexOf = function (value) {
  5673. var position = this.data.indexOf(value);
  5674. if (position >= this.length) {
  5675. return -1;
  5676. }
  5677. return position;
  5678. };
  5679. SmartArray.prototype.contains = function (value) {
  5680. return this.data.indexOf(value) !== -1;
  5681. };
  5682. // Statics
  5683. SmartArray._GlobalId = 0;
  5684. return SmartArray;
  5685. }());
  5686. BABYLON.SmartArray = SmartArray;
  5687. })(BABYLON || (BABYLON = {}));
  5688. //# sourceMappingURL=babylon.smartArray.js.map
  5689. var BABYLON;
  5690. (function (BABYLON) {
  5691. // Screenshots
  5692. var screenshotCanvas;
  5693. var cloneValue = function (source, destinationObject) {
  5694. if (!source)
  5695. return null;
  5696. if (source instanceof BABYLON.Mesh) {
  5697. return null;
  5698. }
  5699. if (source instanceof BABYLON.SubMesh) {
  5700. return source.clone(destinationObject);
  5701. }
  5702. else if (source.clone) {
  5703. return source.clone();
  5704. }
  5705. return null;
  5706. };
  5707. var Tools = (function () {
  5708. function Tools() {
  5709. }
  5710. ;
  5711. /**
  5712. * Interpolates between a and b via alpha
  5713. * @param a The lower value (returned when alpha = 0)
  5714. * @param b The upper value (returned when alpha = 1)
  5715. * @param alpha The interpolation-factor
  5716. * @return The mixed value
  5717. */
  5718. Tools.Mix = function (a, b, alpha) {
  5719. return a * (1 - alpha) + b * alpha;
  5720. };
  5721. Tools.Instantiate = function (className) {
  5722. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5723. return Tools.RegisteredExternalClasses[className];
  5724. }
  5725. var arr = className.split(".");
  5726. var fn = (window || this);
  5727. for (var i = 0, len = arr.length; i < len; i++) {
  5728. fn = fn[arr[i]];
  5729. }
  5730. if (typeof fn !== "function") {
  5731. return null;
  5732. }
  5733. return fn;
  5734. };
  5735. Tools.SetImmediate = function (action) {
  5736. if (window.setImmediate) {
  5737. window.setImmediate(action);
  5738. }
  5739. else {
  5740. setTimeout(action, 1);
  5741. }
  5742. };
  5743. Tools.IsExponentOfTwo = function (value) {
  5744. var count = 1;
  5745. do {
  5746. count *= 2;
  5747. } while (count < value);
  5748. return count === value;
  5749. };
  5750. /**
  5751. * Find the next highest power of two.
  5752. * @param x Number to start search from.
  5753. * @return Next highest power of two.
  5754. */
  5755. Tools.CeilingPOT = function (x) {
  5756. x--;
  5757. x |= x >> 1;
  5758. x |= x >> 2;
  5759. x |= x >> 4;
  5760. x |= x >> 8;
  5761. x |= x >> 16;
  5762. x++;
  5763. return x;
  5764. };
  5765. /**
  5766. * Find the next lowest power of two.
  5767. * @param x Number to start search from.
  5768. * @return Next lowest power of two.
  5769. */
  5770. Tools.FloorPOT = function (x) {
  5771. x = x | (x >> 1);
  5772. x = x | (x >> 2);
  5773. x = x | (x >> 4);
  5774. x = x | (x >> 8);
  5775. x = x | (x >> 16);
  5776. return x - (x >> 1);
  5777. };
  5778. /**
  5779. * Find the nearest power of two.
  5780. * @param x Number to start search from.
  5781. * @return Next nearest power of two.
  5782. */
  5783. Tools.NearestPOT = function (x) {
  5784. var c = Tools.CeilingPOT(x);
  5785. var f = Tools.FloorPOT(x);
  5786. return (c - x) > (x - f) ? f : c;
  5787. };
  5788. Tools.GetExponentOfTwo = function (value, max, mode) {
  5789. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5790. var pot;
  5791. switch (mode) {
  5792. case BABYLON.Engine.SCALEMODE_FLOOR:
  5793. pot = Tools.FloorPOT(value);
  5794. break;
  5795. case BABYLON.Engine.SCALEMODE_NEAREST:
  5796. pot = Tools.NearestPOT(value);
  5797. break;
  5798. case BABYLON.Engine.SCALEMODE_CEILING:
  5799. pot = Tools.CeilingPOT(value);
  5800. break;
  5801. }
  5802. return Math.min(pot, max);
  5803. };
  5804. Tools.GetFilename = function (path) {
  5805. var index = path.lastIndexOf("/");
  5806. if (index < 0)
  5807. return path;
  5808. return path.substring(index + 1);
  5809. };
  5810. Tools.GetDOMTextContent = function (element) {
  5811. var result = "";
  5812. var child = element.firstChild;
  5813. while (child) {
  5814. if (child.nodeType === 3) {
  5815. result += child.textContent;
  5816. }
  5817. child = child.nextSibling;
  5818. }
  5819. return result;
  5820. };
  5821. Tools.ToDegrees = function (angle) {
  5822. return angle * 180 / Math.PI;
  5823. };
  5824. Tools.ToRadians = function (angle) {
  5825. return angle * Math.PI / 180;
  5826. };
  5827. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5828. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5829. var output = "";
  5830. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5831. var i = 0;
  5832. var bytes = new Uint8Array(buffer);
  5833. while (i < bytes.length) {
  5834. chr1 = bytes[i++];
  5835. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5836. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5837. enc1 = chr1 >> 2;
  5838. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5839. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5840. enc4 = chr3 & 63;
  5841. if (isNaN(chr2)) {
  5842. enc3 = enc4 = 64;
  5843. }
  5844. else if (isNaN(chr3)) {
  5845. enc4 = 64;
  5846. }
  5847. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5848. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5849. }
  5850. return "data:image/png;base64," + output;
  5851. };
  5852. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5853. if (bias === void 0) { bias = null; }
  5854. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5855. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5856. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5857. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5858. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5859. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5860. }
  5861. if (bias) {
  5862. minimum.x -= minimum.x * bias.x + bias.y;
  5863. minimum.y -= minimum.y * bias.x + bias.y;
  5864. minimum.z -= minimum.z * bias.x + bias.y;
  5865. maximum.x += maximum.x * bias.x + bias.y;
  5866. maximum.y += maximum.y * bias.x + bias.y;
  5867. maximum.z += maximum.z * bias.x + bias.y;
  5868. }
  5869. return {
  5870. minimum: minimum,
  5871. maximum: maximum
  5872. };
  5873. };
  5874. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5875. if (bias === void 0) { bias = null; }
  5876. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5877. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5878. if (!stride) {
  5879. stride = 3;
  5880. }
  5881. for (var index = start; index < start + count; index++) {
  5882. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5883. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5884. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5885. }
  5886. if (bias) {
  5887. minimum.x -= minimum.x * bias.x + bias.y;
  5888. minimum.y -= minimum.y * bias.x + bias.y;
  5889. minimum.z -= minimum.z * bias.x + bias.y;
  5890. maximum.x += maximum.x * bias.x + bias.y;
  5891. maximum.y += maximum.y * bias.x + bias.y;
  5892. maximum.z += maximum.z * bias.x + bias.y;
  5893. }
  5894. return {
  5895. minimum: minimum,
  5896. maximum: maximum
  5897. };
  5898. };
  5899. Tools.Vector2ArrayFeeder = function (array) {
  5900. return function (index) {
  5901. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5902. var length = isFloatArray ? array.length / 2 : array.length;
  5903. if (index >= length) {
  5904. return null;
  5905. }
  5906. if (isFloatArray) {
  5907. var fa = array;
  5908. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5909. }
  5910. var a = array;
  5911. return a[index];
  5912. };
  5913. };
  5914. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5915. if (bias === void 0) { bias = null; }
  5916. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5917. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5918. var i = 0;
  5919. var cur = feeder(i++);
  5920. while (cur) {
  5921. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5922. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5923. cur = feeder(i++);
  5924. }
  5925. if (bias) {
  5926. minimum.x -= minimum.x * bias.x + bias.y;
  5927. minimum.y -= minimum.y * bias.x + bias.y;
  5928. maximum.x += maximum.x * bias.x + bias.y;
  5929. maximum.y += maximum.y * bias.x + bias.y;
  5930. }
  5931. return {
  5932. minimum: minimum,
  5933. maximum: maximum
  5934. };
  5935. };
  5936. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5937. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5938. return undefined;
  5939. return Array.isArray(obj) ? obj : [obj];
  5940. };
  5941. // Misc.
  5942. Tools.GetPointerPrefix = function () {
  5943. var eventPrefix = "pointer";
  5944. // Check if pointer events are supported
  5945. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  5946. eventPrefix = "mouse";
  5947. }
  5948. return eventPrefix;
  5949. };
  5950. /**
  5951. * @param func - the function to be called
  5952. * @param requester - the object that will request the next frame. Falls back to window.
  5953. */
  5954. Tools.QueueNewFrame = function (func, requester) {
  5955. if (!Tools.IsWindowObjectExist()) {
  5956. return setTimeout(func, 16);
  5957. }
  5958. if (!requester) {
  5959. requester = window;
  5960. }
  5961. if (requester.requestAnimationFrame) {
  5962. return requester.requestAnimationFrame(func);
  5963. }
  5964. else if (requester.msRequestAnimationFrame) {
  5965. return requester.msRequestAnimationFrame(func);
  5966. }
  5967. else if (requester.webkitRequestAnimationFrame) {
  5968. return requester.webkitRequestAnimationFrame(func);
  5969. }
  5970. else if (requester.mozRequestAnimationFrame) {
  5971. return requester.mozRequestAnimationFrame(func);
  5972. }
  5973. else if (requester.oRequestAnimationFrame) {
  5974. return requester.oRequestAnimationFrame(func);
  5975. }
  5976. else {
  5977. return window.setTimeout(func, 16);
  5978. }
  5979. };
  5980. Tools.RequestFullscreen = function (element) {
  5981. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5982. if (!requestFunction)
  5983. return;
  5984. requestFunction.call(element);
  5985. };
  5986. Tools.ExitFullscreen = function () {
  5987. if (document.exitFullscreen) {
  5988. document.exitFullscreen();
  5989. }
  5990. else if (document.mozCancelFullScreen) {
  5991. document.mozCancelFullScreen();
  5992. }
  5993. else if (document.webkitCancelFullScreen) {
  5994. document.webkitCancelFullScreen();
  5995. }
  5996. else if (document.msCancelFullScreen) {
  5997. document.msCancelFullScreen();
  5998. }
  5999. };
  6000. Tools.SetCorsBehavior = function (url, img) {
  6001. if (Tools.CorsBehavior) {
  6002. switch (typeof (Tools.CorsBehavior)) {
  6003. case "function":
  6004. var result = Tools.CorsBehavior(url);
  6005. if (result) {
  6006. img.crossOrigin = result;
  6007. }
  6008. break;
  6009. case "string":
  6010. default:
  6011. img.crossOrigin = Tools.CorsBehavior;
  6012. break;
  6013. }
  6014. }
  6015. };
  6016. // External files
  6017. Tools.CleanUrl = function (url) {
  6018. url = url.replace(/#/mg, "%23");
  6019. return url;
  6020. };
  6021. Tools.LoadImage = function (url, onLoad, onError, database) {
  6022. if (url instanceof ArrayBuffer) {
  6023. url = Tools.EncodeArrayBufferTobase64(url);
  6024. }
  6025. url = Tools.CleanUrl(url);
  6026. url = Tools.PreprocessUrl(url);
  6027. var img = new Image();
  6028. if (url.substr(0, 5) !== "data:") {
  6029. Tools.SetCorsBehavior(url, img);
  6030. }
  6031. img.onload = function () {
  6032. onLoad(img);
  6033. };
  6034. img.onerror = function (err) {
  6035. Tools.Error("Error while trying to load image: " + url);
  6036. if (Tools.UseFallbackTexture) {
  6037. img.src = Tools.fallbackTexture;
  6038. onLoad(img);
  6039. }
  6040. else {
  6041. onError("Error while trying to load image: " + url, err);
  6042. }
  6043. };
  6044. var noIndexedDB = function () {
  6045. img.src = url;
  6046. };
  6047. var loadFromIndexedDB = function () {
  6048. database.loadImageFromDB(url, img);
  6049. };
  6050. //ANY database to do!
  6051. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6052. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6053. }
  6054. else {
  6055. if (url.indexOf("file:") !== 0) {
  6056. noIndexedDB();
  6057. }
  6058. else {
  6059. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  6060. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6061. try {
  6062. var blobURL;
  6063. try {
  6064. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  6065. }
  6066. catch (ex) {
  6067. // Chrome doesn't support oneTimeOnly parameter
  6068. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  6069. }
  6070. img.src = blobURL;
  6071. }
  6072. catch (e) {
  6073. img.src = null;
  6074. }
  6075. }
  6076. else {
  6077. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6078. img.src = Tools.fallbackTexture;
  6079. }
  6080. }
  6081. }
  6082. return img;
  6083. };
  6084. //ANY
  6085. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6086. url = Tools.CleanUrl(url);
  6087. url = Tools.PreprocessUrl(url);
  6088. var noIndexedDB = function () {
  6089. var request = new XMLHttpRequest();
  6090. var loadUrl = Tools.BaseUrl + url;
  6091. request.open('GET', loadUrl, true);
  6092. if (useArrayBuffer) {
  6093. request.responseType = "arraybuffer";
  6094. }
  6095. request.onprogress = progressCallBack;
  6096. request.onreadystatechange = function () {
  6097. // In case of undefined state in some browsers.
  6098. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  6099. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6100. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  6101. callback(!useArrayBuffer ? request.responseText : request.response);
  6102. }
  6103. else {
  6104. var e = new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  6105. if (onError) {
  6106. onError(request, e);
  6107. }
  6108. else {
  6109. throw e;
  6110. }
  6111. }
  6112. }
  6113. };
  6114. request.send(null);
  6115. };
  6116. var loadFromIndexedDB = function () {
  6117. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6118. };
  6119. if (url.indexOf("file:") !== -1) {
  6120. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6121. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6122. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6123. }
  6124. else {
  6125. var errorMessage = "File: " + fileName + " not found. Did you forget to provide it?";
  6126. if (onError) {
  6127. var e = new Error(errorMessage);
  6128. onError(undefined, e);
  6129. }
  6130. else {
  6131. Tools.Error(errorMessage);
  6132. }
  6133. }
  6134. }
  6135. else {
  6136. // Caching all files
  6137. if (database && database.enableSceneOffline) {
  6138. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6139. }
  6140. else {
  6141. noIndexedDB();
  6142. }
  6143. }
  6144. };
  6145. /**
  6146. * Load a script (identified by an url). When the url returns, the
  6147. * content of this file is added into a new script element, attached to the DOM (body element)
  6148. */
  6149. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6150. var head = document.getElementsByTagName('head')[0];
  6151. var script = document.createElement('script');
  6152. script.type = 'text/javascript';
  6153. script.src = scriptUrl;
  6154. script.onload = function () {
  6155. if (onSuccess) {
  6156. onSuccess();
  6157. }
  6158. };
  6159. script.onerror = function (e) {
  6160. if (onError) {
  6161. onError("Unable to load script", e);
  6162. }
  6163. };
  6164. head.appendChild(script);
  6165. };
  6166. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6167. var reader = new FileReader();
  6168. reader.onload = function (e) {
  6169. //target doesn't have result from ts 1.3
  6170. callback(e.target['result']);
  6171. };
  6172. reader.onprogress = progressCallback;
  6173. reader.readAsDataURL(fileToLoad);
  6174. };
  6175. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6176. var reader = new FileReader();
  6177. reader.onerror = function (e) {
  6178. Tools.Log("Error while reading file: " + fileToLoad.name);
  6179. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6180. };
  6181. reader.onload = function (e) {
  6182. //target doesn't have result from ts 1.3
  6183. callback(e.target['result']);
  6184. };
  6185. reader.onprogress = progressCallBack;
  6186. if (!useArrayBuffer) {
  6187. // Asynchronous read
  6188. reader.readAsText(fileToLoad);
  6189. }
  6190. else {
  6191. reader.readAsArrayBuffer(fileToLoad);
  6192. }
  6193. };
  6194. //returns a downloadable url to a file content.
  6195. Tools.FileAsURL = function (content) {
  6196. var fileBlob = new Blob([content]);
  6197. var url = window.URL || window.webkitURL;
  6198. var link = url.createObjectURL(fileBlob);
  6199. return link;
  6200. };
  6201. // Misc.
  6202. Tools.Format = function (value, decimals) {
  6203. if (decimals === void 0) { decimals = 2; }
  6204. return value.toFixed(decimals);
  6205. };
  6206. Tools.CheckExtends = function (v, min, max) {
  6207. if (v.x < min.x)
  6208. min.x = v.x;
  6209. if (v.y < min.y)
  6210. min.y = v.y;
  6211. if (v.z < min.z)
  6212. min.z = v.z;
  6213. if (v.x > max.x)
  6214. max.x = v.x;
  6215. if (v.y > max.y)
  6216. max.y = v.y;
  6217. if (v.z > max.z)
  6218. max.z = v.z;
  6219. };
  6220. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6221. for (var prop in source) {
  6222. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6223. continue;
  6224. }
  6225. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6226. continue;
  6227. }
  6228. var sourceValue = source[prop];
  6229. var typeOfSourceValue = typeof sourceValue;
  6230. if (typeOfSourceValue === "function") {
  6231. continue;
  6232. }
  6233. if (typeOfSourceValue === "object") {
  6234. if (sourceValue instanceof Array) {
  6235. destination[prop] = [];
  6236. if (sourceValue.length > 0) {
  6237. if (typeof sourceValue[0] == "object") {
  6238. for (var index = 0; index < sourceValue.length; index++) {
  6239. var clonedValue = cloneValue(sourceValue[index], destination);
  6240. if (destination[prop].indexOf(clonedValue) === -1) {
  6241. destination[prop].push(clonedValue);
  6242. }
  6243. }
  6244. }
  6245. else {
  6246. destination[prop] = sourceValue.slice(0);
  6247. }
  6248. }
  6249. }
  6250. else {
  6251. destination[prop] = cloneValue(sourceValue, destination);
  6252. }
  6253. }
  6254. else {
  6255. destination[prop] = sourceValue;
  6256. }
  6257. }
  6258. };
  6259. Tools.IsEmpty = function (obj) {
  6260. for (var i in obj) {
  6261. if (obj.hasOwnProperty(i)) {
  6262. return false;
  6263. }
  6264. }
  6265. return true;
  6266. };
  6267. Tools.RegisterTopRootEvents = function (events) {
  6268. for (var index = 0; index < events.length; index++) {
  6269. var event = events[index];
  6270. window.addEventListener(event.name, event.handler, false);
  6271. try {
  6272. if (window.parent) {
  6273. window.parent.addEventListener(event.name, event.handler, false);
  6274. }
  6275. }
  6276. catch (e) {
  6277. // Silently fails...
  6278. }
  6279. }
  6280. };
  6281. Tools.UnregisterTopRootEvents = function (events) {
  6282. for (var index = 0; index < events.length; index++) {
  6283. var event = events[index];
  6284. window.removeEventListener(event.name, event.handler);
  6285. try {
  6286. if (window.parent) {
  6287. window.parent.removeEventListener(event.name, event.handler);
  6288. }
  6289. }
  6290. catch (e) {
  6291. // Silently fails...
  6292. }
  6293. }
  6294. };
  6295. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6296. if (mimeType === void 0) { mimeType = "image/png"; }
  6297. // Read the contents of the framebuffer
  6298. var numberOfChannelsByLine = width * 4;
  6299. var halfHeight = height / 2;
  6300. //Reading datas from WebGL
  6301. var data = engine.readPixels(0, 0, width, height);
  6302. //To flip image on Y axis.
  6303. for (var i = 0; i < halfHeight; i++) {
  6304. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6305. var currentCell = j + i * numberOfChannelsByLine;
  6306. var targetLine = height - i - 1;
  6307. var targetCell = j + targetLine * numberOfChannelsByLine;
  6308. var temp = data[currentCell];
  6309. data[currentCell] = data[targetCell];
  6310. data[targetCell] = temp;
  6311. }
  6312. }
  6313. // Create a 2D canvas to store the result
  6314. if (!screenshotCanvas) {
  6315. screenshotCanvas = document.createElement('canvas');
  6316. }
  6317. screenshotCanvas.width = width;
  6318. screenshotCanvas.height = height;
  6319. var context = screenshotCanvas.getContext('2d');
  6320. // Copy the pixels to a 2D canvas
  6321. var imageData = context.createImageData(width, height);
  6322. var castData = (imageData.data);
  6323. castData.set(data);
  6324. context.putImageData(imageData, 0, 0);
  6325. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6326. };
  6327. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6328. if (mimeType === void 0) { mimeType = "image/png"; }
  6329. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6330. if (successCallback) {
  6331. successCallback(base64Image);
  6332. }
  6333. else {
  6334. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6335. if (("download" in document.createElement("a"))) {
  6336. var a = window.document.createElement("a");
  6337. a.href = base64Image;
  6338. var date = new Date();
  6339. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6340. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6341. window.document.body.appendChild(a);
  6342. a.addEventListener("click", function () {
  6343. a.parentElement.removeChild(a);
  6344. });
  6345. a.click();
  6346. //Or opening a new tab with the image if it is not possible to automatically start download.
  6347. }
  6348. else {
  6349. var newWindow = window.open("");
  6350. var img = newWindow.document.createElement("img");
  6351. img.src = base64Image;
  6352. newWindow.document.body.appendChild(img);
  6353. }
  6354. }
  6355. };
  6356. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6357. if (mimeType === void 0) { mimeType = "image/png"; }
  6358. var width;
  6359. var height;
  6360. // If a precision value is specified
  6361. if (size.precision) {
  6362. width = Math.round(engine.getRenderWidth() * size.precision);
  6363. height = Math.round(width / engine.getAspectRatio(camera));
  6364. }
  6365. else if (size.width && size.height) {
  6366. width = size.width;
  6367. height = size.height;
  6368. }
  6369. else if (size.width && !size.height) {
  6370. width = size.width;
  6371. height = Math.round(width / engine.getAspectRatio(camera));
  6372. }
  6373. else if (size.height && !size.width) {
  6374. height = size.height;
  6375. width = Math.round(height * engine.getAspectRatio(camera));
  6376. }
  6377. else if (!isNaN(size)) {
  6378. height = size;
  6379. width = size;
  6380. }
  6381. else {
  6382. Tools.Error("Invalid 'size' parameter !");
  6383. return;
  6384. }
  6385. if (!screenshotCanvas) {
  6386. screenshotCanvas = document.createElement('canvas');
  6387. }
  6388. screenshotCanvas.width = width;
  6389. screenshotCanvas.height = height;
  6390. var renderContext = screenshotCanvas.getContext("2d");
  6391. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6392. var newWidth = width;
  6393. var newHeight = newWidth / ratio;
  6394. if (newHeight > height) {
  6395. newHeight = height;
  6396. newWidth = newHeight * ratio;
  6397. }
  6398. var offsetX = Math.max(0, width - newWidth) / 2;
  6399. var offsetY = Math.max(0, height - newHeight) / 2;
  6400. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6401. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6402. };
  6403. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6404. if (mimeType === void 0) { mimeType = "image/png"; }
  6405. if (samples === void 0) { samples = 1; }
  6406. var width;
  6407. var height;
  6408. //If a precision value is specified
  6409. if (size.precision) {
  6410. width = Math.round(engine.getRenderWidth() * size.precision);
  6411. height = Math.round(width / engine.getAspectRatio(camera));
  6412. size = { width: width, height: height };
  6413. }
  6414. else if (size.width && size.height) {
  6415. width = size.width;
  6416. height = size.height;
  6417. }
  6418. else if (size.width && !size.height) {
  6419. width = size.width;
  6420. height = Math.round(width / engine.getAspectRatio(camera));
  6421. size = { width: width, height: height };
  6422. }
  6423. else if (size.height && !size.width) {
  6424. height = size.height;
  6425. width = Math.round(height * engine.getAspectRatio(camera));
  6426. size = { width: width, height: height };
  6427. }
  6428. else if (!isNaN(size)) {
  6429. height = size;
  6430. width = size;
  6431. }
  6432. else {
  6433. Tools.Error("Invalid 'size' parameter !");
  6434. return;
  6435. }
  6436. var scene = camera.getScene();
  6437. var previousCamera = null;
  6438. if (scene.activeCamera !== camera) {
  6439. previousCamera = scene.activeCamera;
  6440. scene.activeCamera = camera;
  6441. }
  6442. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6443. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6444. texture.renderList = null;
  6445. texture.samples = samples;
  6446. texture.onAfterRenderObservable.add(function () {
  6447. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6448. });
  6449. scene.incrementRenderId();
  6450. scene.resetCachedMaterial();
  6451. texture.render(true);
  6452. texture.dispose();
  6453. if (previousCamera) {
  6454. scene.activeCamera = previousCamera;
  6455. }
  6456. camera.getProjectionMatrix(true); // Force cache refresh;
  6457. };
  6458. // XHR response validator for local file scenario
  6459. Tools.ValidateXHRData = function (xhr, dataType) {
  6460. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6461. if (dataType === void 0) { dataType = 7; }
  6462. try {
  6463. if (dataType & 1) {
  6464. if (xhr.responseText && xhr.responseText.length > 0) {
  6465. return true;
  6466. }
  6467. else if (dataType === 1) {
  6468. return false;
  6469. }
  6470. }
  6471. if (dataType & 2) {
  6472. // Check header width and height since there is no "TGA" magic number
  6473. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6474. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6475. return true;
  6476. }
  6477. else if (dataType === 2) {
  6478. return false;
  6479. }
  6480. }
  6481. if (dataType & 4) {
  6482. // Check for the "DDS" magic number
  6483. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6484. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6485. return true;
  6486. }
  6487. else {
  6488. return false;
  6489. }
  6490. }
  6491. }
  6492. catch (e) {
  6493. // Global protection
  6494. }
  6495. return false;
  6496. };
  6497. /**
  6498. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6499. * Be aware Math.random() could cause collisions, but:
  6500. * "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"
  6501. */
  6502. Tools.RandomId = function () {
  6503. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6504. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6505. return v.toString(16);
  6506. });
  6507. };
  6508. Object.defineProperty(Tools, "NoneLogLevel", {
  6509. get: function () {
  6510. return Tools._NoneLogLevel;
  6511. },
  6512. enumerable: true,
  6513. configurable: true
  6514. });
  6515. Object.defineProperty(Tools, "MessageLogLevel", {
  6516. get: function () {
  6517. return Tools._MessageLogLevel;
  6518. },
  6519. enumerable: true,
  6520. configurable: true
  6521. });
  6522. Object.defineProperty(Tools, "WarningLogLevel", {
  6523. get: function () {
  6524. return Tools._WarningLogLevel;
  6525. },
  6526. enumerable: true,
  6527. configurable: true
  6528. });
  6529. Object.defineProperty(Tools, "ErrorLogLevel", {
  6530. get: function () {
  6531. return Tools._ErrorLogLevel;
  6532. },
  6533. enumerable: true,
  6534. configurable: true
  6535. });
  6536. Object.defineProperty(Tools, "AllLogLevel", {
  6537. get: function () {
  6538. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6539. },
  6540. enumerable: true,
  6541. configurable: true
  6542. });
  6543. Tools._AddLogEntry = function (entry) {
  6544. Tools._LogCache = entry + Tools._LogCache;
  6545. if (Tools.OnNewCacheEntry) {
  6546. Tools.OnNewCacheEntry(entry);
  6547. }
  6548. };
  6549. Tools._FormatMessage = function (message) {
  6550. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6551. var date = new Date();
  6552. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6553. };
  6554. Tools._LogDisabled = function (message) {
  6555. // nothing to do
  6556. };
  6557. Tools._LogEnabled = function (message) {
  6558. var formattedMessage = Tools._FormatMessage(message);
  6559. console.log("BJS - " + formattedMessage);
  6560. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6561. Tools._AddLogEntry(entry);
  6562. };
  6563. Tools._WarnDisabled = function (message) {
  6564. // nothing to do
  6565. };
  6566. Tools._WarnEnabled = function (message) {
  6567. var formattedMessage = Tools._FormatMessage(message);
  6568. console.warn("BJS - " + formattedMessage);
  6569. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6570. Tools._AddLogEntry(entry);
  6571. };
  6572. Tools._ErrorDisabled = function (message) {
  6573. // nothing to do
  6574. };
  6575. Tools._ErrorEnabled = function (message) {
  6576. Tools.errorsCount++;
  6577. var formattedMessage = Tools._FormatMessage(message);
  6578. console.error("BJS - " + formattedMessage);
  6579. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6580. Tools._AddLogEntry(entry);
  6581. };
  6582. Object.defineProperty(Tools, "LogCache", {
  6583. get: function () {
  6584. return Tools._LogCache;
  6585. },
  6586. enumerable: true,
  6587. configurable: true
  6588. });
  6589. Tools.ClearLogCache = function () {
  6590. Tools._LogCache = "";
  6591. Tools.errorsCount = 0;
  6592. };
  6593. Object.defineProperty(Tools, "LogLevels", {
  6594. set: function (level) {
  6595. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6596. Tools.Log = Tools._LogEnabled;
  6597. }
  6598. else {
  6599. Tools.Log = Tools._LogDisabled;
  6600. }
  6601. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6602. Tools.Warn = Tools._WarnEnabled;
  6603. }
  6604. else {
  6605. Tools.Warn = Tools._WarnDisabled;
  6606. }
  6607. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6608. Tools.Error = Tools._ErrorEnabled;
  6609. }
  6610. else {
  6611. Tools.Error = Tools._ErrorDisabled;
  6612. }
  6613. },
  6614. enumerable: true,
  6615. configurable: true
  6616. });
  6617. Tools.IsWindowObjectExist = function () {
  6618. return (typeof window) !== "undefined";
  6619. };
  6620. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6621. get: function () {
  6622. return Tools._PerformanceNoneLogLevel;
  6623. },
  6624. enumerable: true,
  6625. configurable: true
  6626. });
  6627. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6628. get: function () {
  6629. return Tools._PerformanceUserMarkLogLevel;
  6630. },
  6631. enumerable: true,
  6632. configurable: true
  6633. });
  6634. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6635. get: function () {
  6636. return Tools._PerformanceConsoleLogLevel;
  6637. },
  6638. enumerable: true,
  6639. configurable: true
  6640. });
  6641. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6642. set: function (level) {
  6643. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6644. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6645. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6646. return;
  6647. }
  6648. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6649. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6650. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6651. return;
  6652. }
  6653. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6654. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6655. },
  6656. enumerable: true,
  6657. configurable: true
  6658. });
  6659. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6660. };
  6661. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6662. };
  6663. Tools._StartUserMark = function (counterName, condition) {
  6664. if (condition === void 0) { condition = true; }
  6665. if (!Tools._performance) {
  6666. if (!Tools.IsWindowObjectExist()) {
  6667. return;
  6668. }
  6669. Tools._performance = window.performance;
  6670. }
  6671. if (!condition || !Tools._performance.mark) {
  6672. return;
  6673. }
  6674. Tools._performance.mark(counterName + "-Begin");
  6675. };
  6676. Tools._EndUserMark = function (counterName, condition) {
  6677. if (condition === void 0) { condition = true; }
  6678. if (!condition || !Tools._performance.mark) {
  6679. return;
  6680. }
  6681. Tools._performance.mark(counterName + "-End");
  6682. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6683. };
  6684. Tools._StartPerformanceConsole = function (counterName, condition) {
  6685. if (condition === void 0) { condition = true; }
  6686. if (!condition) {
  6687. return;
  6688. }
  6689. Tools._StartUserMark(counterName, condition);
  6690. if (console.time) {
  6691. console.time(counterName);
  6692. }
  6693. };
  6694. Tools._EndPerformanceConsole = function (counterName, condition) {
  6695. if (condition === void 0) { condition = true; }
  6696. if (!condition) {
  6697. return;
  6698. }
  6699. Tools._EndUserMark(counterName, condition);
  6700. if (console.time) {
  6701. console.timeEnd(counterName);
  6702. }
  6703. };
  6704. Object.defineProperty(Tools, "Now", {
  6705. get: function () {
  6706. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6707. return window.performance.now();
  6708. }
  6709. return new Date().getTime();
  6710. },
  6711. enumerable: true,
  6712. configurable: true
  6713. });
  6714. /**
  6715. * This method will return the name of the class used to create the instance of the given object.
  6716. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6717. * @param object the object to get the class name from
  6718. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6719. */
  6720. Tools.GetClassName = function (object, isType) {
  6721. if (isType === void 0) { isType = false; }
  6722. var name = null;
  6723. if (!isType && object.getClassName) {
  6724. name = object.getClassName();
  6725. }
  6726. else {
  6727. if (object instanceof Object) {
  6728. var classObj = isType ? object : Object.getPrototypeOf(object);
  6729. name = classObj.constructor["__bjsclassName__"];
  6730. }
  6731. if (!name) {
  6732. name = typeof object;
  6733. }
  6734. }
  6735. return name;
  6736. };
  6737. Tools.First = function (array, predicate) {
  6738. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6739. var el = array_1[_i];
  6740. if (predicate(el)) {
  6741. return el;
  6742. }
  6743. }
  6744. return null;
  6745. };
  6746. /**
  6747. * This method will return the name of the full name of the class, including its owning module (if any).
  6748. * 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).
  6749. * @param object the object to get the class name from
  6750. * @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.
  6751. */
  6752. Tools.getFullClassName = function (object, isType) {
  6753. if (isType === void 0) { isType = false; }
  6754. var className = null;
  6755. var moduleName = null;
  6756. if (!isType && object.getClassName) {
  6757. className = object.getClassName();
  6758. }
  6759. else {
  6760. if (object instanceof Object) {
  6761. var classObj = isType ? object : Object.getPrototypeOf(object);
  6762. className = classObj.constructor["__bjsclassName__"];
  6763. moduleName = classObj.constructor["__bjsmoduleName__"];
  6764. }
  6765. if (!className) {
  6766. className = typeof object;
  6767. }
  6768. }
  6769. if (!className) {
  6770. return null;
  6771. }
  6772. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6773. };
  6774. /**
  6775. * 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.
  6776. * @param array
  6777. */
  6778. Tools.arrayOrStringFeeder = function (array) {
  6779. return function (index) {
  6780. if (index >= array.length) {
  6781. return null;
  6782. }
  6783. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6784. if (val && val.getHashCode) {
  6785. val = val.getHashCode();
  6786. }
  6787. if (typeof val === "string") {
  6788. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6789. }
  6790. return val;
  6791. };
  6792. };
  6793. /**
  6794. * Compute the hashCode of a stream of number
  6795. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6796. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6797. * @return the hash code computed
  6798. */
  6799. Tools.hashCodeFromStream = function (feeder) {
  6800. // Based from here: http://stackoverflow.com/a/7616484/802124
  6801. var hash = 0;
  6802. var index = 0;
  6803. var chr = feeder(index++);
  6804. while (chr != null) {
  6805. hash = ((hash << 5) - hash) + chr;
  6806. hash |= 0; // Convert to 32bit integer
  6807. chr = feeder(index++);
  6808. }
  6809. return hash;
  6810. };
  6811. Tools.BaseUrl = "";
  6812. Tools.CorsBehavior = "anonymous";
  6813. Tools.UseFallbackTexture = true;
  6814. /**
  6815. * Use this object to register external classes like custom textures or material
  6816. * to allow the laoders to instantiate them
  6817. */
  6818. Tools.RegisteredExternalClasses = {};
  6819. // Used in case of a texture loading problem
  6820. 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";
  6821. Tools.PreprocessUrl = function (url) {
  6822. return url;
  6823. };
  6824. // Logs
  6825. Tools._NoneLogLevel = 0;
  6826. Tools._MessageLogLevel = 1;
  6827. Tools._WarningLogLevel = 2;
  6828. Tools._ErrorLogLevel = 4;
  6829. Tools._LogCache = "";
  6830. Tools.errorsCount = 0;
  6831. Tools.Log = Tools._LogEnabled;
  6832. Tools.Warn = Tools._WarnEnabled;
  6833. Tools.Error = Tools._ErrorEnabled;
  6834. // Performances
  6835. Tools._PerformanceNoneLogLevel = 0;
  6836. Tools._PerformanceUserMarkLogLevel = 1;
  6837. Tools._PerformanceConsoleLogLevel = 2;
  6838. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6839. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6840. return Tools;
  6841. }());
  6842. BABYLON.Tools = Tools;
  6843. /**
  6844. * This class is used to track a performance counter which is number based.
  6845. * The user has access to many properties which give statistics of different nature
  6846. *
  6847. * The implementer can track two kinds of Performance Counter: time and count
  6848. * 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.
  6849. * 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.
  6850. */
  6851. var PerfCounter = (function () {
  6852. function PerfCounter() {
  6853. this._startMonitoringTime = 0;
  6854. this._min = 0;
  6855. this._max = 0;
  6856. this._average = 0;
  6857. this._lastSecAverage = 0;
  6858. this._current = 0;
  6859. this._totalValueCount = 0;
  6860. this._totalAccumulated = 0;
  6861. this._lastSecAccumulated = 0;
  6862. this._lastSecTime = 0;
  6863. this._lastSecValueCount = 0;
  6864. }
  6865. Object.defineProperty(PerfCounter.prototype, "min", {
  6866. /**
  6867. * Returns the smallest value ever
  6868. */
  6869. get: function () {
  6870. return this._min;
  6871. },
  6872. enumerable: true,
  6873. configurable: true
  6874. });
  6875. Object.defineProperty(PerfCounter.prototype, "max", {
  6876. /**
  6877. * Returns the biggest value ever
  6878. */
  6879. get: function () {
  6880. return this._max;
  6881. },
  6882. enumerable: true,
  6883. configurable: true
  6884. });
  6885. Object.defineProperty(PerfCounter.prototype, "average", {
  6886. /**
  6887. * Returns the average value since the performance counter is running
  6888. */
  6889. get: function () {
  6890. return this._average;
  6891. },
  6892. enumerable: true,
  6893. configurable: true
  6894. });
  6895. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6896. /**
  6897. * Returns the average value of the last second the counter was monitored
  6898. */
  6899. get: function () {
  6900. return this._lastSecAverage;
  6901. },
  6902. enumerable: true,
  6903. configurable: true
  6904. });
  6905. Object.defineProperty(PerfCounter.prototype, "current", {
  6906. /**
  6907. * Returns the current value
  6908. */
  6909. get: function () {
  6910. return this._current;
  6911. },
  6912. enumerable: true,
  6913. configurable: true
  6914. });
  6915. Object.defineProperty(PerfCounter.prototype, "total", {
  6916. get: function () {
  6917. return this._totalAccumulated;
  6918. },
  6919. enumerable: true,
  6920. configurable: true
  6921. });
  6922. /**
  6923. * Call this method to start monitoring a new frame.
  6924. * 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.
  6925. */
  6926. PerfCounter.prototype.fetchNewFrame = function () {
  6927. this._totalValueCount++;
  6928. this._current = 0;
  6929. this._lastSecValueCount++;
  6930. };
  6931. /**
  6932. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6933. * @param newCount the count value to add to the monitored count
  6934. * @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.
  6935. */
  6936. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6937. if (!PerfCounter.Enabled) {
  6938. return;
  6939. }
  6940. this._current += newCount;
  6941. if (fetchResult) {
  6942. this._fetchResult();
  6943. }
  6944. };
  6945. /**
  6946. * Start monitoring this performance counter
  6947. */
  6948. PerfCounter.prototype.beginMonitoring = function () {
  6949. if (!PerfCounter.Enabled) {
  6950. return;
  6951. }
  6952. this._startMonitoringTime = Tools.Now;
  6953. };
  6954. /**
  6955. * Compute the time lapsed since the previous beginMonitoring() call.
  6956. * @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
  6957. */
  6958. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6959. if (newFrame === void 0) { newFrame = true; }
  6960. if (!PerfCounter.Enabled) {
  6961. return;
  6962. }
  6963. if (newFrame) {
  6964. this.fetchNewFrame();
  6965. }
  6966. var currentTime = Tools.Now;
  6967. this._current = currentTime - this._startMonitoringTime;
  6968. if (newFrame) {
  6969. this._fetchResult();
  6970. }
  6971. };
  6972. PerfCounter.prototype._fetchResult = function () {
  6973. this._totalAccumulated += this._current;
  6974. this._lastSecAccumulated += this._current;
  6975. // Min/Max update
  6976. this._min = Math.min(this._min, this._current);
  6977. this._max = Math.max(this._max, this._current);
  6978. this._average = this._totalAccumulated / this._totalValueCount;
  6979. // Reset last sec?
  6980. var now = Tools.Now;
  6981. if ((now - this._lastSecTime) > 1000) {
  6982. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6983. this._lastSecTime = now;
  6984. this._lastSecAccumulated = 0;
  6985. this._lastSecValueCount = 0;
  6986. }
  6987. };
  6988. PerfCounter.Enabled = true;
  6989. return PerfCounter;
  6990. }());
  6991. BABYLON.PerfCounter = PerfCounter;
  6992. /**
  6993. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6994. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6995. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6996. * @param name The name of the class, case should be preserved
  6997. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6998. */
  6999. function className(name, module) {
  7000. return function (target) {
  7001. target["__bjsclassName__"] = name;
  7002. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7003. };
  7004. }
  7005. BABYLON.className = className;
  7006. /**
  7007. * An implementation of a loop for asynchronous functions.
  7008. */
  7009. var AsyncLoop = (function () {
  7010. /**
  7011. * Constroctor.
  7012. * @param iterations the number of iterations.
  7013. * @param _fn the function to run each iteration
  7014. * @param _successCallback the callback that will be called upon succesful execution
  7015. * @param offset starting offset.
  7016. */
  7017. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7018. if (offset === void 0) { offset = 0; }
  7019. this.iterations = iterations;
  7020. this._fn = _fn;
  7021. this._successCallback = _successCallback;
  7022. this.index = offset - 1;
  7023. this._done = false;
  7024. }
  7025. /**
  7026. * Execute the next iteration. Must be called after the last iteration was finished.
  7027. */
  7028. AsyncLoop.prototype.executeNext = function () {
  7029. if (!this._done) {
  7030. if (this.index + 1 < this.iterations) {
  7031. ++this.index;
  7032. this._fn(this);
  7033. }
  7034. else {
  7035. this.breakLoop();
  7036. }
  7037. }
  7038. };
  7039. /**
  7040. * Break the loop and run the success callback.
  7041. */
  7042. AsyncLoop.prototype.breakLoop = function () {
  7043. this._done = true;
  7044. this._successCallback();
  7045. };
  7046. /**
  7047. * Helper function
  7048. */
  7049. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7050. if (offset === void 0) { offset = 0; }
  7051. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7052. loop.executeNext();
  7053. return loop;
  7054. };
  7055. /**
  7056. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7057. * @param iterations total number of iterations
  7058. * @param syncedIterations number of synchronous iterations in each async iteration.
  7059. * @param fn the function to call each iteration.
  7060. * @param callback a success call back that will be called when iterating stops.
  7061. * @param breakFunction a break condition (optional)
  7062. * @param timeout timeout settings for the setTimeout function. default - 0.
  7063. * @constructor
  7064. */
  7065. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7066. if (timeout === void 0) { timeout = 0; }
  7067. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7068. if (breakFunction && breakFunction())
  7069. loop.breakLoop();
  7070. else {
  7071. setTimeout(function () {
  7072. for (var i = 0; i < syncedIterations; ++i) {
  7073. var iteration = (loop.index * syncedIterations) + i;
  7074. if (iteration >= iterations)
  7075. break;
  7076. fn(iteration);
  7077. if (breakFunction && breakFunction()) {
  7078. loop.breakLoop();
  7079. break;
  7080. }
  7081. }
  7082. loop.executeNext();
  7083. }, timeout);
  7084. }
  7085. }, callback);
  7086. };
  7087. return AsyncLoop;
  7088. }());
  7089. BABYLON.AsyncLoop = AsyncLoop;
  7090. })(BABYLON || (BABYLON = {}));
  7091. //# sourceMappingURL=babylon.tools.js.map
  7092. var BABYLON;
  7093. (function (BABYLON) {
  7094. var Internals;
  7095. (function (Internals) {
  7096. var _AlphaState = (function () {
  7097. /**
  7098. * Initializes the state.
  7099. */
  7100. function _AlphaState() {
  7101. this._isAlphaBlendDirty = false;
  7102. this._isBlendFunctionParametersDirty = false;
  7103. this._isBlendEquationParametersDirty = false;
  7104. this._isBlendConstantsDirty = false;
  7105. this._alphaBlend = false;
  7106. this._blendFunctionParameters = new Array(4);
  7107. this._blendEquationParameters = new Array(2);
  7108. this._blendConstants = new Array(4);
  7109. this.reset();
  7110. }
  7111. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7112. get: function () {
  7113. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7114. },
  7115. enumerable: true,
  7116. configurable: true
  7117. });
  7118. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7119. get: function () {
  7120. return this._alphaBlend;
  7121. },
  7122. set: function (value) {
  7123. if (this._alphaBlend === value) {
  7124. return;
  7125. }
  7126. this._alphaBlend = value;
  7127. this._isAlphaBlendDirty = true;
  7128. },
  7129. enumerable: true,
  7130. configurable: true
  7131. });
  7132. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7133. if (this._blendConstants[0] === r &&
  7134. this._blendConstants[1] === g &&
  7135. this._blendConstants[2] === b &&
  7136. this._blendConstants[3] === a) {
  7137. return;
  7138. }
  7139. this._blendConstants[0] = r;
  7140. this._blendConstants[1] = g;
  7141. this._blendConstants[2] = b;
  7142. this._blendConstants[3] = a;
  7143. this._isBlendConstantsDirty = true;
  7144. };
  7145. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7146. if (this._blendFunctionParameters[0] === value0 &&
  7147. this._blendFunctionParameters[1] === value1 &&
  7148. this._blendFunctionParameters[2] === value2 &&
  7149. this._blendFunctionParameters[3] === value3) {
  7150. return;
  7151. }
  7152. this._blendFunctionParameters[0] = value0;
  7153. this._blendFunctionParameters[1] = value1;
  7154. this._blendFunctionParameters[2] = value2;
  7155. this._blendFunctionParameters[3] = value3;
  7156. this._isBlendFunctionParametersDirty = true;
  7157. };
  7158. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7159. if (this._blendEquationParameters[0] === rgb &&
  7160. this._blendEquationParameters[1] === alpha) {
  7161. return;
  7162. }
  7163. this._blendEquationParameters[0] = rgb;
  7164. this._blendEquationParameters[1] = alpha;
  7165. this._isBlendEquationParametersDirty = true;
  7166. };
  7167. _AlphaState.prototype.reset = function () {
  7168. this._alphaBlend = false;
  7169. this._blendFunctionParameters[0] = null;
  7170. this._blendFunctionParameters[1] = null;
  7171. this._blendFunctionParameters[2] = null;
  7172. this._blendFunctionParameters[3] = null;
  7173. this._blendEquationParameters[0] = null;
  7174. this._blendEquationParameters[1] = null;
  7175. this._blendConstants[0] = null;
  7176. this._blendConstants[1] = null;
  7177. this._blendConstants[2] = null;
  7178. this._blendConstants[3] = null;
  7179. this._isAlphaBlendDirty = true;
  7180. this._isBlendFunctionParametersDirty = false;
  7181. this._isBlendEquationParametersDirty = false;
  7182. this._isBlendConstantsDirty = false;
  7183. };
  7184. _AlphaState.prototype.apply = function (gl) {
  7185. if (!this.isDirty) {
  7186. return;
  7187. }
  7188. // Alpha blend
  7189. if (this._isAlphaBlendDirty) {
  7190. if (this._alphaBlend) {
  7191. gl.enable(gl.BLEND);
  7192. }
  7193. else {
  7194. gl.disable(gl.BLEND);
  7195. }
  7196. this._isAlphaBlendDirty = false;
  7197. }
  7198. // Alpha function
  7199. if (this._isBlendFunctionParametersDirty) {
  7200. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7201. this._isBlendFunctionParametersDirty = false;
  7202. }
  7203. // Alpha equation
  7204. if (this._isBlendEquationParametersDirty) {
  7205. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7206. this._isBlendEquationParametersDirty = false;
  7207. }
  7208. // Constants
  7209. if (this._isBlendConstantsDirty) {
  7210. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7211. this._isBlendConstantsDirty = false;
  7212. }
  7213. };
  7214. return _AlphaState;
  7215. }());
  7216. Internals._AlphaState = _AlphaState;
  7217. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7218. })(BABYLON || (BABYLON = {}));
  7219. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7220. var BABYLON;
  7221. (function (BABYLON) {
  7222. var Internals;
  7223. (function (Internals) {
  7224. var _DepthCullingState = (function () {
  7225. /**
  7226. * Initializes the state.
  7227. */
  7228. function _DepthCullingState() {
  7229. this._isDepthTestDirty = false;
  7230. this._isDepthMaskDirty = false;
  7231. this._isDepthFuncDirty = false;
  7232. this._isCullFaceDirty = false;
  7233. this._isCullDirty = false;
  7234. this._isZOffsetDirty = false;
  7235. this.reset();
  7236. }
  7237. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7238. get: function () {
  7239. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7240. },
  7241. enumerable: true,
  7242. configurable: true
  7243. });
  7244. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7245. get: function () {
  7246. return this._zOffset;
  7247. },
  7248. set: function (value) {
  7249. if (this._zOffset === value) {
  7250. return;
  7251. }
  7252. this._zOffset = value;
  7253. this._isZOffsetDirty = true;
  7254. },
  7255. enumerable: true,
  7256. configurable: true
  7257. });
  7258. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7259. get: function () {
  7260. return this._cullFace;
  7261. },
  7262. set: function (value) {
  7263. if (this._cullFace === value) {
  7264. return;
  7265. }
  7266. this._cullFace = value;
  7267. this._isCullFaceDirty = true;
  7268. },
  7269. enumerable: true,
  7270. configurable: true
  7271. });
  7272. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7273. get: function () {
  7274. return this._cull;
  7275. },
  7276. set: function (value) {
  7277. if (this._cull === value) {
  7278. return;
  7279. }
  7280. this._cull = value;
  7281. this._isCullDirty = true;
  7282. },
  7283. enumerable: true,
  7284. configurable: true
  7285. });
  7286. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7287. get: function () {
  7288. return this._depthFunc;
  7289. },
  7290. set: function (value) {
  7291. if (this._depthFunc === value) {
  7292. return;
  7293. }
  7294. this._depthFunc = value;
  7295. this._isDepthFuncDirty = true;
  7296. },
  7297. enumerable: true,
  7298. configurable: true
  7299. });
  7300. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7301. get: function () {
  7302. return this._depthMask;
  7303. },
  7304. set: function (value) {
  7305. if (this._depthMask === value) {
  7306. return;
  7307. }
  7308. this._depthMask = value;
  7309. this._isDepthMaskDirty = true;
  7310. },
  7311. enumerable: true,
  7312. configurable: true
  7313. });
  7314. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7315. get: function () {
  7316. return this._depthTest;
  7317. },
  7318. set: function (value) {
  7319. if (this._depthTest === value) {
  7320. return;
  7321. }
  7322. this._depthTest = value;
  7323. this._isDepthTestDirty = true;
  7324. },
  7325. enumerable: true,
  7326. configurable: true
  7327. });
  7328. _DepthCullingState.prototype.reset = function () {
  7329. this._depthMask = true;
  7330. this._depthTest = true;
  7331. this._depthFunc = null;
  7332. this._cullFace = null;
  7333. this._cull = null;
  7334. this._zOffset = 0;
  7335. this._isDepthTestDirty = true;
  7336. this._isDepthMaskDirty = true;
  7337. this._isDepthFuncDirty = false;
  7338. this._isCullFaceDirty = false;
  7339. this._isCullDirty = false;
  7340. this._isZOffsetDirty = false;
  7341. };
  7342. _DepthCullingState.prototype.apply = function (gl) {
  7343. if (!this.isDirty) {
  7344. return;
  7345. }
  7346. // Cull
  7347. if (this._isCullDirty) {
  7348. if (this.cull) {
  7349. gl.enable(gl.CULL_FACE);
  7350. }
  7351. else {
  7352. gl.disable(gl.CULL_FACE);
  7353. }
  7354. this._isCullDirty = false;
  7355. }
  7356. // Cull face
  7357. if (this._isCullFaceDirty) {
  7358. gl.cullFace(this.cullFace);
  7359. this._isCullFaceDirty = false;
  7360. }
  7361. // Depth mask
  7362. if (this._isDepthMaskDirty) {
  7363. gl.depthMask(this.depthMask);
  7364. this._isDepthMaskDirty = false;
  7365. }
  7366. // Depth test
  7367. if (this._isDepthTestDirty) {
  7368. if (this.depthTest) {
  7369. gl.enable(gl.DEPTH_TEST);
  7370. }
  7371. else {
  7372. gl.disable(gl.DEPTH_TEST);
  7373. }
  7374. this._isDepthTestDirty = false;
  7375. }
  7376. // Depth func
  7377. if (this._isDepthFuncDirty) {
  7378. gl.depthFunc(this.depthFunc);
  7379. this._isDepthFuncDirty = false;
  7380. }
  7381. // zOffset
  7382. if (this._isZOffsetDirty) {
  7383. if (this.zOffset) {
  7384. gl.enable(gl.POLYGON_OFFSET_FILL);
  7385. gl.polygonOffset(this.zOffset, 0);
  7386. }
  7387. else {
  7388. gl.disable(gl.POLYGON_OFFSET_FILL);
  7389. }
  7390. this._isZOffsetDirty = false;
  7391. }
  7392. };
  7393. return _DepthCullingState;
  7394. }());
  7395. Internals._DepthCullingState = _DepthCullingState;
  7396. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7397. })(BABYLON || (BABYLON = {}));
  7398. //# sourceMappingURL=babylon.depthCullingState.js.map
  7399. var BABYLON;
  7400. (function (BABYLON) {
  7401. var Internals;
  7402. (function (Internals) {
  7403. var _StencilState = (function () {
  7404. function _StencilState() {
  7405. this._isStencilTestDirty = false;
  7406. this._isStencilMaskDirty = false;
  7407. this._isStencilFuncDirty = false;
  7408. this._isStencilOpDirty = false;
  7409. this.reset();
  7410. }
  7411. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7412. get: function () {
  7413. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7414. },
  7415. enumerable: true,
  7416. configurable: true
  7417. });
  7418. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7419. get: function () {
  7420. return this._stencilFunc;
  7421. },
  7422. set: function (value) {
  7423. if (this._stencilFunc === value) {
  7424. return;
  7425. }
  7426. this._stencilFunc = value;
  7427. this._isStencilFuncDirty = true;
  7428. },
  7429. enumerable: true,
  7430. configurable: true
  7431. });
  7432. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7433. get: function () {
  7434. return this._stencilFuncRef;
  7435. },
  7436. set: function (value) {
  7437. if (this._stencilFuncRef === value) {
  7438. return;
  7439. }
  7440. this._stencilFuncRef = value;
  7441. this._isStencilFuncDirty = true;
  7442. },
  7443. enumerable: true,
  7444. configurable: true
  7445. });
  7446. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7447. get: function () {
  7448. return this._stencilFuncMask;
  7449. },
  7450. set: function (value) {
  7451. if (this._stencilFuncMask === value) {
  7452. return;
  7453. }
  7454. this._stencilFuncMask = value;
  7455. this._isStencilFuncDirty = true;
  7456. },
  7457. enumerable: true,
  7458. configurable: true
  7459. });
  7460. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7461. get: function () {
  7462. return this._stencilOpStencilFail;
  7463. },
  7464. set: function (value) {
  7465. if (this._stencilOpStencilFail === value) {
  7466. return;
  7467. }
  7468. this._stencilOpStencilFail = value;
  7469. this._isStencilOpDirty = true;
  7470. },
  7471. enumerable: true,
  7472. configurable: true
  7473. });
  7474. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7475. get: function () {
  7476. return this._stencilOpDepthFail;
  7477. },
  7478. set: function (value) {
  7479. if (this._stencilOpDepthFail === value) {
  7480. return;
  7481. }
  7482. this._stencilOpDepthFail = value;
  7483. this._isStencilOpDirty = true;
  7484. },
  7485. enumerable: true,
  7486. configurable: true
  7487. });
  7488. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7489. get: function () {
  7490. return this._stencilOpStencilDepthPass;
  7491. },
  7492. set: function (value) {
  7493. if (this._stencilOpStencilDepthPass === value) {
  7494. return;
  7495. }
  7496. this._stencilOpStencilDepthPass = value;
  7497. this._isStencilOpDirty = true;
  7498. },
  7499. enumerable: true,
  7500. configurable: true
  7501. });
  7502. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7503. get: function () {
  7504. return this._stencilMask;
  7505. },
  7506. set: function (value) {
  7507. if (this._stencilMask === value) {
  7508. return;
  7509. }
  7510. this._stencilMask = value;
  7511. this._isStencilMaskDirty = true;
  7512. },
  7513. enumerable: true,
  7514. configurable: true
  7515. });
  7516. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7517. get: function () {
  7518. return this._stencilTest;
  7519. },
  7520. set: function (value) {
  7521. if (this._stencilTest === value) {
  7522. return;
  7523. }
  7524. this._stencilTest = value;
  7525. this._isStencilTestDirty = true;
  7526. },
  7527. enumerable: true,
  7528. configurable: true
  7529. });
  7530. _StencilState.prototype.reset = function () {
  7531. this._stencilTest = false;
  7532. this._stencilMask = 0xFF;
  7533. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7534. this._stencilFuncRef = 1;
  7535. this._stencilFuncMask = 0xFF;
  7536. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7537. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7538. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7539. this._isStencilTestDirty = true;
  7540. this._isStencilMaskDirty = true;
  7541. this._isStencilFuncDirty = true;
  7542. this._isStencilOpDirty = true;
  7543. };
  7544. _StencilState.prototype.apply = function (gl) {
  7545. if (!this.isDirty) {
  7546. return;
  7547. }
  7548. // Stencil test
  7549. if (this._isStencilTestDirty) {
  7550. if (this.stencilTest) {
  7551. gl.enable(gl.STENCIL_TEST);
  7552. }
  7553. else {
  7554. gl.disable(gl.STENCIL_TEST);
  7555. }
  7556. this._isStencilTestDirty = false;
  7557. }
  7558. // Stencil mask
  7559. if (this._isStencilMaskDirty) {
  7560. gl.stencilMask(this.stencilMask);
  7561. this._isStencilMaskDirty = false;
  7562. }
  7563. // Stencil func
  7564. if (this._isStencilFuncDirty) {
  7565. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7566. this._isStencilFuncDirty = false;
  7567. }
  7568. // Stencil op
  7569. if (this._isStencilOpDirty) {
  7570. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7571. this._isStencilOpDirty = false;
  7572. }
  7573. };
  7574. return _StencilState;
  7575. }());
  7576. Internals._StencilState = _StencilState;
  7577. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7578. })(BABYLON || (BABYLON = {}));
  7579. //# sourceMappingURL=babylon.stencilState.js.map
  7580. var BABYLON;
  7581. (function (BABYLON) {
  7582. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7583. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7584. };
  7585. var compileRawShader = function (gl, source, type) {
  7586. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7587. gl.shaderSource(shader, source);
  7588. gl.compileShader(shader);
  7589. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7590. throw new Error(gl.getShaderInfoLog(shader));
  7591. }
  7592. return shader;
  7593. };
  7594. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7595. var magFilter = gl.NEAREST;
  7596. var minFilter = gl.NEAREST;
  7597. switch (samplingMode) {
  7598. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7599. magFilter = gl.LINEAR;
  7600. if (generateMipMaps) {
  7601. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7602. }
  7603. else {
  7604. minFilter = gl.LINEAR;
  7605. }
  7606. break;
  7607. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7608. magFilter = gl.LINEAR;
  7609. if (generateMipMaps) {
  7610. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7611. }
  7612. else {
  7613. minFilter = gl.LINEAR;
  7614. }
  7615. break;
  7616. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7617. magFilter = gl.NEAREST;
  7618. if (generateMipMaps) {
  7619. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7620. }
  7621. else {
  7622. minFilter = gl.NEAREST;
  7623. }
  7624. break;
  7625. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7626. magFilter = gl.NEAREST;
  7627. if (generateMipMaps) {
  7628. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7629. }
  7630. else {
  7631. minFilter = gl.NEAREST;
  7632. }
  7633. break;
  7634. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7635. magFilter = gl.NEAREST;
  7636. if (generateMipMaps) {
  7637. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7638. }
  7639. else {
  7640. minFilter = gl.LINEAR;
  7641. }
  7642. break;
  7643. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7644. magFilter = gl.NEAREST;
  7645. if (generateMipMaps) {
  7646. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7647. }
  7648. else {
  7649. minFilter = gl.LINEAR;
  7650. }
  7651. break;
  7652. case BABYLON.Texture.NEAREST_LINEAR:
  7653. magFilter = gl.NEAREST;
  7654. minFilter = gl.LINEAR;
  7655. break;
  7656. case BABYLON.Texture.NEAREST_NEAREST:
  7657. magFilter = gl.NEAREST;
  7658. minFilter = gl.NEAREST;
  7659. break;
  7660. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7661. magFilter = gl.LINEAR;
  7662. if (generateMipMaps) {
  7663. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7664. }
  7665. else {
  7666. minFilter = gl.NEAREST;
  7667. }
  7668. break;
  7669. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7670. magFilter = gl.LINEAR;
  7671. if (generateMipMaps) {
  7672. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7673. }
  7674. else {
  7675. minFilter = gl.NEAREST;
  7676. }
  7677. break;
  7678. case BABYLON.Texture.LINEAR_LINEAR:
  7679. magFilter = gl.LINEAR;
  7680. minFilter = gl.LINEAR;
  7681. break;
  7682. case BABYLON.Texture.LINEAR_NEAREST:
  7683. magFilter = gl.LINEAR;
  7684. minFilter = gl.NEAREST;
  7685. break;
  7686. }
  7687. return {
  7688. min: minFilter,
  7689. mag: magFilter
  7690. };
  7691. };
  7692. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7693. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7694. var img;
  7695. var onload = function () {
  7696. loadedImages[index] = img;
  7697. loadedImages._internalCount++;
  7698. if (scene) {
  7699. scene._removePendingData(img);
  7700. }
  7701. if (loadedImages._internalCount === 6) {
  7702. onfinish(loadedImages);
  7703. }
  7704. };
  7705. var onerror = function (message, exception) {
  7706. if (scene) {
  7707. scene._removePendingData(img);
  7708. }
  7709. if (onErrorCallBack) {
  7710. onErrorCallBack(message, exception);
  7711. }
  7712. };
  7713. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7714. if (scene) {
  7715. scene._addPendingData(img);
  7716. }
  7717. };
  7718. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7719. if (onError === void 0) { onError = null; }
  7720. var loadedImages = [];
  7721. loadedImages._internalCount = 0;
  7722. for (var index = 0; index < 6; index++) {
  7723. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7724. }
  7725. };
  7726. var BufferPointer = (function () {
  7727. function BufferPointer() {
  7728. }
  7729. return BufferPointer;
  7730. }());
  7731. var InstancingAttributeInfo = (function () {
  7732. function InstancingAttributeInfo() {
  7733. }
  7734. return InstancingAttributeInfo;
  7735. }());
  7736. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7737. /**
  7738. * Define options used to create a render target texture
  7739. */
  7740. var RenderTargetCreationOptions = (function () {
  7741. function RenderTargetCreationOptions() {
  7742. }
  7743. return RenderTargetCreationOptions;
  7744. }());
  7745. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7746. /**
  7747. * Regroup several parameters relative to the browser in use
  7748. */
  7749. var EngineCapabilities = (function () {
  7750. function EngineCapabilities() {
  7751. }
  7752. return EngineCapabilities;
  7753. }());
  7754. BABYLON.EngineCapabilities = EngineCapabilities;
  7755. /**
  7756. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7757. */
  7758. var Engine = (function () {
  7759. /**
  7760. * @constructor
  7761. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7762. * @param {boolean} [antialias] - enable antialias
  7763. * @param options - further options to be sent to the getContext function
  7764. */
  7765. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7766. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7767. var _this = this;
  7768. // Public members
  7769. this.forcePOTTextures = false;
  7770. this.isFullscreen = false;
  7771. this.isPointerLock = false;
  7772. this.cullBackFaces = true;
  7773. this.renderEvenInBackground = true;
  7774. this.preventCacheWipeBetweenFrames = false;
  7775. // To enable/disable IDB support and avoid XHR on .manifest
  7776. this.enableOfflineSupport = false;
  7777. this.scenes = new Array();
  7778. this.postProcesses = new Array();
  7779. // Observables
  7780. /**
  7781. * Observable event triggered each time the rendering canvas is resized
  7782. */
  7783. this.onResizeObservable = new BABYLON.Observable();
  7784. /**
  7785. * Observable event triggered each time the canvas loses focus
  7786. */
  7787. this.onCanvasBlurObservable = new BABYLON.Observable();
  7788. /**
  7789. * Observable event triggered each time the canvas gains focus
  7790. */
  7791. this.onCanvasFocusObservable = new BABYLON.Observable();
  7792. /**
  7793. * Observable event triggered each time the canvas receives pointerout event
  7794. */
  7795. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7796. /**
  7797. * Observable event triggered before each texture is initialized
  7798. */
  7799. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  7800. //WebVR
  7801. this._vrDisplay = undefined;
  7802. this._vrSupported = false;
  7803. this._vrExclusivePointerMode = false;
  7804. // Uniform buffers list
  7805. this.disableUniformBuffers = false;
  7806. this._uniformBuffers = new Array();
  7807. this._windowIsBackground = false;
  7808. this._webGLVersion = 1.0;
  7809. this._badOS = false;
  7810. this._badDesktopOS = false;
  7811. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  7812. this.onVRRequestPresentComplete = new BABYLON.Observable();
  7813. this.onVRRequestPresentStart = new BABYLON.Observable();
  7814. this._colorWrite = true;
  7815. this._drawCalls = new BABYLON.PerfCounter();
  7816. this._renderingQueueLaunched = false;
  7817. this._activeRenderLoops = new Array();
  7818. // Deterministic lockstepMaxSteps
  7819. this._deterministicLockstep = false;
  7820. this._lockstepMaxSteps = 4;
  7821. // Lost context
  7822. this.onContextLostObservable = new BABYLON.Observable();
  7823. this.onContextRestoredObservable = new BABYLON.Observable();
  7824. this._contextWasLost = false;
  7825. this._doNotHandleContextLost = false;
  7826. // FPS
  7827. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7828. this._fps = 60;
  7829. this._deltaTime = 0;
  7830. /**
  7831. * Turn this value on if you want to pause FPS computation when in background
  7832. */
  7833. this.disablePerformanceMonitorInBackground = false;
  7834. // States
  7835. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7836. this._stencilState = new BABYLON.Internals._StencilState();
  7837. this._alphaState = new BABYLON.Internals._AlphaState();
  7838. this._alphaMode = Engine.ALPHA_DISABLE;
  7839. // Cache
  7840. this._internalTexturesCache = new Array();
  7841. this._activeTexturesCache = {};
  7842. this._compiledEffects = {};
  7843. this._vertexAttribArraysEnabled = [];
  7844. this._uintIndicesCurrentlySet = false;
  7845. this._currentBoundBuffer = new Array();
  7846. this._currentBufferPointers = new Array();
  7847. this._currentInstanceLocations = new Array();
  7848. this._currentInstanceBuffers = new Array();
  7849. this._vaoRecordInProgress = false;
  7850. this._mustWipeVertexAttributes = false;
  7851. // Hardware supported Compressed Textures
  7852. this._texturesSupported = new Array();
  7853. this._onVRFullScreenTriggered = function () {
  7854. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  7855. //get the old size before we change
  7856. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7857. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7858. //get the width and height, change the render size
  7859. var leftEye = _this._vrDisplay.getEyeParameters('left');
  7860. _this.setHardwareScalingLevel(1);
  7861. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7862. }
  7863. else {
  7864. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7865. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7866. }
  7867. };
  7868. var canvas;
  7869. Engine.Instances.push(this);
  7870. if (!canvasOrContext) {
  7871. return;
  7872. }
  7873. options = options || {};
  7874. if (canvasOrContext.getContext) {
  7875. canvas = canvasOrContext;
  7876. this._renderingCanvas = canvas;
  7877. if (antialias != null) {
  7878. options.antialias = antialias;
  7879. }
  7880. if (options.deterministicLockstep === undefined) {
  7881. options.deterministicLockstep = false;
  7882. }
  7883. if (options.lockstepMaxSteps === undefined) {
  7884. options.lockstepMaxSteps = 4;
  7885. }
  7886. if (options.preserveDrawingBuffer === undefined) {
  7887. options.preserveDrawingBuffer = false;
  7888. }
  7889. if (options.audioEngine === undefined) {
  7890. options.audioEngine = true;
  7891. }
  7892. if (options.stencil === undefined) {
  7893. options.stencil = true;
  7894. }
  7895. this._deterministicLockstep = options.deterministicLockstep;
  7896. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7897. this._doNotHandleContextLost = options.doNotHandleContextLost;
  7898. // GL
  7899. if (!options.disableWebGL2Support) {
  7900. try {
  7901. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7902. if (this._gl) {
  7903. this._webGLVersion = 2.0;
  7904. }
  7905. }
  7906. catch (e) {
  7907. // Do nothing
  7908. }
  7909. }
  7910. if (!this._gl) {
  7911. if (!canvas) {
  7912. throw new Error("The provided canvas is null or undefined.");
  7913. }
  7914. try {
  7915. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7916. }
  7917. catch (e) {
  7918. throw new Error("WebGL not supported");
  7919. }
  7920. }
  7921. if (!this._gl) {
  7922. throw new Error("WebGL not supported");
  7923. }
  7924. this._onCanvasFocus = function () {
  7925. _this.onCanvasFocusObservable.notifyObservers(_this);
  7926. };
  7927. this._onCanvasBlur = function () {
  7928. _this.onCanvasBlurObservable.notifyObservers(_this);
  7929. };
  7930. canvas.addEventListener("focus", this._onCanvasFocus);
  7931. canvas.addEventListener("blur", this._onCanvasBlur);
  7932. this._onBlur = function () {
  7933. if (_this.disablePerformanceMonitorInBackground) {
  7934. _this._performanceMonitor.disable();
  7935. }
  7936. _this._windowIsBackground = true;
  7937. };
  7938. this._onFocus = function () {
  7939. if (_this.disablePerformanceMonitorInBackground) {
  7940. _this._performanceMonitor.enable();
  7941. }
  7942. _this._windowIsBackground = false;
  7943. };
  7944. this._onCanvasPointerOut = function () {
  7945. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  7946. };
  7947. window.addEventListener("blur", this._onBlur);
  7948. window.addEventListener("focus", this._onFocus);
  7949. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  7950. // Context lost
  7951. if (!this._doNotHandleContextLost) {
  7952. this._onContextLost = function (evt) {
  7953. evt.preventDefault();
  7954. _this._contextWasLost = true;
  7955. BABYLON.Tools.Warn("WebGL context lost.");
  7956. _this.onContextLostObservable.notifyObservers(_this);
  7957. };
  7958. this._onContextRestored = function (evt) {
  7959. // Adding a timeout to avoid race condition at browser level
  7960. setTimeout(function () {
  7961. // Rebuild gl context
  7962. _this._initGLContext();
  7963. // Rebuild effects
  7964. _this._rebuildEffects();
  7965. // Rebuild textures
  7966. _this._rebuildInternalTextures();
  7967. // Rebuild buffers
  7968. _this._rebuildBuffers();
  7969. // Cache
  7970. _this.wipeCaches(true);
  7971. BABYLON.Tools.Warn("WebGL context successfully restored.");
  7972. _this.onContextRestoredObservable.notifyObservers(_this);
  7973. _this._contextWasLost = false;
  7974. }, 0);
  7975. };
  7976. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  7977. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  7978. }
  7979. }
  7980. else {
  7981. this._gl = canvasOrContext;
  7982. this._renderingCanvas = this._gl.canvas;
  7983. if (this._gl.renderbufferStorageMultisample) {
  7984. this._webGLVersion = 2.0;
  7985. }
  7986. options.stencil = this._gl.getContextAttributes().stencil;
  7987. }
  7988. // Viewport
  7989. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7990. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7991. this.resize();
  7992. this._isStencilEnable = options.stencil;
  7993. this._initGLContext();
  7994. if (canvas) {
  7995. // Fullscreen
  7996. this._onFullscreenChange = function () {
  7997. if (document.fullscreen !== undefined) {
  7998. _this.isFullscreen = document.fullscreen;
  7999. }
  8000. else if (document.mozFullScreen !== undefined) {
  8001. _this.isFullscreen = document.mozFullScreen;
  8002. }
  8003. else if (document.webkitIsFullScreen !== undefined) {
  8004. _this.isFullscreen = document.webkitIsFullScreen;
  8005. }
  8006. else if (document.msIsFullScreen !== undefined) {
  8007. _this.isFullscreen = document.msIsFullScreen;
  8008. }
  8009. // Pointer lock
  8010. if (_this.isFullscreen && _this._pointerLockRequested) {
  8011. canvas.requestPointerLock = canvas.requestPointerLock ||
  8012. canvas.msRequestPointerLock ||
  8013. canvas.mozRequestPointerLock ||
  8014. canvas.webkitRequestPointerLock;
  8015. if (canvas.requestPointerLock) {
  8016. canvas.requestPointerLock();
  8017. }
  8018. }
  8019. };
  8020. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8021. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8022. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8023. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8024. // Pointer lock
  8025. this._onPointerLockChange = function () {
  8026. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8027. document.webkitPointerLockElement === canvas ||
  8028. document.msPointerLockElement === canvas ||
  8029. document.pointerLockElement === canvas);
  8030. };
  8031. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8032. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8033. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8034. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8035. this._onVRDisplayPointerRestricted = function () {
  8036. canvas.requestPointerLock();
  8037. };
  8038. this._onVRDisplayPointerUnrestricted = function () {
  8039. document.exitPointerLock();
  8040. };
  8041. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8042. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8043. }
  8044. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8045. Engine.audioEngine = new BABYLON.AudioEngine();
  8046. }
  8047. // Prepare buffer pointers
  8048. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8049. this._currentBufferPointers[i] = new BufferPointer();
  8050. }
  8051. // Load WebVR Devices
  8052. if (options.autoEnableWebVR) {
  8053. this.initWebVR();
  8054. }
  8055. // Detect if we are running on a faulty buggy OS.
  8056. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8057. // Detect if we are running on a faulty buggy desktop OS.
  8058. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8059. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8060. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8061. }
  8062. Object.defineProperty(Engine, "LastCreatedEngine", {
  8063. get: function () {
  8064. if (Engine.Instances.length === 0) {
  8065. return null;
  8066. }
  8067. return Engine.Instances[Engine.Instances.length - 1];
  8068. },
  8069. enumerable: true,
  8070. configurable: true
  8071. });
  8072. Object.defineProperty(Engine, "LastCreatedScene", {
  8073. get: function () {
  8074. var lastCreatedEngine = Engine.LastCreatedEngine;
  8075. if (!lastCreatedEngine) {
  8076. return null;
  8077. }
  8078. if (lastCreatedEngine.scenes.length === 0) {
  8079. return null;
  8080. }
  8081. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8082. },
  8083. enumerable: true,
  8084. configurable: true
  8085. });
  8086. /**
  8087. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8088. */
  8089. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8090. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8091. var engine = Engine.Instances[engineIndex];
  8092. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8093. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8094. }
  8095. }
  8096. };
  8097. Object.defineProperty(Engine, "NEVER", {
  8098. get: function () {
  8099. return Engine._NEVER;
  8100. },
  8101. enumerable: true,
  8102. configurable: true
  8103. });
  8104. Object.defineProperty(Engine, "ALWAYS", {
  8105. get: function () {
  8106. return Engine._ALWAYS;
  8107. },
  8108. enumerable: true,
  8109. configurable: true
  8110. });
  8111. Object.defineProperty(Engine, "LESS", {
  8112. get: function () {
  8113. return Engine._LESS;
  8114. },
  8115. enumerable: true,
  8116. configurable: true
  8117. });
  8118. Object.defineProperty(Engine, "EQUAL", {
  8119. get: function () {
  8120. return Engine._EQUAL;
  8121. },
  8122. enumerable: true,
  8123. configurable: true
  8124. });
  8125. Object.defineProperty(Engine, "LEQUAL", {
  8126. get: function () {
  8127. return Engine._LEQUAL;
  8128. },
  8129. enumerable: true,
  8130. configurable: true
  8131. });
  8132. Object.defineProperty(Engine, "GREATER", {
  8133. get: function () {
  8134. return Engine._GREATER;
  8135. },
  8136. enumerable: true,
  8137. configurable: true
  8138. });
  8139. Object.defineProperty(Engine, "GEQUAL", {
  8140. get: function () {
  8141. return Engine._GEQUAL;
  8142. },
  8143. enumerable: true,
  8144. configurable: true
  8145. });
  8146. Object.defineProperty(Engine, "NOTEQUAL", {
  8147. get: function () {
  8148. return Engine._NOTEQUAL;
  8149. },
  8150. enumerable: true,
  8151. configurable: true
  8152. });
  8153. Object.defineProperty(Engine, "KEEP", {
  8154. get: function () {
  8155. return Engine._KEEP;
  8156. },
  8157. enumerable: true,
  8158. configurable: true
  8159. });
  8160. Object.defineProperty(Engine, "REPLACE", {
  8161. get: function () {
  8162. return Engine._REPLACE;
  8163. },
  8164. enumerable: true,
  8165. configurable: true
  8166. });
  8167. Object.defineProperty(Engine, "INCR", {
  8168. get: function () {
  8169. return Engine._INCR;
  8170. },
  8171. enumerable: true,
  8172. configurable: true
  8173. });
  8174. Object.defineProperty(Engine, "DECR", {
  8175. get: function () {
  8176. return Engine._DECR;
  8177. },
  8178. enumerable: true,
  8179. configurable: true
  8180. });
  8181. Object.defineProperty(Engine, "INVERT", {
  8182. get: function () {
  8183. return Engine._INVERT;
  8184. },
  8185. enumerable: true,
  8186. configurable: true
  8187. });
  8188. Object.defineProperty(Engine, "INCR_WRAP", {
  8189. get: function () {
  8190. return Engine._INCR_WRAP;
  8191. },
  8192. enumerable: true,
  8193. configurable: true
  8194. });
  8195. Object.defineProperty(Engine, "DECR_WRAP", {
  8196. get: function () {
  8197. return Engine._DECR_WRAP;
  8198. },
  8199. enumerable: true,
  8200. configurable: true
  8201. });
  8202. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8203. get: function () {
  8204. return Engine._ALPHA_DISABLE;
  8205. },
  8206. enumerable: true,
  8207. configurable: true
  8208. });
  8209. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8210. get: function () {
  8211. return Engine._ALPHA_ONEONE;
  8212. },
  8213. enumerable: true,
  8214. configurable: true
  8215. });
  8216. Object.defineProperty(Engine, "ALPHA_ADD", {
  8217. get: function () {
  8218. return Engine._ALPHA_ADD;
  8219. },
  8220. enumerable: true,
  8221. configurable: true
  8222. });
  8223. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8224. get: function () {
  8225. return Engine._ALPHA_COMBINE;
  8226. },
  8227. enumerable: true,
  8228. configurable: true
  8229. });
  8230. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8231. get: function () {
  8232. return Engine._ALPHA_SUBTRACT;
  8233. },
  8234. enumerable: true,
  8235. configurable: true
  8236. });
  8237. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8238. get: function () {
  8239. return Engine._ALPHA_MULTIPLY;
  8240. },
  8241. enumerable: true,
  8242. configurable: true
  8243. });
  8244. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8245. get: function () {
  8246. return Engine._ALPHA_MAXIMIZED;
  8247. },
  8248. enumerable: true,
  8249. configurable: true
  8250. });
  8251. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8252. get: function () {
  8253. return Engine._ALPHA_PREMULTIPLIED;
  8254. },
  8255. enumerable: true,
  8256. configurable: true
  8257. });
  8258. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8259. get: function () {
  8260. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8261. },
  8262. enumerable: true,
  8263. configurable: true
  8264. });
  8265. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8266. get: function () {
  8267. return Engine._ALPHA_INTERPOLATE;
  8268. },
  8269. enumerable: true,
  8270. configurable: true
  8271. });
  8272. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8273. get: function () {
  8274. return Engine._ALPHA_SCREENMODE;
  8275. },
  8276. enumerable: true,
  8277. configurable: true
  8278. });
  8279. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8280. get: function () {
  8281. return Engine._DELAYLOADSTATE_NONE;
  8282. },
  8283. enumerable: true,
  8284. configurable: true
  8285. });
  8286. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8287. get: function () {
  8288. return Engine._DELAYLOADSTATE_LOADED;
  8289. },
  8290. enumerable: true,
  8291. configurable: true
  8292. });
  8293. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8294. get: function () {
  8295. return Engine._DELAYLOADSTATE_LOADING;
  8296. },
  8297. enumerable: true,
  8298. configurable: true
  8299. });
  8300. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8301. get: function () {
  8302. return Engine._DELAYLOADSTATE_NOTLOADED;
  8303. },
  8304. enumerable: true,
  8305. configurable: true
  8306. });
  8307. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8308. get: function () {
  8309. return Engine._TEXTUREFORMAT_ALPHA;
  8310. },
  8311. enumerable: true,
  8312. configurable: true
  8313. });
  8314. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8315. get: function () {
  8316. return Engine._TEXTUREFORMAT_LUMINANCE;
  8317. },
  8318. enumerable: true,
  8319. configurable: true
  8320. });
  8321. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8322. get: function () {
  8323. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8324. },
  8325. enumerable: true,
  8326. configurable: true
  8327. });
  8328. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8329. get: function () {
  8330. return Engine._TEXTUREFORMAT_RGB;
  8331. },
  8332. enumerable: true,
  8333. configurable: true
  8334. });
  8335. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8336. get: function () {
  8337. return Engine._TEXTUREFORMAT_RGBA;
  8338. },
  8339. enumerable: true,
  8340. configurable: true
  8341. });
  8342. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8343. get: function () {
  8344. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8345. },
  8346. enumerable: true,
  8347. configurable: true
  8348. });
  8349. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8350. get: function () {
  8351. return Engine._TEXTURETYPE_FLOAT;
  8352. },
  8353. enumerable: true,
  8354. configurable: true
  8355. });
  8356. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8357. get: function () {
  8358. return Engine._TEXTURETYPE_HALF_FLOAT;
  8359. },
  8360. enumerable: true,
  8361. configurable: true
  8362. });
  8363. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8364. get: function () {
  8365. return Engine._SCALEMODE_FLOOR;
  8366. },
  8367. enumerable: true,
  8368. configurable: true
  8369. });
  8370. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8371. get: function () {
  8372. return Engine._SCALEMODE_NEAREST;
  8373. },
  8374. enumerable: true,
  8375. configurable: true
  8376. });
  8377. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8378. get: function () {
  8379. return Engine._SCALEMODE_CEILING;
  8380. },
  8381. enumerable: true,
  8382. configurable: true
  8383. });
  8384. Object.defineProperty(Engine, "Version", {
  8385. get: function () {
  8386. return "3.1-alpha";
  8387. },
  8388. enumerable: true,
  8389. configurable: true
  8390. });
  8391. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8392. get: function () {
  8393. return this._vrExclusivePointerMode;
  8394. },
  8395. enumerable: true,
  8396. configurable: true
  8397. });
  8398. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8399. get: function () {
  8400. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8401. },
  8402. enumerable: true,
  8403. configurable: true
  8404. });
  8405. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8406. get: function () {
  8407. return this._webGLVersion < 2 || this.forcePOTTextures;
  8408. },
  8409. enumerable: true,
  8410. configurable: true
  8411. });
  8412. Object.defineProperty(Engine.prototype, "badOS", {
  8413. get: function () {
  8414. return this._badOS;
  8415. },
  8416. enumerable: true,
  8417. configurable: true
  8418. });
  8419. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8420. get: function () {
  8421. return this._badDesktopOS;
  8422. },
  8423. enumerable: true,
  8424. configurable: true
  8425. });
  8426. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8427. get: function () {
  8428. return this._performanceMonitor;
  8429. },
  8430. enumerable: true,
  8431. configurable: true
  8432. });
  8433. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8434. get: function () {
  8435. return this._texturesSupported;
  8436. },
  8437. enumerable: true,
  8438. configurable: true
  8439. });
  8440. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8441. get: function () {
  8442. return this._textureFormatInUse;
  8443. },
  8444. enumerable: true,
  8445. configurable: true
  8446. });
  8447. Object.defineProperty(Engine.prototype, "currentViewport", {
  8448. get: function () {
  8449. return this._cachedViewport;
  8450. },
  8451. enumerable: true,
  8452. configurable: true
  8453. });
  8454. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8455. // Empty texture
  8456. get: function () {
  8457. if (!this._emptyTexture) {
  8458. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8459. }
  8460. return this._emptyTexture;
  8461. },
  8462. enumerable: true,
  8463. configurable: true
  8464. });
  8465. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8466. get: function () {
  8467. if (!this._emptyCubeTexture) {
  8468. var faceData = new Uint8Array(4);
  8469. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8470. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8471. }
  8472. return this._emptyCubeTexture;
  8473. },
  8474. enumerable: true,
  8475. configurable: true
  8476. });
  8477. Engine.prototype._rebuildInternalTextures = function () {
  8478. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8479. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8480. var internalTexture = currentState_1[_i];
  8481. internalTexture._rebuild();
  8482. }
  8483. };
  8484. Engine.prototype._rebuildEffects = function () {
  8485. for (var key in this._compiledEffects) {
  8486. var effect = this._compiledEffects[key];
  8487. effect._prepareEffect();
  8488. }
  8489. BABYLON.Effect.ResetCache();
  8490. };
  8491. Engine.prototype._rebuildBuffers = function () {
  8492. // Index / Vertex
  8493. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8494. var scene = _a[_i];
  8495. scene.resetCachedMaterial();
  8496. scene._rebuildGeometries();
  8497. scene._rebuildTextures();
  8498. }
  8499. // Uniforms
  8500. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8501. var uniformBuffer = _c[_b];
  8502. uniformBuffer._rebuild();
  8503. }
  8504. };
  8505. Engine.prototype._initGLContext = function () {
  8506. // Caps
  8507. this._caps = new EngineCapabilities();
  8508. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8509. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8510. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8511. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8512. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8513. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8514. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8515. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8516. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8517. // Infos
  8518. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8519. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8520. if (rendererInfo != null) {
  8521. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8522. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8523. }
  8524. if (!this._glVendor) {
  8525. this._glVendor = "Unknown vendor";
  8526. }
  8527. if (!this._glRenderer) {
  8528. this._glRenderer = "Unknown renderer";
  8529. }
  8530. // Constants
  8531. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8532. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8533. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8534. this._gl.DEPTH24_STENCIL8 = 35056;
  8535. // Extensions
  8536. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8537. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8538. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8539. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8540. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8541. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8542. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8543. 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');
  8544. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8545. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8546. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8547. this._caps.highPrecisionShaderSupported = true;
  8548. // Checks if some of the format renders first to allow the use of webgl inspector.
  8549. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8550. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8551. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8552. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8553. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8554. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8555. if (this._webGLVersion > 1) {
  8556. this._gl.HALF_FLOAT_OES = 0x140B;
  8557. }
  8558. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8559. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8560. // Draw buffers
  8561. if (this._webGLVersion > 1) {
  8562. this._caps.drawBuffersExtension = true;
  8563. }
  8564. else {
  8565. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8566. if (drawBuffersExtension !== null) {
  8567. this._caps.drawBuffersExtension = true;
  8568. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8569. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8570. for (var i = 0; i < 16; i++) {
  8571. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8572. }
  8573. }
  8574. else {
  8575. this._caps.drawBuffersExtension = false;
  8576. }
  8577. }
  8578. // Depth Texture
  8579. if (this._webGLVersion > 1) {
  8580. this._caps.depthTextureExtension = true;
  8581. }
  8582. else {
  8583. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8584. if (depthTextureExtension != null) {
  8585. this._caps.depthTextureExtension = true;
  8586. }
  8587. }
  8588. // Vertex array object
  8589. if (this._webGLVersion > 1) {
  8590. this._caps.vertexArrayObject = true;
  8591. }
  8592. else {
  8593. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8594. if (vertexArrayObjectExtension != null) {
  8595. this._caps.vertexArrayObject = true;
  8596. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8597. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8598. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8599. }
  8600. else {
  8601. this._caps.vertexArrayObject = false;
  8602. }
  8603. }
  8604. // Instances count
  8605. if (this._webGLVersion > 1) {
  8606. this._caps.instancedArrays = true;
  8607. }
  8608. else {
  8609. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8610. if (instanceExtension != null) {
  8611. this._caps.instancedArrays = true;
  8612. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8613. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8614. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8615. }
  8616. else {
  8617. this._caps.instancedArrays = false;
  8618. }
  8619. }
  8620. // Intelligently add supported compressed formats in order to check for.
  8621. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8622. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8623. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8624. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8625. if (this._caps.astc)
  8626. this.texturesSupported.push('-astc.ktx');
  8627. if (this._caps.s3tc)
  8628. this.texturesSupported.push('-dxt.ktx');
  8629. if (this._caps.pvrtc)
  8630. this.texturesSupported.push('-pvrtc.ktx');
  8631. if (this._caps.etc2)
  8632. this.texturesSupported.push('-etc2.ktx');
  8633. if (this._caps.etc1)
  8634. this.texturesSupported.push('-etc1.ktx');
  8635. if (this._gl.getShaderPrecisionFormat) {
  8636. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8637. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8638. }
  8639. // Depth buffer
  8640. this.setDepthBuffer(true);
  8641. this.setDepthFunctionToLessOrEqual();
  8642. this.setDepthWrite(true);
  8643. };
  8644. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8645. get: function () {
  8646. return this._webGLVersion;
  8647. },
  8648. enumerable: true,
  8649. configurable: true
  8650. });
  8651. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8652. /**
  8653. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8654. */
  8655. get: function () {
  8656. return this._isStencilEnable;
  8657. },
  8658. enumerable: true,
  8659. configurable: true
  8660. });
  8661. Engine.prototype._prepareWorkingCanvas = function () {
  8662. if (this._workingCanvas) {
  8663. return;
  8664. }
  8665. this._workingCanvas = document.createElement("canvas");
  8666. this._workingContext = this._workingCanvas.getContext("2d");
  8667. };
  8668. Engine.prototype.resetTextureCache = function () {
  8669. for (var key in this._activeTexturesCache) {
  8670. this._activeTexturesCache[key] = null;
  8671. }
  8672. };
  8673. Engine.prototype.isDeterministicLockStep = function () {
  8674. return this._deterministicLockstep;
  8675. };
  8676. Engine.prototype.getLockstepMaxSteps = function () {
  8677. return this._lockstepMaxSteps;
  8678. };
  8679. Engine.prototype.getGlInfo = function () {
  8680. return {
  8681. vendor: this._glVendor,
  8682. renderer: this._glRenderer,
  8683. version: this._glVersion
  8684. };
  8685. };
  8686. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8687. if (useScreen === void 0) { useScreen = false; }
  8688. var viewport = camera.viewport;
  8689. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8690. };
  8691. Engine.prototype.getRenderWidth = function (useScreen) {
  8692. if (useScreen === void 0) { useScreen = false; }
  8693. if (!useScreen && this._currentRenderTarget) {
  8694. return this._currentRenderTarget.width;
  8695. }
  8696. return this._gl.drawingBufferWidth;
  8697. };
  8698. Engine.prototype.getRenderHeight = function (useScreen) {
  8699. if (useScreen === void 0) { useScreen = false; }
  8700. if (!useScreen && this._currentRenderTarget) {
  8701. return this._currentRenderTarget.height;
  8702. }
  8703. return this._gl.drawingBufferHeight;
  8704. };
  8705. Engine.prototype.getRenderingCanvas = function () {
  8706. return this._renderingCanvas;
  8707. };
  8708. Engine.prototype.getRenderingCanvasClientRect = function () {
  8709. return this._renderingCanvas.getBoundingClientRect();
  8710. };
  8711. Engine.prototype.setHardwareScalingLevel = function (level) {
  8712. this._hardwareScalingLevel = level;
  8713. this.resize();
  8714. };
  8715. Engine.prototype.getHardwareScalingLevel = function () {
  8716. return this._hardwareScalingLevel;
  8717. };
  8718. Engine.prototype.getLoadedTexturesCache = function () {
  8719. return this._internalTexturesCache;
  8720. };
  8721. Engine.prototype.getCaps = function () {
  8722. return this._caps;
  8723. };
  8724. Object.defineProperty(Engine.prototype, "drawCalls", {
  8725. /** The number of draw calls submitted last frame */
  8726. get: function () {
  8727. return this._drawCalls.current;
  8728. },
  8729. enumerable: true,
  8730. configurable: true
  8731. });
  8732. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8733. get: function () {
  8734. return this._drawCalls;
  8735. },
  8736. enumerable: true,
  8737. configurable: true
  8738. });
  8739. Engine.prototype.getDepthFunction = function () {
  8740. return this._depthCullingState.depthFunc;
  8741. };
  8742. Engine.prototype.setDepthFunction = function (depthFunc) {
  8743. this._depthCullingState.depthFunc = depthFunc;
  8744. };
  8745. Engine.prototype.setDepthFunctionToGreater = function () {
  8746. this._depthCullingState.depthFunc = this._gl.GREATER;
  8747. };
  8748. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8749. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8750. };
  8751. Engine.prototype.setDepthFunctionToLess = function () {
  8752. this._depthCullingState.depthFunc = this._gl.LESS;
  8753. };
  8754. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8755. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8756. };
  8757. Engine.prototype.getStencilBuffer = function () {
  8758. return this._stencilState.stencilTest;
  8759. };
  8760. Engine.prototype.setStencilBuffer = function (enable) {
  8761. this._stencilState.stencilTest = enable;
  8762. };
  8763. Engine.prototype.getStencilMask = function () {
  8764. return this._stencilState.stencilMask;
  8765. };
  8766. Engine.prototype.setStencilMask = function (mask) {
  8767. this._stencilState.stencilMask = mask;
  8768. };
  8769. Engine.prototype.getStencilFunction = function () {
  8770. return this._stencilState.stencilFunc;
  8771. };
  8772. Engine.prototype.getStencilFunctionReference = function () {
  8773. return this._stencilState.stencilFuncRef;
  8774. };
  8775. Engine.prototype.getStencilFunctionMask = function () {
  8776. return this._stencilState.stencilFuncMask;
  8777. };
  8778. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8779. this._stencilState.stencilFunc = stencilFunc;
  8780. };
  8781. Engine.prototype.setStencilFunctionReference = function (reference) {
  8782. this._stencilState.stencilFuncRef = reference;
  8783. };
  8784. Engine.prototype.setStencilFunctionMask = function (mask) {
  8785. this._stencilState.stencilFuncMask = mask;
  8786. };
  8787. Engine.prototype.getStencilOperationFail = function () {
  8788. return this._stencilState.stencilOpStencilFail;
  8789. };
  8790. Engine.prototype.getStencilOperationDepthFail = function () {
  8791. return this._stencilState.stencilOpDepthFail;
  8792. };
  8793. Engine.prototype.getStencilOperationPass = function () {
  8794. return this._stencilState.stencilOpStencilDepthPass;
  8795. };
  8796. Engine.prototype.setStencilOperationFail = function (operation) {
  8797. this._stencilState.stencilOpStencilFail = operation;
  8798. };
  8799. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8800. this._stencilState.stencilOpDepthFail = operation;
  8801. };
  8802. Engine.prototype.setStencilOperationPass = function (operation) {
  8803. this._stencilState.stencilOpStencilDepthPass = operation;
  8804. };
  8805. Engine.prototype.setDitheringState = function (value) {
  8806. if (value) {
  8807. this._gl.enable(this._gl.DITHER);
  8808. }
  8809. else {
  8810. this._gl.disable(this._gl.DITHER);
  8811. }
  8812. };
  8813. /**
  8814. * stop executing a render loop function and remove it from the execution array
  8815. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8816. */
  8817. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8818. if (!renderFunction) {
  8819. this._activeRenderLoops = [];
  8820. return;
  8821. }
  8822. var index = this._activeRenderLoops.indexOf(renderFunction);
  8823. if (index >= 0) {
  8824. this._activeRenderLoops.splice(index, 1);
  8825. }
  8826. };
  8827. Engine.prototype._renderLoop = function () {
  8828. if (!this._contextWasLost) {
  8829. var shouldRender = true;
  8830. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8831. shouldRender = false;
  8832. }
  8833. if (shouldRender) {
  8834. // Start new frame
  8835. this.beginFrame();
  8836. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8837. var renderFunction = this._activeRenderLoops[index];
  8838. renderFunction();
  8839. }
  8840. // Present
  8841. this.endFrame();
  8842. }
  8843. }
  8844. if (this._activeRenderLoops.length > 0) {
  8845. // Register new frame
  8846. var requester = null;
  8847. if (this._vrDisplay && this._vrDisplay.isPresenting)
  8848. requester = this._vrDisplay;
  8849. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  8850. }
  8851. else {
  8852. this._renderingQueueLaunched = false;
  8853. }
  8854. };
  8855. /**
  8856. * Register and execute a render loop. The engine can have more than one render function.
  8857. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8858. * @example
  8859. * engine.runRenderLoop(function () {
  8860. * scene.render()
  8861. * })
  8862. */
  8863. Engine.prototype.runRenderLoop = function (renderFunction) {
  8864. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8865. return;
  8866. }
  8867. this._activeRenderLoops.push(renderFunction);
  8868. if (!this._renderingQueueLaunched) {
  8869. this._renderingQueueLaunched = true;
  8870. this._bindedRenderFunction = this._renderLoop.bind(this);
  8871. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8872. }
  8873. };
  8874. /**
  8875. * Toggle full screen mode.
  8876. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8877. * @param {any} options - an options object to be sent to the requestFullscreen function
  8878. */
  8879. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8880. if (this.isFullscreen) {
  8881. BABYLON.Tools.ExitFullscreen();
  8882. }
  8883. else {
  8884. this._pointerLockRequested = requestPointerLock;
  8885. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8886. }
  8887. };
  8888. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8889. if (stencil === void 0) { stencil = false; }
  8890. this.applyStates();
  8891. var mode = 0;
  8892. if (backBuffer && color) {
  8893. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8894. mode |= this._gl.COLOR_BUFFER_BIT;
  8895. }
  8896. if (depth) {
  8897. this._gl.clearDepth(1.0);
  8898. mode |= this._gl.DEPTH_BUFFER_BIT;
  8899. }
  8900. if (stencil) {
  8901. this._gl.clearStencil(0);
  8902. mode |= this._gl.STENCIL_BUFFER_BIT;
  8903. }
  8904. this._gl.clear(mode);
  8905. };
  8906. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8907. var gl = this._gl;
  8908. // Save state
  8909. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8910. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8911. // Change state
  8912. gl.enable(gl.SCISSOR_TEST);
  8913. gl.scissor(x, y, width, height);
  8914. // Clear
  8915. this.clear(clearColor, true, true, true);
  8916. // Restore state
  8917. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8918. if (curScissor === true) {
  8919. gl.enable(gl.SCISSOR_TEST);
  8920. }
  8921. else {
  8922. gl.disable(gl.SCISSOR_TEST);
  8923. }
  8924. };
  8925. /**
  8926. * Set the WebGL's viewport
  8927. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8928. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8929. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8930. */
  8931. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8932. var width = requiredWidth || this.getRenderWidth();
  8933. var height = requiredHeight || this.getRenderHeight();
  8934. var x = viewport.x || 0;
  8935. var y = viewport.y || 0;
  8936. this._cachedViewport = viewport;
  8937. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8938. };
  8939. /**
  8940. * Directly set the WebGL Viewport
  8941. * The x, y, width & height are directly passed to the WebGL call
  8942. * @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.
  8943. */
  8944. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8945. var currentViewport = this._cachedViewport;
  8946. this._cachedViewport = null;
  8947. this._gl.viewport(x, y, width, height);
  8948. return currentViewport;
  8949. };
  8950. Engine.prototype.beginFrame = function () {
  8951. this._measureFps();
  8952. };
  8953. Engine.prototype.endFrame = function () {
  8954. //force a flush in case we are using a bad OS.
  8955. if (this._badOS) {
  8956. this.flushFramebuffer();
  8957. }
  8958. //submit frame to the vr device, if enabled
  8959. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  8960. // TODO: We should only submit the frame if we read frameData successfully.
  8961. this._vrDisplay.submitFrame();
  8962. }
  8963. };
  8964. /**
  8965. * resize the view according to the canvas' size.
  8966. * @example
  8967. * window.addEventListener("resize", function () {
  8968. * engine.resize();
  8969. * });
  8970. */
  8971. Engine.prototype.resize = function () {
  8972. // We're not resizing the size of the canvas while in VR mode & presenting
  8973. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  8974. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8975. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8976. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8977. }
  8978. };
  8979. /**
  8980. * force a specific size of the canvas
  8981. * @param {number} width - the new canvas' width
  8982. * @param {number} height - the new canvas' height
  8983. */
  8984. Engine.prototype.setSize = function (width, height) {
  8985. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8986. return;
  8987. }
  8988. this._renderingCanvas.width = width;
  8989. this._renderingCanvas.height = height;
  8990. for (var index = 0; index < this.scenes.length; index++) {
  8991. var scene = this.scenes[index];
  8992. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8993. var cam = scene.cameras[camIndex];
  8994. cam._currentRenderId = 0;
  8995. }
  8996. }
  8997. if (this.onResizeObservable.hasObservers) {
  8998. this.onResizeObservable.notifyObservers(this);
  8999. }
  9000. };
  9001. // WebVR functions
  9002. Engine.prototype.isVRDevicePresent = function () {
  9003. return !!this._vrDisplay;
  9004. };
  9005. Engine.prototype.getVRDevice = function () {
  9006. return this._vrDisplay;
  9007. };
  9008. Engine.prototype.initWebVR = function () {
  9009. var _this = this;
  9010. var notifyObservers = function () {
  9011. var eventArgs = {
  9012. vrDisplay: _this._vrDisplay,
  9013. vrSupported: _this._vrSupported
  9014. };
  9015. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9016. };
  9017. if (!this._onVrDisplayConnect) {
  9018. this._onVrDisplayConnect = function (event) {
  9019. _this._vrDisplay = event.display;
  9020. notifyObservers();
  9021. };
  9022. this._onVrDisplayDisconnect = function () {
  9023. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9024. _this._vrDisplay = undefined;
  9025. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9026. notifyObservers();
  9027. };
  9028. this._onVrDisplayPresentChange = function () {
  9029. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9030. };
  9031. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9032. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9033. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9034. }
  9035. this._getVRDisplays(notifyObservers);
  9036. return this.onVRDisplayChangedObservable;
  9037. };
  9038. Engine.prototype.enableVR = function () {
  9039. var _this = this;
  9040. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9041. var onResolved = function () {
  9042. _this.onVRRequestPresentComplete.notifyObservers(true);
  9043. _this._onVRFullScreenTriggered();
  9044. };
  9045. var onRejected = function () {
  9046. _this.onVRRequestPresentComplete.notifyObservers(false);
  9047. };
  9048. this.onVRRequestPresentStart.notifyObservers(this);
  9049. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9050. }
  9051. };
  9052. Engine.prototype.disableVR = function () {
  9053. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9054. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9055. }
  9056. };
  9057. Engine.prototype._getVRDisplays = function (callback) {
  9058. var _this = this;
  9059. var getWebVRDevices = function (devices) {
  9060. _this._vrSupported = true;
  9061. // note that devices may actually be an empty array. This is fine;
  9062. // we expect this._vrDisplay to be undefined in this case.
  9063. return _this._vrDisplay = devices[0];
  9064. };
  9065. if (navigator.getVRDisplays) {
  9066. // TODO: Backwards compatible for 1.0?
  9067. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9068. // TODO: System CANNOT support WebVR, despite API presence.
  9069. _this._vrSupported = false;
  9070. callback();
  9071. });
  9072. }
  9073. else {
  9074. // TODO: Browser does not support WebVR
  9075. this._vrDisplay = undefined;
  9076. this._vrSupported = false;
  9077. callback();
  9078. }
  9079. };
  9080. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9081. if (this._currentRenderTarget) {
  9082. this.unBindFramebuffer(this._currentRenderTarget);
  9083. }
  9084. this._currentRenderTarget = texture;
  9085. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9086. var gl = this._gl;
  9087. if (texture.isCube) {
  9088. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9089. }
  9090. if (this._cachedViewport && !forceFullscreenViewport) {
  9091. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9092. }
  9093. else {
  9094. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9095. }
  9096. this.wipeCaches();
  9097. };
  9098. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9099. if (this._currentFramebuffer !== framebuffer) {
  9100. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9101. this._currentFramebuffer = framebuffer;
  9102. }
  9103. };
  9104. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9105. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9106. this._currentRenderTarget = null;
  9107. // If MSAA, we need to bitblt back to main texture
  9108. var gl = this._gl;
  9109. if (texture._MSAAFramebuffer) {
  9110. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9111. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9112. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9113. }
  9114. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9115. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9116. gl.generateMipmap(gl.TEXTURE_2D);
  9117. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9118. }
  9119. if (onBeforeUnbind) {
  9120. if (texture._MSAAFramebuffer) {
  9121. // Bind the correct framebuffer
  9122. this.bindUnboundFramebuffer(texture._framebuffer);
  9123. }
  9124. onBeforeUnbind();
  9125. }
  9126. this.bindUnboundFramebuffer(null);
  9127. };
  9128. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9129. if (texture.generateMipMaps) {
  9130. var gl = this._gl;
  9131. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9132. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9133. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9134. }
  9135. };
  9136. Engine.prototype.flushFramebuffer = function () {
  9137. this._gl.flush();
  9138. };
  9139. Engine.prototype.restoreDefaultFramebuffer = function () {
  9140. if (this._currentRenderTarget) {
  9141. this.unBindFramebuffer(this._currentRenderTarget);
  9142. }
  9143. else {
  9144. this.bindUnboundFramebuffer(null);
  9145. }
  9146. if (this._cachedViewport) {
  9147. this.setViewport(this._cachedViewport);
  9148. }
  9149. this.wipeCaches();
  9150. };
  9151. // UBOs
  9152. Engine.prototype.createUniformBuffer = function (elements) {
  9153. var ubo = this._gl.createBuffer();
  9154. this.bindUniformBuffer(ubo);
  9155. if (elements instanceof Float32Array) {
  9156. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9157. }
  9158. else {
  9159. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9160. }
  9161. this.bindUniformBuffer(null);
  9162. ubo.references = 1;
  9163. return ubo;
  9164. };
  9165. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9166. var ubo = this._gl.createBuffer();
  9167. this.bindUniformBuffer(ubo);
  9168. if (elements instanceof Float32Array) {
  9169. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9170. }
  9171. else {
  9172. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9173. }
  9174. this.bindUniformBuffer(null);
  9175. ubo.references = 1;
  9176. return ubo;
  9177. };
  9178. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9179. this.bindUniformBuffer(uniformBuffer);
  9180. if (offset === undefined) {
  9181. offset = 0;
  9182. }
  9183. if (count === undefined) {
  9184. if (elements instanceof Float32Array) {
  9185. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9186. }
  9187. else {
  9188. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9189. }
  9190. }
  9191. else {
  9192. if (elements instanceof Float32Array) {
  9193. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9194. }
  9195. else {
  9196. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9197. }
  9198. }
  9199. this.bindUniformBuffer(null);
  9200. };
  9201. // VBOs
  9202. Engine.prototype._resetVertexBufferBinding = function () {
  9203. this.bindArrayBuffer(null);
  9204. this._cachedVertexBuffers = null;
  9205. };
  9206. Engine.prototype.createVertexBuffer = function (vertices) {
  9207. var vbo = this._gl.createBuffer();
  9208. this.bindArrayBuffer(vbo);
  9209. if (vertices instanceof Float32Array) {
  9210. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9211. }
  9212. else {
  9213. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9214. }
  9215. this._resetVertexBufferBinding();
  9216. vbo.references = 1;
  9217. return vbo;
  9218. };
  9219. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9220. var vbo = this._gl.createBuffer();
  9221. this.bindArrayBuffer(vbo);
  9222. if (vertices instanceof Float32Array) {
  9223. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9224. }
  9225. else {
  9226. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9227. }
  9228. this._resetVertexBufferBinding();
  9229. vbo.references = 1;
  9230. return vbo;
  9231. };
  9232. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9233. if (offset === void 0) { offset = 0; }
  9234. this.bindIndexBuffer(indexBuffer);
  9235. var arrayBuffer;
  9236. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9237. arrayBuffer = indices;
  9238. }
  9239. else {
  9240. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9241. }
  9242. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9243. this._resetIndexBufferBinding();
  9244. };
  9245. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9246. this.bindArrayBuffer(vertexBuffer);
  9247. if (offset === undefined) {
  9248. offset = 0;
  9249. }
  9250. if (count === undefined) {
  9251. if (vertices instanceof Float32Array) {
  9252. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9253. }
  9254. else {
  9255. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9256. }
  9257. }
  9258. else {
  9259. if (vertices instanceof Float32Array) {
  9260. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9261. }
  9262. else {
  9263. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9264. }
  9265. }
  9266. this._resetVertexBufferBinding();
  9267. };
  9268. Engine.prototype._resetIndexBufferBinding = function () {
  9269. this.bindIndexBuffer(null);
  9270. this._cachedIndexBuffer = null;
  9271. };
  9272. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9273. var vbo = this._gl.createBuffer();
  9274. this.bindIndexBuffer(vbo);
  9275. // Check for 32 bits indices
  9276. var arrayBuffer;
  9277. var need32Bits = false;
  9278. if (indices instanceof Uint16Array) {
  9279. arrayBuffer = indices;
  9280. }
  9281. else {
  9282. //check 32 bit support
  9283. if (this._caps.uintIndices) {
  9284. if (indices instanceof Uint32Array) {
  9285. arrayBuffer = indices;
  9286. need32Bits = true;
  9287. }
  9288. else {
  9289. //number[] or Int32Array, check if 32 bit is necessary
  9290. for (var index = 0; index < indices.length; index++) {
  9291. if (indices[index] > 65535) {
  9292. need32Bits = true;
  9293. break;
  9294. }
  9295. }
  9296. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9297. }
  9298. }
  9299. else {
  9300. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9301. arrayBuffer = new Uint16Array(indices);
  9302. }
  9303. }
  9304. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9305. this._resetIndexBufferBinding();
  9306. vbo.references = 1;
  9307. vbo.is32Bits = need32Bits;
  9308. return vbo;
  9309. };
  9310. Engine.prototype.bindArrayBuffer = function (buffer) {
  9311. if (!this._vaoRecordInProgress) {
  9312. this._unbindVertexArrayObject();
  9313. }
  9314. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9315. };
  9316. Engine.prototype.bindUniformBuffer = function (buffer) {
  9317. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9318. };
  9319. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9320. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9321. };
  9322. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9323. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9324. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9325. };
  9326. ;
  9327. Engine.prototype.bindIndexBuffer = function (buffer) {
  9328. if (!this._vaoRecordInProgress) {
  9329. this._unbindVertexArrayObject();
  9330. }
  9331. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9332. };
  9333. Engine.prototype.bindBuffer = function (buffer, target) {
  9334. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9335. this._gl.bindBuffer(target, buffer);
  9336. this._currentBoundBuffer[target] = buffer;
  9337. }
  9338. };
  9339. Engine.prototype.updateArrayBuffer = function (data) {
  9340. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9341. };
  9342. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9343. var pointer = this._currentBufferPointers[indx];
  9344. var changed = false;
  9345. if (!pointer.active) {
  9346. changed = true;
  9347. pointer.active = true;
  9348. pointer.index = indx;
  9349. pointer.size = size;
  9350. pointer.type = type;
  9351. pointer.normalized = normalized;
  9352. pointer.stride = stride;
  9353. pointer.offset = offset;
  9354. pointer.buffer = buffer;
  9355. }
  9356. else {
  9357. if (pointer.buffer !== buffer) {
  9358. pointer.buffer = buffer;
  9359. changed = true;
  9360. }
  9361. if (pointer.size !== size) {
  9362. pointer.size = size;
  9363. changed = true;
  9364. }
  9365. if (pointer.type !== type) {
  9366. pointer.type = type;
  9367. changed = true;
  9368. }
  9369. if (pointer.normalized !== normalized) {
  9370. pointer.normalized = normalized;
  9371. changed = true;
  9372. }
  9373. if (pointer.stride !== stride) {
  9374. pointer.stride = stride;
  9375. changed = true;
  9376. }
  9377. if (pointer.offset !== offset) {
  9378. pointer.offset = offset;
  9379. changed = true;
  9380. }
  9381. }
  9382. if (changed || this._vaoRecordInProgress) {
  9383. this.bindArrayBuffer(buffer);
  9384. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9385. }
  9386. };
  9387. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9388. if (indexBuffer == null) {
  9389. return;
  9390. }
  9391. if (this._cachedIndexBuffer !== indexBuffer) {
  9392. this._cachedIndexBuffer = indexBuffer;
  9393. this.bindIndexBuffer(indexBuffer);
  9394. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9395. }
  9396. };
  9397. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9398. var attributes = effect.getAttributesNames();
  9399. if (!this._vaoRecordInProgress) {
  9400. this._unbindVertexArrayObject();
  9401. }
  9402. this.unbindAllAttributes();
  9403. for (var index = 0; index < attributes.length; index++) {
  9404. var order = effect.getAttributeLocation(index);
  9405. if (order >= 0) {
  9406. var vertexBuffer = vertexBuffers[attributes[index]];
  9407. if (!vertexBuffer) {
  9408. continue;
  9409. }
  9410. this._gl.enableVertexAttribArray(order);
  9411. if (!this._vaoRecordInProgress) {
  9412. this._vertexAttribArraysEnabled[order] = true;
  9413. }
  9414. var buffer = vertexBuffer.getBuffer();
  9415. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9416. if (vertexBuffer.getIsInstanced()) {
  9417. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9418. if (!this._vaoRecordInProgress) {
  9419. this._currentInstanceLocations.push(order);
  9420. this._currentInstanceBuffers.push(buffer);
  9421. }
  9422. }
  9423. }
  9424. }
  9425. };
  9426. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9427. var vao = this._gl.createVertexArray();
  9428. this._vaoRecordInProgress = true;
  9429. this._gl.bindVertexArray(vao);
  9430. this._mustWipeVertexAttributes = true;
  9431. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9432. this.bindIndexBuffer(indexBuffer);
  9433. this._vaoRecordInProgress = false;
  9434. this._gl.bindVertexArray(null);
  9435. return vao;
  9436. };
  9437. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9438. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9439. this._cachedVertexArrayObject = vertexArrayObject;
  9440. this._gl.bindVertexArray(vertexArrayObject);
  9441. this._cachedVertexBuffers = null;
  9442. this._cachedIndexBuffer = null;
  9443. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9444. this._mustWipeVertexAttributes = true;
  9445. }
  9446. };
  9447. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9448. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9449. this._cachedVertexBuffers = vertexBuffer;
  9450. this._cachedEffectForVertexBuffers = effect;
  9451. var attributesCount = effect.getAttributesCount();
  9452. this._unbindVertexArrayObject();
  9453. this.unbindAllAttributes();
  9454. var offset = 0;
  9455. for (var index = 0; index < attributesCount; index++) {
  9456. if (index < vertexDeclaration.length) {
  9457. var order = effect.getAttributeLocation(index);
  9458. if (order >= 0) {
  9459. this._gl.enableVertexAttribArray(order);
  9460. this._vertexAttribArraysEnabled[order] = true;
  9461. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9462. }
  9463. offset += vertexDeclaration[index] * 4;
  9464. }
  9465. }
  9466. }
  9467. this._bindIndexBufferWithCache(indexBuffer);
  9468. };
  9469. Engine.prototype._unbindVertexArrayObject = function () {
  9470. if (!this._cachedVertexArrayObject) {
  9471. return;
  9472. }
  9473. this._cachedVertexArrayObject = null;
  9474. this._gl.bindVertexArray(null);
  9475. };
  9476. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9477. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9478. this._cachedVertexBuffers = vertexBuffers;
  9479. this._cachedEffectForVertexBuffers = effect;
  9480. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9481. }
  9482. this._bindIndexBufferWithCache(indexBuffer);
  9483. };
  9484. Engine.prototype.unbindInstanceAttributes = function () {
  9485. var boundBuffer;
  9486. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9487. var instancesBuffer = this._currentInstanceBuffers[i];
  9488. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9489. boundBuffer = instancesBuffer;
  9490. this.bindArrayBuffer(instancesBuffer);
  9491. }
  9492. var offsetLocation = this._currentInstanceLocations[i];
  9493. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9494. }
  9495. this._currentInstanceBuffers.length = 0;
  9496. this._currentInstanceLocations.length = 0;
  9497. };
  9498. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9499. this._gl.deleteVertexArray(vao);
  9500. };
  9501. Engine.prototype._releaseBuffer = function (buffer) {
  9502. buffer.references--;
  9503. if (buffer.references === 0) {
  9504. this._gl.deleteBuffer(buffer);
  9505. return true;
  9506. }
  9507. return false;
  9508. };
  9509. Engine.prototype.createInstancesBuffer = function (capacity) {
  9510. var buffer = this._gl.createBuffer();
  9511. buffer.capacity = capacity;
  9512. this.bindArrayBuffer(buffer);
  9513. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9514. return buffer;
  9515. };
  9516. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9517. this._gl.deleteBuffer(buffer);
  9518. };
  9519. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9520. this.bindArrayBuffer(instancesBuffer);
  9521. if (data) {
  9522. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9523. }
  9524. if (offsetLocations[0].index !== undefined) {
  9525. var stride = 0;
  9526. for (var i = 0; i < offsetLocations.length; i++) {
  9527. var ai = offsetLocations[i];
  9528. stride += ai.attributeSize * 4;
  9529. }
  9530. for (var i = 0; i < offsetLocations.length; i++) {
  9531. var ai = offsetLocations[i];
  9532. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9533. this._gl.enableVertexAttribArray(ai.index);
  9534. this._vertexAttribArraysEnabled[ai.index] = true;
  9535. }
  9536. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9537. this._gl.vertexAttribDivisor(ai.index, 1);
  9538. this._currentInstanceLocations.push(ai.index);
  9539. this._currentInstanceBuffers.push(instancesBuffer);
  9540. }
  9541. }
  9542. else {
  9543. for (var index = 0; index < 4; index++) {
  9544. var offsetLocation = offsetLocations[index];
  9545. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9546. this._gl.enableVertexAttribArray(offsetLocation);
  9547. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9548. }
  9549. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9550. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9551. this._currentInstanceLocations.push(offsetLocation);
  9552. this._currentInstanceBuffers.push(instancesBuffer);
  9553. }
  9554. }
  9555. };
  9556. Engine.prototype.applyStates = function () {
  9557. this._depthCullingState.apply(this._gl);
  9558. this._stencilState.apply(this._gl);
  9559. this._alphaState.apply(this._gl);
  9560. };
  9561. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9562. // Apply states
  9563. this.applyStates();
  9564. this._drawCalls.addCount(1, false);
  9565. // Render
  9566. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9567. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9568. if (instancesCount) {
  9569. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9570. return;
  9571. }
  9572. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9573. };
  9574. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9575. // Apply states
  9576. this.applyStates();
  9577. this._drawCalls.addCount(1, false);
  9578. if (instancesCount) {
  9579. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9580. return;
  9581. }
  9582. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9583. };
  9584. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9585. // Apply states
  9586. this.applyStates();
  9587. this._drawCalls.addCount(1, false);
  9588. if (instancesCount) {
  9589. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9590. return;
  9591. }
  9592. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9593. };
  9594. // Shaders
  9595. Engine.prototype._releaseEffect = function (effect) {
  9596. if (this._compiledEffects[effect._key]) {
  9597. delete this._compiledEffects[effect._key];
  9598. this._deleteProgram(effect.getProgram());
  9599. }
  9600. };
  9601. Engine.prototype._deleteProgram = function (program) {
  9602. if (program) {
  9603. program.__SPECTOR_rebuildProgram = null;
  9604. this._gl.deleteProgram(program);
  9605. }
  9606. };
  9607. /**
  9608. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9609. * @param samplers An array of string used to represent textures
  9610. */
  9611. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9612. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9613. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9614. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9615. if (this._compiledEffects[name]) {
  9616. var compiledEffect = this._compiledEffects[name];
  9617. if (onCompiled && compiledEffect.isReady()) {
  9618. onCompiled(compiledEffect);
  9619. }
  9620. return compiledEffect;
  9621. }
  9622. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9623. effect._key = name;
  9624. this._compiledEffects[name] = effect;
  9625. return effect;
  9626. };
  9627. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9628. if (uniformsNames === void 0) { uniformsNames = []; }
  9629. if (samplers === void 0) { samplers = []; }
  9630. if (defines === void 0) { defines = ""; }
  9631. return this.createEffect({
  9632. vertex: "particles",
  9633. fragmentElement: fragmentName
  9634. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9635. };
  9636. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context) {
  9637. context = context || this._gl;
  9638. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  9639. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  9640. return this._createShaderProgram(vertexShader, fragmentShader, context);
  9641. };
  9642. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9643. context = context || this._gl;
  9644. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9645. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9646. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9647. return this._createShaderProgram(vertexShader, fragmentShader, context);
  9648. };
  9649. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context) {
  9650. var shaderProgram = context.createProgram();
  9651. context.attachShader(shaderProgram, vertexShader);
  9652. context.attachShader(shaderProgram, fragmentShader);
  9653. context.linkProgram(shaderProgram);
  9654. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9655. if (!linked) {
  9656. context.validateProgram(shaderProgram);
  9657. var error = context.getProgramInfoLog(shaderProgram);
  9658. if (error) {
  9659. throw new Error(error);
  9660. }
  9661. }
  9662. context.deleteShader(vertexShader);
  9663. context.deleteShader(fragmentShader);
  9664. return shaderProgram;
  9665. };
  9666. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9667. var results = [];
  9668. for (var index = 0; index < uniformsNames.length; index++) {
  9669. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9670. }
  9671. return results;
  9672. };
  9673. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9674. var results = [];
  9675. for (var index = 0; index < attributesNames.length; index++) {
  9676. try {
  9677. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9678. }
  9679. catch (e) {
  9680. results.push(-1);
  9681. }
  9682. }
  9683. return results;
  9684. };
  9685. Engine.prototype.enableEffect = function (effect) {
  9686. // Use program
  9687. this.setProgram(effect.getProgram());
  9688. this._currentEffect = effect;
  9689. if (effect.onBind) {
  9690. effect.onBind(effect);
  9691. }
  9692. effect.onBindObservable.notifyObservers(effect);
  9693. };
  9694. Engine.prototype.setIntArray = function (uniform, array) {
  9695. if (!uniform)
  9696. return;
  9697. this._gl.uniform1iv(uniform, array);
  9698. };
  9699. Engine.prototype.setIntArray2 = function (uniform, array) {
  9700. if (!uniform || array.length % 2 !== 0)
  9701. return;
  9702. this._gl.uniform2iv(uniform, array);
  9703. };
  9704. Engine.prototype.setIntArray3 = function (uniform, array) {
  9705. if (!uniform || array.length % 3 !== 0)
  9706. return;
  9707. this._gl.uniform3iv(uniform, array);
  9708. };
  9709. Engine.prototype.setIntArray4 = function (uniform, array) {
  9710. if (!uniform || array.length % 4 !== 0)
  9711. return;
  9712. this._gl.uniform4iv(uniform, array);
  9713. };
  9714. Engine.prototype.setFloatArray = function (uniform, array) {
  9715. if (!uniform)
  9716. return;
  9717. this._gl.uniform1fv(uniform, array);
  9718. };
  9719. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9720. if (!uniform || array.length % 2 !== 0)
  9721. return;
  9722. this._gl.uniform2fv(uniform, array);
  9723. };
  9724. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9725. if (!uniform || array.length % 3 !== 0)
  9726. return;
  9727. this._gl.uniform3fv(uniform, array);
  9728. };
  9729. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9730. if (!uniform || array.length % 4 !== 0)
  9731. return;
  9732. this._gl.uniform4fv(uniform, array);
  9733. };
  9734. Engine.prototype.setArray = function (uniform, array) {
  9735. if (!uniform)
  9736. return;
  9737. this._gl.uniform1fv(uniform, array);
  9738. };
  9739. Engine.prototype.setArray2 = function (uniform, array) {
  9740. if (!uniform || array.length % 2 !== 0)
  9741. return;
  9742. this._gl.uniform2fv(uniform, array);
  9743. };
  9744. Engine.prototype.setArray3 = function (uniform, array) {
  9745. if (!uniform || array.length % 3 !== 0)
  9746. return;
  9747. this._gl.uniform3fv(uniform, array);
  9748. };
  9749. Engine.prototype.setArray4 = function (uniform, array) {
  9750. if (!uniform || array.length % 4 !== 0)
  9751. return;
  9752. this._gl.uniform4fv(uniform, array);
  9753. };
  9754. Engine.prototype.setMatrices = function (uniform, matrices) {
  9755. if (!uniform)
  9756. return;
  9757. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9758. };
  9759. Engine.prototype.setMatrix = function (uniform, matrix) {
  9760. if (!uniform)
  9761. return;
  9762. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9763. };
  9764. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9765. if (!uniform)
  9766. return;
  9767. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9768. };
  9769. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9770. if (!uniform)
  9771. return;
  9772. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9773. };
  9774. Engine.prototype.setFloat = function (uniform, value) {
  9775. if (!uniform)
  9776. return;
  9777. this._gl.uniform1f(uniform, value);
  9778. };
  9779. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9780. if (!uniform)
  9781. return;
  9782. this._gl.uniform2f(uniform, x, y);
  9783. };
  9784. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9785. if (!uniform)
  9786. return;
  9787. this._gl.uniform3f(uniform, x, y, z);
  9788. };
  9789. Engine.prototype.setBool = function (uniform, bool) {
  9790. if (!uniform)
  9791. return;
  9792. this._gl.uniform1i(uniform, bool);
  9793. };
  9794. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9795. if (!uniform)
  9796. return;
  9797. this._gl.uniform4f(uniform, x, y, z, w);
  9798. };
  9799. Engine.prototype.setColor3 = function (uniform, color3) {
  9800. if (!uniform)
  9801. return;
  9802. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9803. };
  9804. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9805. if (!uniform)
  9806. return;
  9807. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9808. };
  9809. // States
  9810. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9811. if (zOffset === void 0) { zOffset = 0; }
  9812. if (reverseSide === void 0) { reverseSide = false; }
  9813. // Culling
  9814. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9815. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9816. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9817. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9818. if (culling) {
  9819. this._depthCullingState.cullFace = cullFace;
  9820. this._depthCullingState.cull = true;
  9821. }
  9822. else {
  9823. this._depthCullingState.cull = false;
  9824. }
  9825. }
  9826. // Z offset
  9827. this.setZOffset(zOffset);
  9828. };
  9829. Engine.prototype.setZOffset = function (value) {
  9830. this._depthCullingState.zOffset = value;
  9831. };
  9832. Engine.prototype.getZOffset = function () {
  9833. return this._depthCullingState.zOffset;
  9834. };
  9835. Engine.prototype.setDepthBuffer = function (enable) {
  9836. this._depthCullingState.depthTest = enable;
  9837. };
  9838. Engine.prototype.getDepthWrite = function () {
  9839. return this._depthCullingState.depthMask;
  9840. };
  9841. Engine.prototype.setDepthWrite = function (enable) {
  9842. this._depthCullingState.depthMask = enable;
  9843. };
  9844. Engine.prototype.setColorWrite = function (enable) {
  9845. this._gl.colorMask(enable, enable, enable, enable);
  9846. this._colorWrite = enable;
  9847. };
  9848. Engine.prototype.getColorWrite = function () {
  9849. return this._colorWrite;
  9850. };
  9851. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9852. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9853. };
  9854. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9855. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9856. if (this._alphaMode === mode) {
  9857. return;
  9858. }
  9859. switch (mode) {
  9860. case Engine.ALPHA_DISABLE:
  9861. this._alphaState.alphaBlend = false;
  9862. break;
  9863. case Engine.ALPHA_PREMULTIPLIED:
  9864. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9865. this._alphaState.alphaBlend = true;
  9866. break;
  9867. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9868. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9869. this._alphaState.alphaBlend = true;
  9870. break;
  9871. case Engine.ALPHA_COMBINE:
  9872. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9873. this._alphaState.alphaBlend = true;
  9874. break;
  9875. case Engine.ALPHA_ONEONE:
  9876. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9877. this._alphaState.alphaBlend = true;
  9878. break;
  9879. case Engine.ALPHA_ADD:
  9880. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9881. this._alphaState.alphaBlend = true;
  9882. break;
  9883. case Engine.ALPHA_SUBTRACT:
  9884. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9885. this._alphaState.alphaBlend = true;
  9886. break;
  9887. case Engine.ALPHA_MULTIPLY:
  9888. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9889. this._alphaState.alphaBlend = true;
  9890. break;
  9891. case Engine.ALPHA_MAXIMIZED:
  9892. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9893. this._alphaState.alphaBlend = true;
  9894. break;
  9895. case Engine.ALPHA_INTERPOLATE:
  9896. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9897. this._alphaState.alphaBlend = true;
  9898. break;
  9899. case Engine.ALPHA_SCREENMODE:
  9900. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9901. this._alphaState.alphaBlend = true;
  9902. break;
  9903. }
  9904. if (!noDepthWriteChange) {
  9905. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9906. }
  9907. this._alphaMode = mode;
  9908. };
  9909. Engine.prototype.getAlphaMode = function () {
  9910. return this._alphaMode;
  9911. };
  9912. Engine.prototype.setAlphaTesting = function (enable) {
  9913. this._alphaTest = enable;
  9914. };
  9915. Engine.prototype.getAlphaTesting = function () {
  9916. return !!this._alphaTest;
  9917. };
  9918. // Textures
  9919. Engine.prototype.wipeCaches = function (bruteForce) {
  9920. if (this.preventCacheWipeBetweenFrames) {
  9921. return;
  9922. }
  9923. this.resetTextureCache();
  9924. this._currentEffect = null;
  9925. // 6/8/2017: deltakosh: Should not be required anymore.
  9926. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9927. if (bruteForce) {
  9928. this._currentProgram = null;
  9929. this._stencilState.reset();
  9930. this._depthCullingState.reset();
  9931. this.setDepthFunctionToLessOrEqual();
  9932. this._alphaState.reset();
  9933. }
  9934. this._cachedVertexBuffers = null;
  9935. this._cachedIndexBuffer = null;
  9936. this._cachedEffectForVertexBuffers = null;
  9937. this._unbindVertexArrayObject();
  9938. this.bindIndexBuffer(null);
  9939. this.bindArrayBuffer(null);
  9940. };
  9941. /**
  9942. * Set the compressed texture format to use, based on the formats you have, and the formats
  9943. * supported by the hardware / browser.
  9944. *
  9945. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9946. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9947. * to API arguments needed to compressed textures. This puts the burden on the container
  9948. * generator to house the arcane code for determining these for current & future formats.
  9949. *
  9950. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9951. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9952. *
  9953. * Note: The result of this call is not taken into account when a texture is base64.
  9954. *
  9955. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9956. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9957. *
  9958. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9959. * @returns The extension selected.
  9960. */
  9961. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9962. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9963. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9964. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9965. return this._textureFormatInUse = this._texturesSupported[i];
  9966. }
  9967. }
  9968. }
  9969. // actively set format to nothing, to allow this to be called more than once
  9970. // and possibly fail the 2nd time
  9971. return this._textureFormatInUse = null;
  9972. };
  9973. Engine.prototype._createTexture = function () {
  9974. return this._gl.createTexture();
  9975. };
  9976. /**
  9977. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9978. * @param {string} urlArg- This contains one of the following:
  9979. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9980. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9981. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9982. *
  9983. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9984. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9985. * @param {Scene} scene- Needed for loading to the correct scene.
  9986. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9987. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9988. * @param {callback} onError- Optional callback to be called upon failure.
  9989. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9990. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9991. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9992. *
  9993. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9994. */
  9995. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9996. var _this = this;
  9997. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9998. if (onLoad === void 0) { onLoad = null; }
  9999. if (onError === void 0) { onError = null; }
  10000. if (buffer === void 0) { buffer = null; }
  10001. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10002. var fromData = url.substr(0, 5) === "data:";
  10003. var fromBlob = url.substr(0, 5) === "blob:";
  10004. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10005. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10006. // establish the file extension, if possible
  10007. var lastDot = url.lastIndexOf('.');
  10008. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10009. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10010. var isTGA = (extension === ".tga");
  10011. // determine if a ktx file should be substituted
  10012. var isKTX = false;
  10013. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10014. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10015. isKTX = true;
  10016. }
  10017. if (scene) {
  10018. scene._addPendingData(texture);
  10019. }
  10020. texture.url = url;
  10021. texture.generateMipMaps = !noMipmap;
  10022. texture.samplingMode = samplingMode;
  10023. texture.invertY = invertY;
  10024. if (!this._doNotHandleContextLost) {
  10025. // Keep a link to the buffer only if we plan to handle context lost
  10026. texture._buffer = buffer;
  10027. }
  10028. if (onLoad) {
  10029. texture.onLoadedObservable.add(onLoad);
  10030. }
  10031. if (!fallBack)
  10032. this._internalTexturesCache.push(texture);
  10033. var onerror = function () {
  10034. if (scene) {
  10035. scene._removePendingData(texture);
  10036. }
  10037. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10038. if (isKTX) {
  10039. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10040. }
  10041. else if (onError) {
  10042. onError();
  10043. }
  10044. };
  10045. var callback;
  10046. // processing for non-image formats
  10047. if (isKTX || isTGA || isDDS) {
  10048. if (isKTX) {
  10049. callback = function (data) {
  10050. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10051. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10052. ktx.uploadLevels(_this._gl, !noMipmap);
  10053. return false;
  10054. }, samplingMode);
  10055. };
  10056. }
  10057. else if (isTGA) {
  10058. callback = function (arrayBuffer) {
  10059. var data = new Uint8Array(arrayBuffer);
  10060. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10061. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10062. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10063. return false;
  10064. }, samplingMode);
  10065. };
  10066. }
  10067. else if (isDDS) {
  10068. callback = function (data) {
  10069. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10070. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10071. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10072. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10073. return false;
  10074. }, samplingMode);
  10075. };
  10076. }
  10077. if (!buffer) {
  10078. BABYLON.Tools.LoadFile(url, function (data) {
  10079. callback(data);
  10080. }, null, scene ? scene.database : null, true, onerror);
  10081. }
  10082. else {
  10083. callback(buffer);
  10084. }
  10085. // image format processing
  10086. }
  10087. else {
  10088. var onload = function (img) {
  10089. if (fromBlob && !_this._doNotHandleContextLost) {
  10090. // We need to store the image if we need to rebuild the texture
  10091. // in case of a webgl context lost
  10092. texture._buffer = img;
  10093. }
  10094. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10095. var gl = _this._gl;
  10096. var isPot = (img.width === potWidth && img.height === potHeight);
  10097. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10098. if (isPot) {
  10099. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10100. return false;
  10101. }
  10102. // Using shaders to rescale because canvas.drawImage is lossy
  10103. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10104. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10105. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10106. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10107. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10108. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10109. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10110. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10111. _this._releaseTexture(source);
  10112. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10113. continuationCallback();
  10114. });
  10115. return true;
  10116. }, samplingMode);
  10117. };
  10118. if (!fromData || isBase64)
  10119. if (buffer instanceof HTMLImageElement) {
  10120. onload(buffer);
  10121. }
  10122. else {
  10123. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10124. }
  10125. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10126. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10127. else
  10128. onload(buffer);
  10129. }
  10130. return texture;
  10131. };
  10132. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10133. var _this = this;
  10134. var rtt = this.createRenderTargetTexture({
  10135. width: destination.width,
  10136. height: destination.height,
  10137. }, {
  10138. generateMipMaps: false,
  10139. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10140. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10141. generateDepthBuffer: false,
  10142. generateStencilBuffer: false
  10143. });
  10144. if (!this._rescalePostProcess) {
  10145. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10146. }
  10147. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10148. _this._rescalePostProcess.onApply = function (effect) {
  10149. effect._bindTexture("textureSampler", source);
  10150. };
  10151. var hostingScene = scene;
  10152. if (!hostingScene) {
  10153. hostingScene = _this.scenes[_this.scenes.length - 1];
  10154. }
  10155. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  10156. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10157. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10158. _this.unBindFramebuffer(rtt);
  10159. _this._releaseTexture(rtt);
  10160. if (onComplete) {
  10161. onComplete();
  10162. }
  10163. });
  10164. };
  10165. Engine.prototype._getInternalFormat = function (format) {
  10166. var internalFormat = this._gl.RGBA;
  10167. switch (format) {
  10168. case Engine.TEXTUREFORMAT_ALPHA:
  10169. internalFormat = this._gl.ALPHA;
  10170. break;
  10171. case Engine.TEXTUREFORMAT_LUMINANCE:
  10172. internalFormat = this._gl.LUMINANCE;
  10173. break;
  10174. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10175. internalFormat = this._gl.LUMINANCE_ALPHA;
  10176. break;
  10177. case Engine.TEXTUREFORMAT_RGB:
  10178. internalFormat = this._gl.RGB;
  10179. break;
  10180. case Engine.TEXTUREFORMAT_RGBA:
  10181. internalFormat = this._gl.RGBA;
  10182. break;
  10183. }
  10184. return internalFormat;
  10185. };
  10186. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  10187. if (compression === void 0) { compression = null; }
  10188. var internalFormat = this._getInternalFormat(format);
  10189. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10190. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10191. if (!this._doNotHandleContextLost) {
  10192. texture._bufferView = data;
  10193. texture.format = format;
  10194. texture.invertY = invertY;
  10195. texture._compression = compression;
  10196. }
  10197. if (texture.width % 4 !== 0) {
  10198. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10199. }
  10200. if (compression) {
  10201. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10202. }
  10203. else {
  10204. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  10205. }
  10206. if (texture.generateMipMaps) {
  10207. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10208. }
  10209. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10210. this.resetTextureCache();
  10211. texture.isReady = true;
  10212. };
  10213. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  10214. if (compression === void 0) { compression = null; }
  10215. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10216. texture.baseWidth = width;
  10217. texture.baseHeight = height;
  10218. texture.width = width;
  10219. texture.height = height;
  10220. texture.format = format;
  10221. texture.generateMipMaps = generateMipMaps;
  10222. texture.samplingMode = samplingMode;
  10223. texture.invertY = invertY;
  10224. texture._compression = compression;
  10225. if (!this._doNotHandleContextLost) {
  10226. texture._bufferView = data;
  10227. }
  10228. this.updateRawTexture(texture, data, format, invertY, compression);
  10229. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10230. // Filters
  10231. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10232. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10233. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10234. if (generateMipMaps) {
  10235. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10236. }
  10237. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10238. this._internalTexturesCache.push(texture);
  10239. return texture;
  10240. };
  10241. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10242. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10243. texture.baseWidth = width;
  10244. texture.baseHeight = height;
  10245. if (generateMipMaps) {
  10246. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10247. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10248. }
  10249. this.resetTextureCache();
  10250. texture.width = width;
  10251. texture.height = height;
  10252. texture.isReady = false;
  10253. texture.generateMipMaps = generateMipMaps;
  10254. texture.samplingMode = samplingMode;
  10255. this.updateTextureSamplingMode(samplingMode, texture);
  10256. this._internalTexturesCache.push(texture);
  10257. return texture;
  10258. };
  10259. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10260. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10261. if (texture.isCube) {
  10262. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10263. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10264. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10265. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10266. }
  10267. else {
  10268. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10269. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10270. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10271. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10272. }
  10273. texture.samplingMode = samplingMode;
  10274. };
  10275. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10276. if (premulAlpha === void 0) { premulAlpha = false; }
  10277. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10278. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10279. if (premulAlpha) {
  10280. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10281. }
  10282. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10283. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10284. if (texture.generateMipMaps) {
  10285. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10286. }
  10287. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10288. if (premulAlpha) {
  10289. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10290. }
  10291. this.resetTextureCache();
  10292. texture.isReady = true;
  10293. };
  10294. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10295. if (texture._isDisabled) {
  10296. return;
  10297. }
  10298. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10299. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10300. try {
  10301. // Testing video texture support
  10302. if (this._videoTextureSupported === undefined) {
  10303. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10304. if (this._gl.getError() !== 0) {
  10305. this._videoTextureSupported = false;
  10306. }
  10307. else {
  10308. this._videoTextureSupported = true;
  10309. }
  10310. }
  10311. // Copy video through the current working canvas if video texture is not supported
  10312. if (!this._videoTextureSupported) {
  10313. if (!texture._workingCanvas) {
  10314. texture._workingCanvas = document.createElement("canvas");
  10315. texture._workingContext = texture._workingCanvas.getContext("2d");
  10316. texture._workingCanvas.width = texture.width;
  10317. texture._workingCanvas.height = texture.height;
  10318. }
  10319. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10320. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10321. }
  10322. else {
  10323. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10324. }
  10325. if (texture.generateMipMaps) {
  10326. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10327. }
  10328. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10329. this.resetTextureCache();
  10330. texture.isReady = true;
  10331. }
  10332. catch (ex) {
  10333. // Something unexpected
  10334. // Let's disable the texture
  10335. texture._isDisabled = true;
  10336. }
  10337. };
  10338. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10339. var fullOptions = new RenderTargetCreationOptions();
  10340. if (options !== undefined && typeof options === "object") {
  10341. fullOptions.generateMipMaps = options.generateMipMaps;
  10342. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10343. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10344. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10345. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10346. }
  10347. else {
  10348. fullOptions.generateMipMaps = options;
  10349. fullOptions.generateDepthBuffer = true;
  10350. fullOptions.generateStencilBuffer = false;
  10351. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10352. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10353. }
  10354. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10355. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10356. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10357. }
  10358. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10359. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10360. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10361. }
  10362. var gl = this._gl;
  10363. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10364. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10365. var width = size.width || size;
  10366. var height = size.height || size;
  10367. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  10368. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10369. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10370. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10371. }
  10372. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10373. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10374. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10375. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10376. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10377. // Create the framebuffer
  10378. var framebuffer = gl.createFramebuffer();
  10379. this.bindUnboundFramebuffer(framebuffer);
  10380. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10381. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, width, height);
  10382. if (fullOptions.generateMipMaps) {
  10383. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10384. }
  10385. // Unbind
  10386. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10387. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10388. this.bindUnboundFramebuffer(null);
  10389. texture._framebuffer = framebuffer;
  10390. texture.baseWidth = width;
  10391. texture.baseHeight = height;
  10392. texture.width = width;
  10393. texture.height = height;
  10394. texture.isReady = true;
  10395. texture.samples = 1;
  10396. texture.generateMipMaps = fullOptions.generateMipMaps;
  10397. texture.samplingMode = fullOptions.samplingMode;
  10398. texture.type = fullOptions.type;
  10399. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10400. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  10401. this.resetTextureCache();
  10402. this._internalTexturesCache.push(texture);
  10403. return texture;
  10404. };
  10405. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10406. var generateMipMaps = false;
  10407. var generateDepthBuffer = true;
  10408. var generateStencilBuffer = false;
  10409. var generateDepthTexture = false;
  10410. var textureCount = 1;
  10411. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10412. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10413. var types = [], samplingModes = [];
  10414. if (options !== undefined) {
  10415. generateMipMaps = options.generateMipMaps;
  10416. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10417. generateStencilBuffer = options.generateStencilBuffer;
  10418. generateDepthTexture = options.generateDepthTexture;
  10419. textureCount = options.textureCount || 1;
  10420. if (options.types) {
  10421. types = options.types;
  10422. }
  10423. if (options.samplingModes) {
  10424. samplingModes = options.samplingModes;
  10425. }
  10426. }
  10427. var gl = this._gl;
  10428. // Create the framebuffer
  10429. var framebuffer = gl.createFramebuffer();
  10430. this.bindUnboundFramebuffer(framebuffer);
  10431. var width = size.width || size;
  10432. var height = size.height || size;
  10433. var textures = [];
  10434. var attachments = [];
  10435. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10436. for (var i = 0; i < textureCount; i++) {
  10437. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10438. var type = types[i] || defaultType;
  10439. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10440. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10441. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10442. }
  10443. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10444. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10445. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10446. }
  10447. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10448. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10449. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10450. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10451. }
  10452. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10453. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10454. textures.push(texture);
  10455. attachments.push(attachment);
  10456. gl.activeTexture(gl["TEXTURE" + i]);
  10457. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10458. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10459. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10460. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10461. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10462. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10463. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10464. if (generateMipMaps) {
  10465. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10466. }
  10467. // Unbind
  10468. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10469. texture._framebuffer = framebuffer;
  10470. texture._depthStencilBuffer = depthStencilBuffer;
  10471. texture.baseWidth = width;
  10472. texture.baseHeight = height;
  10473. texture.width = width;
  10474. texture.height = height;
  10475. texture.isReady = true;
  10476. texture.samples = 1;
  10477. texture.generateMipMaps = generateMipMaps;
  10478. texture.samplingMode = samplingMode;
  10479. texture.type = type;
  10480. texture._generateDepthBuffer = generateDepthBuffer;
  10481. texture._generateStencilBuffer = generateStencilBuffer;
  10482. this._internalTexturesCache.push(texture);
  10483. }
  10484. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10485. // Depth texture
  10486. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10487. gl.activeTexture(gl.TEXTURE0);
  10488. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10489. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10490. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10491. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10492. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10493. 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);
  10494. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10495. depthTexture._framebuffer = framebuffer;
  10496. depthTexture.baseWidth = width;
  10497. depthTexture.baseHeight = height;
  10498. depthTexture.width = width;
  10499. depthTexture.height = height;
  10500. depthTexture.isReady = true;
  10501. depthTexture.samples = 1;
  10502. depthTexture.generateMipMaps = generateMipMaps;
  10503. depthTexture.samplingMode = gl.NEAREST;
  10504. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10505. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10506. textures.push(depthTexture);
  10507. this._internalTexturesCache.push(depthTexture);
  10508. }
  10509. gl.drawBuffers(attachments);
  10510. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10511. this.bindUnboundFramebuffer(null);
  10512. this.resetTextureCache();
  10513. return textures;
  10514. };
  10515. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10516. if (samples === void 0) { samples = 1; }
  10517. var depthStencilBuffer = null;
  10518. var gl = this._gl;
  10519. // Create the depth/stencil buffer
  10520. if (generateStencilBuffer) {
  10521. depthStencilBuffer = gl.createRenderbuffer();
  10522. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10523. if (samples > 1) {
  10524. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10525. }
  10526. else {
  10527. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10528. }
  10529. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10530. }
  10531. else if (generateDepthBuffer) {
  10532. depthStencilBuffer = gl.createRenderbuffer();
  10533. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10534. if (samples > 1) {
  10535. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10536. }
  10537. else {
  10538. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10539. }
  10540. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10541. }
  10542. return depthStencilBuffer;
  10543. };
  10544. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10545. if (this.webGLVersion < 2) {
  10546. return 1;
  10547. }
  10548. if (texture.samples === samples) {
  10549. return samples;
  10550. }
  10551. var gl = this._gl;
  10552. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10553. // Dispose previous render buffers
  10554. if (texture._depthStencilBuffer) {
  10555. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10556. }
  10557. if (texture._MSAAFramebuffer) {
  10558. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10559. }
  10560. if (texture._MSAARenderBuffer) {
  10561. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10562. }
  10563. if (samples > 1) {
  10564. texture._MSAAFramebuffer = gl.createFramebuffer();
  10565. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10566. var colorRenderbuffer = gl.createRenderbuffer();
  10567. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10568. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10569. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10570. texture._MSAARenderBuffer = colorRenderbuffer;
  10571. }
  10572. else {
  10573. this.bindUnboundFramebuffer(texture._framebuffer);
  10574. }
  10575. texture.samples = samples;
  10576. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10577. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10578. this.bindUnboundFramebuffer(null);
  10579. return samples;
  10580. };
  10581. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10582. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10583. };
  10584. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10585. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10586. };
  10587. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10588. var gl = this._gl;
  10589. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10590. var generateMipMaps = true;
  10591. var generateDepthBuffer = true;
  10592. var generateStencilBuffer = false;
  10593. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10594. if (options !== undefined) {
  10595. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10596. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10597. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10598. if (options.samplingMode !== undefined) {
  10599. samplingMode = options.samplingMode;
  10600. }
  10601. }
  10602. texture.isCube = true;
  10603. texture.generateMipMaps = generateMipMaps;
  10604. texture.samples = 1;
  10605. texture.samplingMode = samplingMode;
  10606. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10607. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10608. for (var face = 0; face < 6; face++) {
  10609. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10610. }
  10611. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10612. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10613. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10614. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10615. // Create the framebuffer
  10616. var framebuffer = gl.createFramebuffer();
  10617. this.bindUnboundFramebuffer(framebuffer);
  10618. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10619. // Mipmaps
  10620. if (texture.generateMipMaps) {
  10621. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10622. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10623. }
  10624. // Unbind
  10625. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10626. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10627. this.bindUnboundFramebuffer(null);
  10628. texture._framebuffer = framebuffer;
  10629. texture.width = size;
  10630. texture.height = size;
  10631. texture.isReady = true;
  10632. this.resetTextureCache();
  10633. this._internalTexturesCache.push(texture);
  10634. return texture;
  10635. };
  10636. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10637. var _this = this;
  10638. if (onError === void 0) { onError = null; }
  10639. if (forcedExtension === void 0) { forcedExtension = null; }
  10640. var callback = function (loadData) {
  10641. if (!loadData) {
  10642. if (onLoad) {
  10643. onLoad(null);
  10644. }
  10645. return;
  10646. }
  10647. var texture = loadData.texture;
  10648. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10649. texture._lodGenerationScale = scale;
  10650. texture._lodGenerationOffset = offset;
  10651. if (_this._caps.textureLOD) {
  10652. // Do not add extra process if texture lod is supported.
  10653. if (onLoad) {
  10654. onLoad(texture);
  10655. }
  10656. return;
  10657. }
  10658. var mipSlices = 3;
  10659. var gl = _this._gl;
  10660. var width = loadData.width;
  10661. if (!width) {
  10662. return;
  10663. }
  10664. var textures = [];
  10665. for (var i = 0; i < mipSlices; i++) {
  10666. //compute LOD from even spacing in smoothness (matching shader calculation)
  10667. var smoothness = i / (mipSlices - 1);
  10668. var roughness = 1 - smoothness;
  10669. var minLODIndex = offset; // roughness = 0
  10670. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10671. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10672. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10673. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10674. glTextureFromLod.isCube = true;
  10675. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10676. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10677. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10678. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10679. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10680. if (loadData.isDDS) {
  10681. var info = loadData.info;
  10682. var data = loadData.data;
  10683. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10684. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10685. }
  10686. else {
  10687. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10688. }
  10689. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10690. // Wrap in a base texture for easy binding.
  10691. var lodTexture = new BABYLON.BaseTexture(scene);
  10692. lodTexture.isCube = true;
  10693. lodTexture._texture = glTextureFromLod;
  10694. glTextureFromLod.isReady = true;
  10695. textures.push(lodTexture);
  10696. }
  10697. texture._lodTextureHigh = textures[2];
  10698. texture._lodTextureMid = textures[1];
  10699. texture._lodTextureLow = textures[0];
  10700. if (onLoad) {
  10701. onLoad(texture);
  10702. }
  10703. };
  10704. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10705. };
  10706. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10707. var _this = this;
  10708. if (onLoad === void 0) { onLoad = null; }
  10709. if (onError === void 0) { onError = null; }
  10710. if (forcedExtension === void 0) { forcedExtension = null; }
  10711. var gl = this._gl;
  10712. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10713. texture.isCube = true;
  10714. texture.url = rootUrl;
  10715. texture.generateMipMaps = !noMipmap;
  10716. if (!this._doNotHandleContextLost) {
  10717. texture._extension = forcedExtension;
  10718. texture._files = files;
  10719. }
  10720. var isKTX = false;
  10721. var isDDS = false;
  10722. var lastDot = rootUrl.lastIndexOf('.');
  10723. if (lastDot > -1) {
  10724. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  10725. if (this._textureFormatInUse) {
  10726. extension = this._textureFormatInUse;
  10727. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10728. isKTX = true;
  10729. }
  10730. else {
  10731. isDDS = (extension === ".dds");
  10732. }
  10733. }
  10734. var onerror = function (request, exception) {
  10735. if (onError) {
  10736. onError(request.status + " " + request.statusText, exception);
  10737. }
  10738. };
  10739. if (isKTX) {
  10740. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10741. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10742. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10743. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10744. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10745. ktx.uploadLevels(_this._gl, !noMipmap);
  10746. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10747. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10748. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10749. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10750. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10751. _this.resetTextureCache();
  10752. texture.width = ktx.pixelWidth;
  10753. texture.height = ktx.pixelHeight;
  10754. texture.isReady = true;
  10755. }, null, null, true, onerror);
  10756. }
  10757. else if (isDDS) {
  10758. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10759. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10760. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10761. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10762. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10763. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10764. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10765. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10766. }
  10767. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10768. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10769. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10770. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10771. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10772. _this.resetTextureCache();
  10773. texture.width = info.width;
  10774. texture.height = info.height;
  10775. texture.isReady = true;
  10776. texture.type = info.textureType;
  10777. if (onLoad) {
  10778. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10779. }
  10780. }, null, null, true, onerror);
  10781. }
  10782. else {
  10783. cascadeLoad(rootUrl, scene, function (imgs) {
  10784. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10785. var height = width;
  10786. _this._prepareWorkingCanvas();
  10787. _this._workingCanvas.width = width;
  10788. _this._workingCanvas.height = height;
  10789. var faces = [
  10790. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10791. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10792. ];
  10793. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10794. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10795. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10796. for (var index = 0; index < faces.length; index++) {
  10797. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10798. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10799. }
  10800. if (!noMipmap) {
  10801. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10802. }
  10803. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10804. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10805. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10806. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10807. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10808. _this.resetTextureCache();
  10809. texture.width = width;
  10810. texture.height = height;
  10811. texture.isReady = true;
  10812. texture.format = format;
  10813. texture.onLoadedObservable.notifyObservers(texture);
  10814. texture.onLoadedObservable.clear();
  10815. if (onLoad) {
  10816. onLoad();
  10817. }
  10818. }, files, onError);
  10819. }
  10820. this._internalTexturesCache.push(texture);
  10821. return texture;
  10822. };
  10823. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10824. if (compression === void 0) { compression = null; }
  10825. if (level === void 0) { level = 0; }
  10826. texture._bufferViewArray = data;
  10827. texture.format = format;
  10828. texture.type = type;
  10829. texture.invertY = invertY;
  10830. texture._compression = compression;
  10831. var gl = this._gl;
  10832. var textureType = this._getWebGLTextureType(type);
  10833. var internalFormat = this._getInternalFormat(format);
  10834. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10835. var needConversion = false;
  10836. if (internalFormat === gl.RGB) {
  10837. internalFormat = gl.RGBA;
  10838. needConversion = true;
  10839. }
  10840. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10841. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10842. if (texture.width % 4 !== 0) {
  10843. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10844. }
  10845. // Data are known to be in +X +Y +Z -X -Y -Z
  10846. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10847. var faceData = data[faceIndex];
  10848. if (compression) {
  10849. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  10850. }
  10851. else {
  10852. if (needConversion) {
  10853. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  10854. }
  10855. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  10856. }
  10857. }
  10858. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10859. if (isPot && texture.generateMipMaps && level === 0) {
  10860. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10861. }
  10862. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10863. this.resetTextureCache();
  10864. texture.isReady = true;
  10865. };
  10866. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10867. if (compression === void 0) { compression = null; }
  10868. var gl = this._gl;
  10869. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  10870. texture.isCube = true;
  10871. texture.generateMipMaps = generateMipMaps;
  10872. texture.format = format;
  10873. texture.type = type;
  10874. if (!this._doNotHandleContextLost) {
  10875. texture._bufferViewArray = data;
  10876. }
  10877. var textureType = this._getWebGLTextureType(type);
  10878. var internalFormat = this._getInternalFormat(format);
  10879. var needConversion = false;
  10880. if (internalFormat === gl.RGB) {
  10881. internalFormat = gl.RGBA;
  10882. needConversion = true;
  10883. }
  10884. var width = size;
  10885. var height = width;
  10886. texture.width = width;
  10887. texture.height = height;
  10888. // Double check on POT to generate Mips.
  10889. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10890. if (!isPot) {
  10891. generateMipMaps = false;
  10892. }
  10893. // Upload data if needed. The texture won't be ready until then.
  10894. if (data) {
  10895. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10896. }
  10897. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10898. // Filters
  10899. if (data && generateMipMaps) {
  10900. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10901. }
  10902. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10903. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10904. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10905. }
  10906. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10907. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10908. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10909. }
  10910. else {
  10911. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10912. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10913. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10914. }
  10915. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10916. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10917. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10918. return texture;
  10919. };
  10920. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10921. var _this = this;
  10922. if (onLoad === void 0) { onLoad = null; }
  10923. if (onError === void 0) { onError = null; }
  10924. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10925. if (invertY === void 0) { invertY = false; }
  10926. var gl = this._gl;
  10927. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10928. scene._addPendingData(texture);
  10929. texture.url = url;
  10930. this._internalTexturesCache.push(texture);
  10931. var onerror = function (request, exception) {
  10932. scene._removePendingData(texture);
  10933. if (onError) {
  10934. onError(request.status + " " + request.statusText, exception);
  10935. }
  10936. };
  10937. var internalCallback = function (data) {
  10938. var width = texture.width;
  10939. var faceDataArrays = callback(data);
  10940. if (mipmmapGenerator) {
  10941. var textureType = _this._getWebGLTextureType(type);
  10942. var internalFormat = _this._getInternalFormat(format);
  10943. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10944. var needConversion = false;
  10945. if (internalFormat === gl.RGB) {
  10946. internalFormat = gl.RGBA;
  10947. needConversion = true;
  10948. }
  10949. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10950. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10951. var mipData = mipmmapGenerator(faceDataArrays);
  10952. for (var level = 0; level < mipData.length; level++) {
  10953. var mipSize = width >> level;
  10954. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10955. var mipFaceData = mipData[level][faceIndex];
  10956. if (needConversion) {
  10957. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10958. }
  10959. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10960. }
  10961. }
  10962. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10963. }
  10964. else {
  10965. texture.generateMipMaps = !noMipmap;
  10966. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10967. }
  10968. texture.isReady = true;
  10969. _this.resetTextureCache();
  10970. scene._removePendingData(texture);
  10971. if (onLoad) {
  10972. onLoad();
  10973. }
  10974. };
  10975. BABYLON.Tools.LoadFile(url, function (data) {
  10976. internalCallback(data);
  10977. }, undefined, scene.database, true, onerror);
  10978. return texture;
  10979. };
  10980. ;
  10981. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  10982. var gl = this._gl;
  10983. if (!gl) {
  10984. return;
  10985. }
  10986. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  10987. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10988. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10989. if (!noMipmap && !isCompressed) {
  10990. gl.generateMipmap(gl.TEXTURE_2D);
  10991. }
  10992. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10993. this.resetTextureCache();
  10994. if (scene) {
  10995. scene._removePendingData(texture);
  10996. }
  10997. texture.onLoadedObservable.notifyObservers(texture);
  10998. texture.onLoadedObservable.clear();
  10999. };
  11000. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11001. var _this = this;
  11002. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11003. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11004. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11005. var gl = this._gl;
  11006. if (!gl) {
  11007. return;
  11008. }
  11009. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11010. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11011. texture.baseWidth = width;
  11012. texture.baseHeight = height;
  11013. texture.width = potWidth;
  11014. texture.height = potHeight;
  11015. texture.isReady = true;
  11016. if (processFunction(potWidth, potHeight, function () {
  11017. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11018. })) {
  11019. // Returning as texture needs extra async steps
  11020. return;
  11021. }
  11022. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11023. };
  11024. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11025. // Create new RGBA data container.
  11026. var rgbaData;
  11027. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11028. rgbaData = new Float32Array(width * height * 4);
  11029. }
  11030. else {
  11031. rgbaData = new Uint32Array(width * height * 4);
  11032. }
  11033. // Convert each pixel.
  11034. for (var x = 0; x < width; x++) {
  11035. for (var y = 0; y < height; y++) {
  11036. var index = (y * width + x) * 3;
  11037. var newIndex = (y * width + x) * 4;
  11038. // Map Old Value to new value.
  11039. rgbaData[newIndex + 0] = rgbData[index + 0];
  11040. rgbaData[newIndex + 1] = rgbData[index + 1];
  11041. rgbaData[newIndex + 2] = rgbData[index + 2];
  11042. // Add fully opaque alpha channel.
  11043. rgbaData[newIndex + 3] = 1;
  11044. }
  11045. }
  11046. return rgbaData;
  11047. };
  11048. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11049. var gl = this._gl;
  11050. if (texture._framebuffer) {
  11051. gl.deleteFramebuffer(texture._framebuffer);
  11052. texture._framebuffer = null;
  11053. }
  11054. if (texture._depthStencilBuffer) {
  11055. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11056. texture._depthStencilBuffer = null;
  11057. }
  11058. if (texture._MSAAFramebuffer) {
  11059. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11060. texture._MSAAFramebuffer = null;
  11061. }
  11062. if (texture._MSAARenderBuffer) {
  11063. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11064. texture._MSAARenderBuffer = null;
  11065. }
  11066. };
  11067. Engine.prototype._releaseTexture = function (texture) {
  11068. var gl = this._gl;
  11069. this._releaseFramebufferObjects(texture);
  11070. gl.deleteTexture(texture._webGLTexture);
  11071. // Unbind channels
  11072. this.unbindAllTextures();
  11073. var index = this._internalTexturesCache.indexOf(texture);
  11074. if (index !== -1) {
  11075. this._internalTexturesCache.splice(index, 1);
  11076. }
  11077. // Integrated fixed lod samplers.
  11078. if (texture._lodTextureHigh) {
  11079. texture._lodTextureHigh.dispose();
  11080. }
  11081. if (texture._lodTextureMid) {
  11082. texture._lodTextureMid.dispose();
  11083. }
  11084. if (texture._lodTextureLow) {
  11085. texture._lodTextureLow.dispose();
  11086. }
  11087. };
  11088. Engine.prototype.setProgram = function (program) {
  11089. if (this._currentProgram !== program) {
  11090. this._gl.useProgram(program);
  11091. this._currentProgram = program;
  11092. }
  11093. };
  11094. Engine.prototype.bindSamplers = function (effect) {
  11095. this.setProgram(effect.getProgram());
  11096. var samplers = effect.getSamplers();
  11097. for (var index = 0; index < samplers.length; index++) {
  11098. var uniform = effect.getUniform(samplers[index]);
  11099. this._gl.uniform1i(uniform, index);
  11100. }
  11101. this._currentEffect = null;
  11102. };
  11103. Engine.prototype.activateTexture = function (texture) {
  11104. if (this._activeTexture !== texture) {
  11105. this._gl.activeTexture(texture);
  11106. this._activeTexture = texture;
  11107. }
  11108. };
  11109. Engine.prototype._bindTextureDirectly = function (target, texture) {
  11110. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  11111. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11112. this._activeTexturesCache[this._activeTexture] = texture;
  11113. }
  11114. };
  11115. Engine.prototype._bindTexture = function (channel, texture) {
  11116. if (channel < 0) {
  11117. return;
  11118. }
  11119. this.activateTexture(this._gl.TEXTURE0 + channel);
  11120. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11121. };
  11122. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11123. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  11124. };
  11125. Engine.prototype.unbindAllTextures = function () {
  11126. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11127. this.activateTexture(this._gl["TEXTURE" + channel]);
  11128. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11129. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11130. }
  11131. };
  11132. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11133. if (channel < 0) {
  11134. return;
  11135. }
  11136. this._gl.uniform1i(uniform, channel);
  11137. this._setTexture(channel, texture);
  11138. };
  11139. Engine.prototype._setTexture = function (channel, texture) {
  11140. // Not ready?
  11141. if (!texture) {
  11142. if (this._activeTexturesCache[channel] != null) {
  11143. this.activateTexture(this._gl["TEXTURE" + channel]);
  11144. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11145. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11146. }
  11147. return;
  11148. }
  11149. // Video
  11150. var alreadyActivated = false;
  11151. if (texture.video) {
  11152. this.activateTexture(this._gl["TEXTURE" + channel]);
  11153. alreadyActivated = true;
  11154. texture.update();
  11155. }
  11156. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11157. texture.delayLoad();
  11158. return;
  11159. }
  11160. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  11161. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  11162. if (this._activeTexturesCache[channel] === internalTexture) {
  11163. return;
  11164. }
  11165. if (!alreadyActivated) {
  11166. this.activateTexture(this._gl["TEXTURE" + channel]);
  11167. }
  11168. if (internalTexture.isCube) {
  11169. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  11170. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11171. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11172. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11173. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11174. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11175. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11176. }
  11177. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11178. }
  11179. else {
  11180. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  11181. if (internalTexture._cachedWrapU !== texture.wrapU) {
  11182. internalTexture._cachedWrapU = texture.wrapU;
  11183. switch (texture.wrapU) {
  11184. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11185. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11186. break;
  11187. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11188. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11189. break;
  11190. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11191. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11192. break;
  11193. }
  11194. }
  11195. if (internalTexture._cachedWrapV !== texture.wrapV) {
  11196. internalTexture._cachedWrapV = texture.wrapV;
  11197. switch (texture.wrapV) {
  11198. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11199. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11200. break;
  11201. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11202. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11203. break;
  11204. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11205. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11206. break;
  11207. }
  11208. }
  11209. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11210. }
  11211. };
  11212. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11213. if (channel < 0) {
  11214. return;
  11215. }
  11216. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11217. this._textureUnits = new Int32Array(textures.length);
  11218. }
  11219. for (var i = 0; i < textures.length; i++) {
  11220. this._textureUnits[i] = channel + i;
  11221. }
  11222. this._gl.uniform1iv(uniform, this._textureUnits);
  11223. for (var index = 0; index < textures.length; index++) {
  11224. this._setTexture(channel + index, textures[index]);
  11225. }
  11226. };
  11227. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11228. var internalTexture = texture.getInternalTexture();
  11229. if (!internalTexture) {
  11230. return;
  11231. }
  11232. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11233. var value = texture.anisotropicFilteringLevel;
  11234. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11235. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11236. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11237. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11238. }
  11239. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11240. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11241. internalTexture._cachedAnisotropicFilteringLevel = value;
  11242. }
  11243. };
  11244. Engine.prototype.readPixels = function (x, y, width, height) {
  11245. var data = new Uint8Array(height * width * 4);
  11246. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11247. return data;
  11248. };
  11249. /**
  11250. * Add an externaly attached data from its key.
  11251. * This method call will fail and return false, if such key already exists.
  11252. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11253. * @param key the unique key that identifies the data
  11254. * @param data the data object to associate to the key for this Engine instance
  11255. * @return true if no such key were already present and the data was added successfully, false otherwise
  11256. */
  11257. Engine.prototype.addExternalData = function (key, data) {
  11258. if (!this._externalData) {
  11259. this._externalData = new BABYLON.StringDictionary();
  11260. }
  11261. return this._externalData.add(key, data);
  11262. };
  11263. /**
  11264. * Get an externaly attached data from its key
  11265. * @param key the unique key that identifies the data
  11266. * @return the associated data, if present (can be null), or undefined if not present
  11267. */
  11268. Engine.prototype.getExternalData = function (key) {
  11269. if (!this._externalData) {
  11270. this._externalData = new BABYLON.StringDictionary();
  11271. }
  11272. return this._externalData.get(key);
  11273. };
  11274. /**
  11275. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11276. * @param key the unique key that identifies the data
  11277. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11278. * @return the associated data, can be null if the factory returned null.
  11279. */
  11280. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11281. if (!this._externalData) {
  11282. this._externalData = new BABYLON.StringDictionary();
  11283. }
  11284. return this._externalData.getOrAddWithFactory(key, factory);
  11285. };
  11286. /**
  11287. * Remove an externaly attached data from the Engine instance
  11288. * @param key the unique key that identifies the data
  11289. * @return true if the data was successfully removed, false if it doesn't exist
  11290. */
  11291. Engine.prototype.removeExternalData = function (key) {
  11292. if (!this._externalData) {
  11293. this._externalData = new BABYLON.StringDictionary();
  11294. }
  11295. return this._externalData.remove(key);
  11296. };
  11297. Engine.prototype.unbindAllAttributes = function () {
  11298. if (this._mustWipeVertexAttributes) {
  11299. this._mustWipeVertexAttributes = false;
  11300. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11301. this._gl.disableVertexAttribArray(i);
  11302. this._vertexAttribArraysEnabled[i] = false;
  11303. this._currentBufferPointers[i].active = false;
  11304. }
  11305. return;
  11306. }
  11307. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11308. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11309. continue;
  11310. }
  11311. this._gl.disableVertexAttribArray(i);
  11312. this._vertexAttribArraysEnabled[i] = false;
  11313. this._currentBufferPointers[i].active = false;
  11314. }
  11315. };
  11316. Engine.prototype.releaseEffects = function () {
  11317. for (var name in this._compiledEffects) {
  11318. this._deleteProgram(this._compiledEffects[name]._program);
  11319. }
  11320. this._compiledEffects = {};
  11321. };
  11322. // Dispose
  11323. Engine.prototype.dispose = function () {
  11324. this.hideLoadingUI();
  11325. this.stopRenderLoop();
  11326. // Release postProcesses
  11327. while (this.postProcesses.length) {
  11328. this.postProcesses[0].dispose();
  11329. }
  11330. // Empty texture
  11331. if (this._emptyTexture) {
  11332. this._releaseTexture(this._emptyTexture);
  11333. this._emptyTexture = null;
  11334. }
  11335. if (this._emptyCubeTexture) {
  11336. this._releaseTexture(this._emptyCubeTexture);
  11337. this._emptyCubeTexture = null;
  11338. }
  11339. // Rescale PP
  11340. if (this._rescalePostProcess) {
  11341. this._rescalePostProcess.dispose();
  11342. }
  11343. // Release scenes
  11344. while (this.scenes.length) {
  11345. this.scenes[0].dispose();
  11346. }
  11347. // Release audio engine
  11348. if (Engine.audioEngine) {
  11349. Engine.audioEngine.dispose();
  11350. }
  11351. // Release effects
  11352. this.releaseEffects();
  11353. // Unbind
  11354. this.unbindAllAttributes();
  11355. if (this._dummyFramebuffer) {
  11356. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11357. }
  11358. this._gl = null;
  11359. //WebVR
  11360. this.disableVR();
  11361. // Events
  11362. window.removeEventListener("blur", this._onBlur);
  11363. window.removeEventListener("focus", this._onFocus);
  11364. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11365. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11366. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11367. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11368. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11369. if (!this._doNotHandleContextLost) {
  11370. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11371. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11372. }
  11373. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11374. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11375. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11376. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11377. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11378. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11379. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11380. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11381. if (this._onVrDisplayConnect) {
  11382. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11383. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11384. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11385. this._onVrDisplayConnect = undefined;
  11386. this._onVrDisplayDisconnect = undefined;
  11387. }
  11388. // Remove from Instances
  11389. var index = Engine.Instances.indexOf(this);
  11390. if (index >= 0) {
  11391. Engine.Instances.splice(index, 1);
  11392. }
  11393. this._workingCanvas = null;
  11394. this._workingContext = null;
  11395. this._currentBufferPointers = null;
  11396. this._renderingCanvas = null;
  11397. this._currentProgram = null;
  11398. this.onResizeObservable.clear();
  11399. this.onCanvasBlurObservable.clear();
  11400. this.onCanvasFocusObservable.clear();
  11401. this.onCanvasPointerOutObservable.clear();
  11402. BABYLON.Effect.ResetCache();
  11403. };
  11404. // Loading screen
  11405. Engine.prototype.displayLoadingUI = function () {
  11406. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11407. return;
  11408. }
  11409. var loadingScreen = this.loadingScreen;
  11410. if (loadingScreen) {
  11411. loadingScreen.displayLoadingUI();
  11412. }
  11413. };
  11414. Engine.prototype.hideLoadingUI = function () {
  11415. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11416. return;
  11417. }
  11418. var loadingScreen = this.loadingScreen;
  11419. if (loadingScreen) {
  11420. loadingScreen.hideLoadingUI();
  11421. }
  11422. };
  11423. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11424. get: function () {
  11425. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  11426. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11427. return this._loadingScreen;
  11428. },
  11429. set: function (loadingScreen) {
  11430. this._loadingScreen = loadingScreen;
  11431. },
  11432. enumerable: true,
  11433. configurable: true
  11434. });
  11435. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11436. set: function (text) {
  11437. this.loadingScreen.loadingUIText = text;
  11438. },
  11439. enumerable: true,
  11440. configurable: true
  11441. });
  11442. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11443. set: function (color) {
  11444. this.loadingScreen.loadingUIBackgroundColor = color;
  11445. },
  11446. enumerable: true,
  11447. configurable: true
  11448. });
  11449. Engine.prototype.attachContextLostEvent = function (callback) {
  11450. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11451. };
  11452. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11453. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11454. };
  11455. Engine.prototype.getVertexShaderSource = function (program) {
  11456. var shaders = this._gl.getAttachedShaders(program);
  11457. return this._gl.getShaderSource(shaders[0]);
  11458. };
  11459. Engine.prototype.getFragmentShaderSource = function (program) {
  11460. var shaders = this._gl.getAttachedShaders(program);
  11461. return this._gl.getShaderSource(shaders[1]);
  11462. };
  11463. Engine.prototype.getError = function () {
  11464. return this._gl.getError();
  11465. };
  11466. // FPS
  11467. Engine.prototype.getFps = function () {
  11468. return this._fps;
  11469. };
  11470. Engine.prototype.getDeltaTime = function () {
  11471. return this._deltaTime;
  11472. };
  11473. Engine.prototype._measureFps = function () {
  11474. this._performanceMonitor.sampleFrame();
  11475. this._fps = this._performanceMonitor.averageFPS;
  11476. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11477. };
  11478. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11479. if (faceIndex === void 0) { faceIndex = -1; }
  11480. var gl = this._gl;
  11481. if (!this._dummyFramebuffer) {
  11482. this._dummyFramebuffer = gl.createFramebuffer();
  11483. }
  11484. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11485. if (faceIndex > -1) {
  11486. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11487. }
  11488. else {
  11489. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11490. }
  11491. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11492. var buffer;
  11493. switch (readType) {
  11494. case gl.UNSIGNED_BYTE:
  11495. buffer = new Uint8Array(4 * width * height);
  11496. readType = gl.UNSIGNED_BYTE;
  11497. break;
  11498. default:
  11499. buffer = new Float32Array(4 * width * height);
  11500. readType = gl.FLOAT;
  11501. break;
  11502. }
  11503. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11504. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11505. return buffer;
  11506. };
  11507. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11508. if (this._webGLVersion > 1) {
  11509. return this._caps.colorBufferFloat;
  11510. }
  11511. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11512. };
  11513. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11514. if (this._webGLVersion > 1) {
  11515. return this._caps.colorBufferFloat;
  11516. }
  11517. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11518. };
  11519. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11520. Engine.prototype._canRenderToFramebuffer = function (type) {
  11521. var gl = this._gl;
  11522. //clear existing errors
  11523. while (gl.getError() !== gl.NO_ERROR) { }
  11524. var successful = true;
  11525. var texture = gl.createTexture();
  11526. gl.bindTexture(gl.TEXTURE_2D, texture);
  11527. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11528. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11529. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11530. var fb = gl.createFramebuffer();
  11531. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11532. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11533. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11534. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11535. successful = successful && (gl.getError() === gl.NO_ERROR);
  11536. //try render by clearing frame buffer's color buffer
  11537. if (successful) {
  11538. gl.clear(gl.COLOR_BUFFER_BIT);
  11539. successful = successful && (gl.getError() === gl.NO_ERROR);
  11540. }
  11541. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11542. if (successful) {
  11543. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11544. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11545. var readFormat = gl.RGBA;
  11546. var readType = gl.UNSIGNED_BYTE;
  11547. var buffer = new Uint8Array(4);
  11548. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11549. successful = successful && (gl.getError() === gl.NO_ERROR);
  11550. }
  11551. //clean up
  11552. gl.deleteTexture(texture);
  11553. gl.deleteFramebuffer(fb);
  11554. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11555. //clear accumulated errors
  11556. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11557. return successful;
  11558. };
  11559. Engine.prototype._getWebGLTextureType = function (type) {
  11560. if (type === Engine.TEXTURETYPE_FLOAT) {
  11561. return this._gl.FLOAT;
  11562. }
  11563. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11564. // Add Half Float Constant.
  11565. return this._gl.HALF_FLOAT_OES;
  11566. }
  11567. return this._gl.UNSIGNED_BYTE;
  11568. };
  11569. ;
  11570. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11571. if (this._webGLVersion === 1) {
  11572. return this._gl.RGBA;
  11573. }
  11574. if (type === Engine.TEXTURETYPE_FLOAT) {
  11575. return this._gl.RGBA32F;
  11576. }
  11577. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11578. return this._gl.RGBA16F;
  11579. }
  11580. return this._gl.RGBA;
  11581. };
  11582. ;
  11583. Engine.prototype.createQuery = function () {
  11584. return this._gl.createQuery();
  11585. };
  11586. Engine.prototype.deleteQuery = function (query) {
  11587. this._gl.deleteQuery(query);
  11588. return this;
  11589. };
  11590. Engine.prototype.isQueryResultAvailable = function (query) {
  11591. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11592. };
  11593. Engine.prototype.getQueryResult = function (query) {
  11594. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11595. };
  11596. Engine.prototype.beginQuery = function (algorithmType, query) {
  11597. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11598. this._gl.beginQuery(glAlgorithm, query);
  11599. };
  11600. Engine.prototype.endQuery = function (algorithmType) {
  11601. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11602. this._gl.endQuery(glAlgorithm);
  11603. return this;
  11604. };
  11605. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  11606. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  11607. };
  11608. // Statics
  11609. Engine.isSupported = function () {
  11610. try {
  11611. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  11612. if (navigator.isCocoonJS) {
  11613. return true;
  11614. }
  11615. var tempcanvas = document.createElement("canvas");
  11616. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  11617. return gl != null && !!window.WebGLRenderingContext;
  11618. }
  11619. catch (e) {
  11620. return false;
  11621. }
  11622. };
  11623. Engine.Instances = new Array();
  11624. // Const statics
  11625. Engine._ALPHA_DISABLE = 0;
  11626. Engine._ALPHA_ADD = 1;
  11627. Engine._ALPHA_COMBINE = 2;
  11628. Engine._ALPHA_SUBTRACT = 3;
  11629. Engine._ALPHA_MULTIPLY = 4;
  11630. Engine._ALPHA_MAXIMIZED = 5;
  11631. Engine._ALPHA_ONEONE = 6;
  11632. Engine._ALPHA_PREMULTIPLIED = 7;
  11633. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  11634. Engine._ALPHA_INTERPOLATE = 9;
  11635. Engine._ALPHA_SCREENMODE = 10;
  11636. Engine._DELAYLOADSTATE_NONE = 0;
  11637. Engine._DELAYLOADSTATE_LOADED = 1;
  11638. Engine._DELAYLOADSTATE_LOADING = 2;
  11639. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  11640. Engine._TEXTUREFORMAT_ALPHA = 0;
  11641. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  11642. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  11643. Engine._TEXTUREFORMAT_RGB = 4;
  11644. Engine._TEXTUREFORMAT_RGBA = 5;
  11645. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  11646. Engine._TEXTURETYPE_FLOAT = 1;
  11647. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  11648. // Depht or Stencil test Constants.
  11649. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  11650. 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.
  11651. 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.
  11652. 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.
  11653. 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.
  11654. 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.
  11655. 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.
  11656. 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.
  11657. // Stencil Actions Constants.
  11658. Engine._KEEP = 0x1E00;
  11659. Engine._REPLACE = 0x1E01;
  11660. Engine._INCR = 0x1E02;
  11661. Engine._DECR = 0x1E03;
  11662. Engine._INVERT = 0x150A;
  11663. Engine._INCR_WRAP = 0x8507;
  11664. Engine._DECR_WRAP = 0x8508;
  11665. // Texture rescaling mode
  11666. Engine._SCALEMODE_FLOOR = 1;
  11667. Engine._SCALEMODE_NEAREST = 2;
  11668. Engine._SCALEMODE_CEILING = 3;
  11669. // Updatable statics so stick with vars here
  11670. Engine.CollisionsEpsilon = 0.001;
  11671. Engine.CodeRepository = "src/";
  11672. Engine.ShadersRepository = "src/Shaders/";
  11673. return Engine;
  11674. }());
  11675. BABYLON.Engine = Engine;
  11676. })(BABYLON || (BABYLON = {}));
  11677. //# sourceMappingURL=babylon.engine.js.map
  11678. /// <reference path="Tools\babylon.decorators.ts" />
  11679. var BABYLON;
  11680. (function (BABYLON) {
  11681. /**
  11682. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11683. */
  11684. var Node = (function () {
  11685. /**
  11686. * @constructor
  11687. * @param {string} name - the name and id to be given to this node
  11688. * @param {BABYLON.Scene} the scene this node will be added to
  11689. */
  11690. function Node(name, scene) {
  11691. this.state = "";
  11692. this.metadata = null;
  11693. this.doNotSerialize = false;
  11694. this.animations = new Array();
  11695. this._ranges = {};
  11696. this._isEnabled = true;
  11697. this._isReady = true;
  11698. this._currentRenderId = -1;
  11699. this._parentRenderId = -1;
  11700. /**
  11701. * An event triggered when the mesh is disposed.
  11702. * @type {BABYLON.Observable}
  11703. */
  11704. this.onDisposeObservable = new BABYLON.Observable();
  11705. // Behaviors
  11706. this._behaviors = new Array();
  11707. this.name = name;
  11708. this.id = name;
  11709. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11710. this.uniqueId = this._scene.getUniqueId();
  11711. this._initCache();
  11712. }
  11713. Object.defineProperty(Node.prototype, "parent", {
  11714. get: function () {
  11715. return this._parentNode;
  11716. },
  11717. set: function (parent) {
  11718. if (this._parentNode === parent) {
  11719. return;
  11720. }
  11721. if (this._parentNode) {
  11722. var index = this._parentNode._children.indexOf(this);
  11723. if (index !== -1) {
  11724. this._parentNode._children.splice(index, 1);
  11725. }
  11726. }
  11727. this._parentNode = parent;
  11728. if (this._parentNode) {
  11729. if (!this._parentNode._children) {
  11730. this._parentNode._children = new Array();
  11731. }
  11732. this._parentNode._children.push(this);
  11733. }
  11734. },
  11735. enumerable: true,
  11736. configurable: true
  11737. });
  11738. Node.prototype.getClassName = function () {
  11739. return "Node";
  11740. };
  11741. Object.defineProperty(Node.prototype, "onDispose", {
  11742. set: function (callback) {
  11743. if (this._onDisposeObserver) {
  11744. this.onDisposeObservable.remove(this._onDisposeObserver);
  11745. }
  11746. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11747. },
  11748. enumerable: true,
  11749. configurable: true
  11750. });
  11751. Node.prototype.getScene = function () {
  11752. return this._scene;
  11753. };
  11754. Node.prototype.getEngine = function () {
  11755. return this._scene.getEngine();
  11756. };
  11757. Node.prototype.addBehavior = function (behavior) {
  11758. var index = this._behaviors.indexOf(behavior);
  11759. if (index !== -1) {
  11760. return this;
  11761. }
  11762. behavior.attach(this);
  11763. this._behaviors.push(behavior);
  11764. return this;
  11765. };
  11766. Node.prototype.removeBehavior = function (behavior) {
  11767. var index = this._behaviors.indexOf(behavior);
  11768. if (index === -1) {
  11769. return this;
  11770. }
  11771. this._behaviors[index].detach();
  11772. this._behaviors.splice(index, 1);
  11773. return this;
  11774. };
  11775. Object.defineProperty(Node.prototype, "behaviors", {
  11776. get: function () {
  11777. return this._behaviors;
  11778. },
  11779. enumerable: true,
  11780. configurable: true
  11781. });
  11782. Node.prototype.getBehaviorByName = function (name) {
  11783. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11784. var behavior = _a[_i];
  11785. if (behavior.name === name) {
  11786. return behavior;
  11787. }
  11788. }
  11789. return null;
  11790. };
  11791. // override it in derived class
  11792. Node.prototype.getWorldMatrix = function () {
  11793. return BABYLON.Matrix.Identity();
  11794. };
  11795. // override it in derived class if you add new variables to the cache
  11796. // and call the parent class method
  11797. Node.prototype._initCache = function () {
  11798. this._cache = {};
  11799. this._cache.parent = undefined;
  11800. };
  11801. Node.prototype.updateCache = function (force) {
  11802. if (!force && this.isSynchronized())
  11803. return;
  11804. this._cache.parent = this.parent;
  11805. this._updateCache();
  11806. };
  11807. // override it in derived class if you add new variables to the cache
  11808. // and call the parent class method if !ignoreParentClass
  11809. Node.prototype._updateCache = function (ignoreParentClass) {
  11810. };
  11811. // override it in derived class if you add new variables to the cache
  11812. Node.prototype._isSynchronized = function () {
  11813. return true;
  11814. };
  11815. Node.prototype._markSyncedWithParent = function () {
  11816. this._parentRenderId = this.parent._currentRenderId;
  11817. };
  11818. Node.prototype.isSynchronizedWithParent = function () {
  11819. if (!this.parent) {
  11820. return true;
  11821. }
  11822. if (this._parentRenderId !== this.parent._currentRenderId) {
  11823. return false;
  11824. }
  11825. return this.parent.isSynchronized();
  11826. };
  11827. Node.prototype.isSynchronized = function (updateCache) {
  11828. var check = this.hasNewParent();
  11829. check = check || !this.isSynchronizedWithParent();
  11830. check = check || !this._isSynchronized();
  11831. if (updateCache)
  11832. this.updateCache(true);
  11833. return !check;
  11834. };
  11835. Node.prototype.hasNewParent = function (update) {
  11836. if (this._cache.parent === this.parent)
  11837. return false;
  11838. if (update)
  11839. this._cache.parent = this.parent;
  11840. return true;
  11841. };
  11842. /**
  11843. * Is this node ready to be used/rendered
  11844. * @return {boolean} is it ready
  11845. */
  11846. Node.prototype.isReady = function () {
  11847. return this._isReady;
  11848. };
  11849. /**
  11850. * Is this node enabled.
  11851. * If the node has a parent and is enabled, the parent will be inspected as well.
  11852. * @return {boolean} whether this node (and its parent) is enabled.
  11853. * @see setEnabled
  11854. */
  11855. Node.prototype.isEnabled = function () {
  11856. if (!this._isEnabled) {
  11857. return false;
  11858. }
  11859. if (this.parent) {
  11860. return this.parent.isEnabled();
  11861. }
  11862. return true;
  11863. };
  11864. /**
  11865. * Set the enabled state of this node.
  11866. * @param {boolean} value - the new enabled state
  11867. * @see isEnabled
  11868. */
  11869. Node.prototype.setEnabled = function (value) {
  11870. this._isEnabled = value;
  11871. };
  11872. /**
  11873. * Is this node a descendant of the given node.
  11874. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11875. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11876. * @see parent
  11877. */
  11878. Node.prototype.isDescendantOf = function (ancestor) {
  11879. if (this.parent) {
  11880. if (this.parent === ancestor) {
  11881. return true;
  11882. }
  11883. return this.parent.isDescendantOf(ancestor);
  11884. }
  11885. return false;
  11886. };
  11887. /**
  11888. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11889. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11890. * @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.
  11891. * @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.
  11892. */
  11893. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11894. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11895. if (!this._children) {
  11896. return;
  11897. }
  11898. for (var index = 0; index < this._children.length; index++) {
  11899. var item = this._children[index];
  11900. if (!predicate || predicate(item)) {
  11901. results.push(item);
  11902. }
  11903. if (!directDescendantsOnly) {
  11904. item._getDescendants(results, false, predicate);
  11905. }
  11906. }
  11907. };
  11908. /**
  11909. * Will return all nodes that have this node as ascendant.
  11910. * @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.
  11911. * @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.
  11912. * @return {BABYLON.Node[]} all children nodes of all types.
  11913. */
  11914. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11915. var results = new Array();
  11916. this._getDescendants(results, directDescendantsOnly, predicate);
  11917. return results;
  11918. };
  11919. /**
  11920. * Get all child-meshes of this node.
  11921. */
  11922. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11923. var results = [];
  11924. this._getDescendants(results, directDecendantsOnly, function (node) {
  11925. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11926. });
  11927. return results;
  11928. };
  11929. /**
  11930. * Get all direct children of this node.
  11931. */
  11932. Node.prototype.getChildren = function (predicate) {
  11933. return this.getDescendants(true, predicate);
  11934. };
  11935. Node.prototype._setReady = function (state) {
  11936. if (state === this._isReady) {
  11937. return;
  11938. }
  11939. if (!state) {
  11940. this._isReady = false;
  11941. return;
  11942. }
  11943. this._isReady = true;
  11944. if (this.onReady) {
  11945. this.onReady(this);
  11946. }
  11947. };
  11948. Node.prototype.getAnimationByName = function (name) {
  11949. for (var i = 0; i < this.animations.length; i++) {
  11950. var animation = this.animations[i];
  11951. if (animation.name === name) {
  11952. return animation;
  11953. }
  11954. }
  11955. return null;
  11956. };
  11957. Node.prototype.createAnimationRange = function (name, from, to) {
  11958. // check name not already in use
  11959. if (!this._ranges[name]) {
  11960. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11961. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11962. if (this.animations[i]) {
  11963. this.animations[i].createRange(name, from, to);
  11964. }
  11965. }
  11966. }
  11967. };
  11968. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11969. if (deleteFrames === void 0) { deleteFrames = true; }
  11970. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11971. if (this.animations[i]) {
  11972. this.animations[i].deleteRange(name, deleteFrames);
  11973. }
  11974. }
  11975. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11976. };
  11977. Node.prototype.getAnimationRange = function (name) {
  11978. return this._ranges[name];
  11979. };
  11980. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11981. var range = this.getAnimationRange(name);
  11982. if (!range) {
  11983. return null;
  11984. }
  11985. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11986. };
  11987. Node.prototype.serializeAnimationRanges = function () {
  11988. var serializationRanges = [];
  11989. for (var name in this._ranges) {
  11990. var range = {};
  11991. range.name = name;
  11992. range.from = this._ranges[name].from;
  11993. range.to = this._ranges[name].to;
  11994. serializationRanges.push(range);
  11995. }
  11996. return serializationRanges;
  11997. };
  11998. Node.prototype.dispose = function () {
  11999. this.parent = null;
  12000. // Callback
  12001. this.onDisposeObservable.notifyObservers(this);
  12002. this.onDisposeObservable.clear();
  12003. // Behaviors
  12004. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12005. var behavior = _a[_i];
  12006. behavior.detach();
  12007. }
  12008. this._behaviors = [];
  12009. };
  12010. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  12011. if (parsedNode.ranges) {
  12012. for (var index = 0; index < parsedNode.ranges.length; index++) {
  12013. var data = parsedNode.ranges[index];
  12014. node.createAnimationRange(data.name, data.from, data.to);
  12015. }
  12016. }
  12017. };
  12018. __decorate([
  12019. BABYLON.serialize()
  12020. ], Node.prototype, "name", void 0);
  12021. __decorate([
  12022. BABYLON.serialize()
  12023. ], Node.prototype, "id", void 0);
  12024. __decorate([
  12025. BABYLON.serialize()
  12026. ], Node.prototype, "uniqueId", void 0);
  12027. __decorate([
  12028. BABYLON.serialize()
  12029. ], Node.prototype, "state", void 0);
  12030. __decorate([
  12031. BABYLON.serialize()
  12032. ], Node.prototype, "metadata", void 0);
  12033. return Node;
  12034. }());
  12035. BABYLON.Node = Node;
  12036. })(BABYLON || (BABYLON = {}));
  12037. //# sourceMappingURL=babylon.node.js.map
  12038. var BABYLON;
  12039. (function (BABYLON) {
  12040. var BoundingSphere = (function () {
  12041. function BoundingSphere(minimum, maximum) {
  12042. this.minimum = minimum;
  12043. this.maximum = maximum;
  12044. this._tempRadiusVector = BABYLON.Vector3.Zero();
  12045. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  12046. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  12047. this.radius = distance * 0.5;
  12048. this.centerWorld = BABYLON.Vector3.Zero();
  12049. this._update(BABYLON.Matrix.Identity());
  12050. }
  12051. // Methods
  12052. BoundingSphere.prototype._update = function (world) {
  12053. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  12054. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  12055. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  12056. };
  12057. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  12058. for (var i = 0; i < 6; i++) {
  12059. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  12060. return false;
  12061. }
  12062. return true;
  12063. };
  12064. BoundingSphere.prototype.intersectsPoint = function (point) {
  12065. var x = this.centerWorld.x - point.x;
  12066. var y = this.centerWorld.y - point.y;
  12067. var z = this.centerWorld.z - point.z;
  12068. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12069. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  12070. return false;
  12071. return true;
  12072. };
  12073. // Statics
  12074. BoundingSphere.Intersects = function (sphere0, sphere1) {
  12075. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  12076. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  12077. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  12078. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12079. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  12080. return false;
  12081. return true;
  12082. };
  12083. return BoundingSphere;
  12084. }());
  12085. BABYLON.BoundingSphere = BoundingSphere;
  12086. })(BABYLON || (BABYLON = {}));
  12087. //# sourceMappingURL=babylon.boundingSphere.js.map
  12088. var BABYLON;
  12089. (function (BABYLON) {
  12090. var BoundingBox = (function () {
  12091. function BoundingBox(minimum, maximum) {
  12092. this.minimum = minimum;
  12093. this.maximum = maximum;
  12094. this.vectors = new Array();
  12095. this.vectorsWorld = new Array();
  12096. // Bounding vectors
  12097. this.vectors.push(this.minimum.clone());
  12098. this.vectors.push(this.maximum.clone());
  12099. this.vectors.push(this.minimum.clone());
  12100. this.vectors[2].x = this.maximum.x;
  12101. this.vectors.push(this.minimum.clone());
  12102. this.vectors[3].y = this.maximum.y;
  12103. this.vectors.push(this.minimum.clone());
  12104. this.vectors[4].z = this.maximum.z;
  12105. this.vectors.push(this.maximum.clone());
  12106. this.vectors[5].z = this.minimum.z;
  12107. this.vectors.push(this.maximum.clone());
  12108. this.vectors[6].x = this.minimum.x;
  12109. this.vectors.push(this.maximum.clone());
  12110. this.vectors[7].y = this.minimum.y;
  12111. // OBB
  12112. this.center = this.maximum.add(this.minimum).scale(0.5);
  12113. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12114. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12115. // World
  12116. for (var index = 0; index < this.vectors.length; index++) {
  12117. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12118. }
  12119. this.minimumWorld = BABYLON.Vector3.Zero();
  12120. this.maximumWorld = BABYLON.Vector3.Zero();
  12121. this.centerWorld = BABYLON.Vector3.Zero();
  12122. this.extendSizeWorld = BABYLON.Vector3.Zero();
  12123. this._update(BABYLON.Matrix.Identity());
  12124. }
  12125. // Methods
  12126. BoundingBox.prototype.getWorldMatrix = function () {
  12127. return this._worldMatrix;
  12128. };
  12129. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  12130. this._worldMatrix.copyFrom(matrix);
  12131. return this;
  12132. };
  12133. BoundingBox.prototype._update = function (world) {
  12134. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  12135. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  12136. for (var index = 0; index < this.vectors.length; index++) {
  12137. var v = this.vectorsWorld[index];
  12138. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  12139. if (v.x < this.minimumWorld.x)
  12140. this.minimumWorld.x = v.x;
  12141. if (v.y < this.minimumWorld.y)
  12142. this.minimumWorld.y = v.y;
  12143. if (v.z < this.minimumWorld.z)
  12144. this.minimumWorld.z = v.z;
  12145. if (v.x > this.maximumWorld.x)
  12146. this.maximumWorld.x = v.x;
  12147. if (v.y > this.maximumWorld.y)
  12148. this.maximumWorld.y = v.y;
  12149. if (v.z > this.maximumWorld.z)
  12150. this.maximumWorld.z = v.z;
  12151. }
  12152. // Extend
  12153. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  12154. this.extendSizeWorld.scaleInPlace(0.5);
  12155. // OBB
  12156. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  12157. this.centerWorld.scaleInPlace(0.5);
  12158. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  12159. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  12160. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  12161. this._worldMatrix = world;
  12162. };
  12163. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  12164. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  12165. };
  12166. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12167. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  12168. };
  12169. BoundingBox.prototype.intersectsPoint = function (point) {
  12170. var delta = -BABYLON.Epsilon;
  12171. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  12172. return false;
  12173. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  12174. return false;
  12175. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  12176. return false;
  12177. return true;
  12178. };
  12179. BoundingBox.prototype.intersectsSphere = function (sphere) {
  12180. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  12181. };
  12182. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  12183. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  12184. return false;
  12185. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  12186. return false;
  12187. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  12188. return false;
  12189. return true;
  12190. };
  12191. // Statics
  12192. BoundingBox.Intersects = function (box0, box1) {
  12193. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  12194. return false;
  12195. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  12196. return false;
  12197. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  12198. return false;
  12199. return true;
  12200. };
  12201. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  12202. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  12203. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  12204. return (num <= (sphereRadius * sphereRadius));
  12205. };
  12206. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  12207. for (var p = 0; p < 6; p++) {
  12208. for (var i = 0; i < 8; i++) {
  12209. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12210. return false;
  12211. }
  12212. }
  12213. }
  12214. return true;
  12215. };
  12216. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  12217. for (var p = 0; p < 6; p++) {
  12218. var inCount = 8;
  12219. for (var i = 0; i < 8; i++) {
  12220. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12221. --inCount;
  12222. }
  12223. else {
  12224. break;
  12225. }
  12226. }
  12227. if (inCount === 0)
  12228. return false;
  12229. }
  12230. return true;
  12231. };
  12232. return BoundingBox;
  12233. }());
  12234. BABYLON.BoundingBox = BoundingBox;
  12235. })(BABYLON || (BABYLON = {}));
  12236. //# sourceMappingURL=babylon.boundingBox.js.map
  12237. var BABYLON;
  12238. (function (BABYLON) {
  12239. var computeBoxExtents = function (axis, box) {
  12240. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  12241. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  12242. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12243. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12244. var r = r0 + r1 + r2;
  12245. return {
  12246. min: p - r,
  12247. max: p + r
  12248. };
  12249. };
  12250. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12251. var axisOverlap = function (axis, box0, box1) {
  12252. var result0 = computeBoxExtents(axis, box0);
  12253. var result1 = computeBoxExtents(axis, box1);
  12254. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12255. };
  12256. var BoundingInfo = (function () {
  12257. function BoundingInfo(minimum, maximum) {
  12258. this.minimum = minimum;
  12259. this.maximum = maximum;
  12260. this._isLocked = false;
  12261. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12262. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12263. }
  12264. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12265. get: function () {
  12266. return this._isLocked;
  12267. },
  12268. set: function (value) {
  12269. this._isLocked = value;
  12270. },
  12271. enumerable: true,
  12272. configurable: true
  12273. });
  12274. // Methods
  12275. BoundingInfo.prototype.update = function (world) {
  12276. if (this._isLocked) {
  12277. return;
  12278. }
  12279. this.boundingBox._update(world);
  12280. this.boundingSphere._update(world);
  12281. };
  12282. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12283. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12284. return false;
  12285. return this.boundingBox.isInFrustum(frustumPlanes);
  12286. };
  12287. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12288. /**
  12289. * Gets the world distance between the min and max points of the bounding box
  12290. */
  12291. get: function () {
  12292. var boundingBox = this.boundingBox;
  12293. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12294. return size.length();
  12295. },
  12296. enumerable: true,
  12297. configurable: true
  12298. });
  12299. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12300. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12301. };
  12302. BoundingInfo.prototype._checkCollision = function (collider) {
  12303. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12304. };
  12305. BoundingInfo.prototype.intersectsPoint = function (point) {
  12306. if (!this.boundingSphere.centerWorld) {
  12307. return false;
  12308. }
  12309. if (!this.boundingSphere.intersectsPoint(point)) {
  12310. return false;
  12311. }
  12312. if (!this.boundingBox.intersectsPoint(point)) {
  12313. return false;
  12314. }
  12315. return true;
  12316. };
  12317. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12318. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12319. return false;
  12320. }
  12321. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12322. return false;
  12323. }
  12324. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12325. return false;
  12326. }
  12327. if (!precise) {
  12328. return true;
  12329. }
  12330. var box0 = this.boundingBox;
  12331. var box1 = boundingInfo.boundingBox;
  12332. if (!axisOverlap(box0.directions[0], box0, box1))
  12333. return false;
  12334. if (!axisOverlap(box0.directions[1], box0, box1))
  12335. return false;
  12336. if (!axisOverlap(box0.directions[2], box0, box1))
  12337. return false;
  12338. if (!axisOverlap(box1.directions[0], box0, box1))
  12339. return false;
  12340. if (!axisOverlap(box1.directions[1], box0, box1))
  12341. return false;
  12342. if (!axisOverlap(box1.directions[2], box0, box1))
  12343. return false;
  12344. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12345. return false;
  12346. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12347. return false;
  12348. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12349. return false;
  12350. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12351. return false;
  12352. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12353. return false;
  12354. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12355. return false;
  12356. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12357. return false;
  12358. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12359. return false;
  12360. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12361. return false;
  12362. return true;
  12363. };
  12364. return BoundingInfo;
  12365. }());
  12366. BABYLON.BoundingInfo = BoundingInfo;
  12367. })(BABYLON || (BABYLON = {}));
  12368. //# sourceMappingURL=babylon.boundingInfo.js.map
  12369. var BABYLON;
  12370. (function (BABYLON) {
  12371. var AbstractMesh = (function (_super) {
  12372. __extends(AbstractMesh, _super);
  12373. // Constructor
  12374. function AbstractMesh(name, scene) {
  12375. var _this = _super.call(this, name, scene) || this;
  12376. _this._facetNb = 0; // facet number
  12377. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12378. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12379. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12380. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12381. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12382. _this._subDiv = {
  12383. max: 1,
  12384. X: 1,
  12385. Y: 1,
  12386. Z: 1
  12387. };
  12388. // Events
  12389. /**
  12390. * An event triggered when this mesh collides with another one
  12391. * @type {BABYLON.Observable}
  12392. */
  12393. _this.onCollideObservable = new BABYLON.Observable();
  12394. /**
  12395. * An event triggered when the collision's position changes
  12396. * @type {BABYLON.Observable}
  12397. */
  12398. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12399. /**
  12400. * An event triggered after the world matrix is updated
  12401. * @type {BABYLON.Observable}
  12402. */
  12403. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12404. /**
  12405. * An event triggered when material is changed
  12406. * @type {BABYLON.Observable}
  12407. */
  12408. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12409. // Properties
  12410. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12411. _this.position = BABYLON.Vector3.Zero();
  12412. /**
  12413. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12414. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12415. * or
  12416. * 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.
  12417. * for more info check WebGl documentations
  12418. */
  12419. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12420. /**
  12421. * 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:
  12422. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12423. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12424. * 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.
  12425. */
  12426. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12427. /**
  12428. * 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.
  12429. * The default value is -1 which means don't break the query and wait till the result.
  12430. */
  12431. _this.occlusionRetryCount = -1;
  12432. _this._occlusionInternalRetryCounter = 0;
  12433. _this._isOccluded = false;
  12434. _this._isOcclusionQueryInProgress = false;
  12435. _this._rotation = BABYLON.Vector3.Zero();
  12436. _this._scaling = BABYLON.Vector3.One();
  12437. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12438. _this.visibility = 1.0;
  12439. _this.alphaIndex = Number.MAX_VALUE;
  12440. _this.infiniteDistance = false;
  12441. _this.isVisible = true;
  12442. _this.isPickable = true;
  12443. _this.showBoundingBox = false;
  12444. _this.showSubMeshesBoundingBox = false;
  12445. _this.isBlocker = false;
  12446. _this.enablePointerMoveEvents = false;
  12447. _this.renderingGroupId = 0;
  12448. _this._receiveShadows = false;
  12449. _this.renderOutline = false;
  12450. _this.outlineColor = BABYLON.Color3.Red();
  12451. _this.outlineWidth = 0.02;
  12452. _this.renderOverlay = false;
  12453. _this.overlayColor = BABYLON.Color3.Red();
  12454. _this.overlayAlpha = 0.5;
  12455. _this._hasVertexAlpha = false;
  12456. _this._useVertexColors = true;
  12457. _this._computeBonesUsingShaders = true;
  12458. _this._numBoneInfluencers = 4;
  12459. _this._applyFog = true;
  12460. _this.scalingDeterminant = 1;
  12461. _this.useOctreeForRenderingSelection = true;
  12462. _this.useOctreeForPicking = true;
  12463. _this.useOctreeForCollisions = true;
  12464. _this._layerMask = 0x0FFFFFFF;
  12465. /**
  12466. * True if the mesh must be rendered in any case.
  12467. */
  12468. _this.alwaysSelectAsActiveMesh = false;
  12469. // Collisions
  12470. _this._checkCollisions = false;
  12471. _this._collisionMask = -1;
  12472. _this._collisionGroup = -1;
  12473. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12474. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12475. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12476. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12477. // Edges
  12478. _this.edgesWidth = 1;
  12479. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12480. // Cache
  12481. _this._localWorld = BABYLON.Matrix.Zero();
  12482. _this._worldMatrix = BABYLON.Matrix.Zero();
  12483. _this._absolutePosition = BABYLON.Vector3.Zero();
  12484. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12485. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12486. _this._isDirty = false;
  12487. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12488. _this._postMultiplyPivotMatrix = false;
  12489. _this._isDisposed = false;
  12490. _this._renderId = 0;
  12491. _this._intersectionsInProgress = new Array();
  12492. _this._isWorldMatrixFrozen = false;
  12493. _this._unIndexed = false;
  12494. _this._lightSources = new Array();
  12495. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12496. if (collidedMesh === void 0) { collidedMesh = null; }
  12497. //TODO move this to the collision coordinator!
  12498. if (_this.getScene().workerCollisions)
  12499. newPosition.multiplyInPlace(_this._collider.radius);
  12500. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12501. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12502. _this.position.addInPlace(_this._diffPositionForCollisions);
  12503. }
  12504. if (collidedMesh) {
  12505. _this.onCollideObservable.notifyObservers(collidedMesh);
  12506. }
  12507. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12508. };
  12509. _this.getScene().addMesh(_this);
  12510. _this._resyncLightSources();
  12511. return _this;
  12512. }
  12513. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12514. get: function () {
  12515. return AbstractMesh._BILLBOARDMODE_NONE;
  12516. },
  12517. enumerable: true,
  12518. configurable: true
  12519. });
  12520. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12521. get: function () {
  12522. return AbstractMesh._BILLBOARDMODE_X;
  12523. },
  12524. enumerable: true,
  12525. configurable: true
  12526. });
  12527. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12528. get: function () {
  12529. return AbstractMesh._BILLBOARDMODE_Y;
  12530. },
  12531. enumerable: true,
  12532. configurable: true
  12533. });
  12534. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12535. get: function () {
  12536. return AbstractMesh._BILLBOARDMODE_Z;
  12537. },
  12538. enumerable: true,
  12539. configurable: true
  12540. });
  12541. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12542. get: function () {
  12543. return AbstractMesh._BILLBOARDMODE_ALL;
  12544. },
  12545. enumerable: true,
  12546. configurable: true
  12547. });
  12548. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12549. /**
  12550. * Read-only : the number of facets in the mesh
  12551. */
  12552. get: function () {
  12553. return this._facetNb;
  12554. },
  12555. enumerable: true,
  12556. configurable: true
  12557. });
  12558. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12559. /**
  12560. * The number (integer) of subdivisions per axis in the partioning space
  12561. */
  12562. get: function () {
  12563. return this._partitioningSubdivisions;
  12564. },
  12565. set: function (nb) {
  12566. this._partitioningSubdivisions = nb;
  12567. },
  12568. enumerable: true,
  12569. configurable: true
  12570. });
  12571. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12572. /**
  12573. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12574. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12575. */
  12576. get: function () {
  12577. return this._partitioningBBoxRatio;
  12578. },
  12579. set: function (ratio) {
  12580. this._partitioningBBoxRatio = ratio;
  12581. },
  12582. enumerable: true,
  12583. configurable: true
  12584. });
  12585. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12586. /**
  12587. * Read-only boolean : is the feature facetData enabled ?
  12588. */
  12589. get: function () {
  12590. return this._facetDataEnabled;
  12591. },
  12592. enumerable: true,
  12593. configurable: true
  12594. });
  12595. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12596. set: function (callback) {
  12597. if (this._onCollideObserver) {
  12598. this.onCollideObservable.remove(this._onCollideObserver);
  12599. }
  12600. this._onCollideObserver = this.onCollideObservable.add(callback);
  12601. },
  12602. enumerable: true,
  12603. configurable: true
  12604. });
  12605. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12606. set: function (callback) {
  12607. if (this._onCollisionPositionChangeObserver) {
  12608. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12609. }
  12610. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12611. },
  12612. enumerable: true,
  12613. configurable: true
  12614. });
  12615. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  12616. /**
  12617. * 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.
  12618. */
  12619. get: function () {
  12620. return this._isOccluded;
  12621. },
  12622. set: function (value) {
  12623. this._isOccluded = value;
  12624. },
  12625. enumerable: true,
  12626. configurable: true
  12627. });
  12628. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  12629. /**
  12630. * Flag to check the progress status of the query
  12631. */
  12632. get: function () {
  12633. return this._isOcclusionQueryInProgress;
  12634. },
  12635. enumerable: true,
  12636. configurable: true
  12637. });
  12638. Object.defineProperty(AbstractMesh.prototype, "material", {
  12639. get: function () {
  12640. return this._material;
  12641. },
  12642. set: function (value) {
  12643. if (this._material === value) {
  12644. return;
  12645. }
  12646. this._material = value;
  12647. if (this.onMaterialChangedObservable.hasObservers) {
  12648. this.onMaterialChangedObservable.notifyObservers(this);
  12649. }
  12650. if (!this.subMeshes) {
  12651. return;
  12652. }
  12653. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12654. var subMesh = _a[_i];
  12655. subMesh.setEffect(null);
  12656. }
  12657. },
  12658. enumerable: true,
  12659. configurable: true
  12660. });
  12661. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12662. get: function () {
  12663. return this._receiveShadows;
  12664. },
  12665. set: function (value) {
  12666. if (this._receiveShadows === value) {
  12667. return;
  12668. }
  12669. this._receiveShadows = value;
  12670. this._markSubMeshesAsLightDirty();
  12671. },
  12672. enumerable: true,
  12673. configurable: true
  12674. });
  12675. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12676. get: function () {
  12677. return this._hasVertexAlpha;
  12678. },
  12679. set: function (value) {
  12680. if (this._hasVertexAlpha === value) {
  12681. return;
  12682. }
  12683. this._hasVertexAlpha = value;
  12684. this._markSubMeshesAsAttributesDirty();
  12685. },
  12686. enumerable: true,
  12687. configurable: true
  12688. });
  12689. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12690. get: function () {
  12691. return this._useVertexColors;
  12692. },
  12693. set: function (value) {
  12694. if (this._useVertexColors === value) {
  12695. return;
  12696. }
  12697. this._useVertexColors = value;
  12698. this._markSubMeshesAsAttributesDirty();
  12699. },
  12700. enumerable: true,
  12701. configurable: true
  12702. });
  12703. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12704. get: function () {
  12705. return this._computeBonesUsingShaders;
  12706. },
  12707. set: function (value) {
  12708. if (this._computeBonesUsingShaders === value) {
  12709. return;
  12710. }
  12711. this._computeBonesUsingShaders = value;
  12712. this._markSubMeshesAsAttributesDirty();
  12713. },
  12714. enumerable: true,
  12715. configurable: true
  12716. });
  12717. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12718. get: function () {
  12719. return this._numBoneInfluencers;
  12720. },
  12721. set: function (value) {
  12722. if (this._numBoneInfluencers === value) {
  12723. return;
  12724. }
  12725. this._numBoneInfluencers = value;
  12726. this._markSubMeshesAsAttributesDirty();
  12727. },
  12728. enumerable: true,
  12729. configurable: true
  12730. });
  12731. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12732. get: function () {
  12733. return this._applyFog;
  12734. },
  12735. set: function (value) {
  12736. if (this._applyFog === value) {
  12737. return;
  12738. }
  12739. this._applyFog = value;
  12740. this._markSubMeshesAsMiscDirty();
  12741. },
  12742. enumerable: true,
  12743. configurable: true
  12744. });
  12745. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  12746. get: function () {
  12747. return this._layerMask;
  12748. },
  12749. set: function (value) {
  12750. if (value === this._layerMask) {
  12751. return;
  12752. }
  12753. this._layerMask = value;
  12754. this._resyncLightSources();
  12755. },
  12756. enumerable: true,
  12757. configurable: true
  12758. });
  12759. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12760. get: function () {
  12761. return this._collisionMask;
  12762. },
  12763. set: function (mask) {
  12764. this._collisionMask = !isNaN(mask) ? mask : -1;
  12765. },
  12766. enumerable: true,
  12767. configurable: true
  12768. });
  12769. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12770. get: function () {
  12771. return this._collisionGroup;
  12772. },
  12773. set: function (mask) {
  12774. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12775. },
  12776. enumerable: true,
  12777. configurable: true
  12778. });
  12779. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  12780. get: function () {
  12781. return null;
  12782. },
  12783. enumerable: true,
  12784. configurable: true
  12785. });
  12786. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12787. get: function () {
  12788. return this._skeleton;
  12789. },
  12790. set: function (value) {
  12791. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12792. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12793. }
  12794. if (value && value.needInitialSkinMatrix) {
  12795. value._registerMeshWithPoseMatrix(this);
  12796. }
  12797. this._skeleton = value;
  12798. if (!this._skeleton) {
  12799. this._bonesTransformMatrices = null;
  12800. }
  12801. this._markSubMeshesAsAttributesDirty();
  12802. },
  12803. enumerable: true,
  12804. configurable: true
  12805. });
  12806. /**
  12807. * Boolean : true if the mesh has been disposed.
  12808. */
  12809. AbstractMesh.prototype.isDisposed = function () {
  12810. return this._isDisposed;
  12811. };
  12812. /**
  12813. * Returns the string "AbstractMesh"
  12814. */
  12815. AbstractMesh.prototype.getClassName = function () {
  12816. return "AbstractMesh";
  12817. };
  12818. /**
  12819. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12820. */
  12821. AbstractMesh.prototype.toString = function (fullDetails) {
  12822. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12823. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12824. if (this._skeleton) {
  12825. ret += ", skeleton: " + this._skeleton.name;
  12826. }
  12827. if (fullDetails) {
  12828. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12829. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12830. }
  12831. return ret;
  12832. };
  12833. AbstractMesh.prototype._rebuild = function () {
  12834. if (this._occlusionQuery) {
  12835. this._occlusionQuery = null;
  12836. }
  12837. if (this._edgesRenderer) {
  12838. this._edgesRenderer._rebuild();
  12839. }
  12840. if (!this.subMeshes) {
  12841. return;
  12842. }
  12843. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12844. var subMesh = _a[_i];
  12845. subMesh._rebuild();
  12846. }
  12847. };
  12848. AbstractMesh.prototype._resyncLightSources = function () {
  12849. this._lightSources.length = 0;
  12850. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12851. var light = _a[_i];
  12852. if (!light.isEnabled()) {
  12853. continue;
  12854. }
  12855. if (light.canAffectMesh(this)) {
  12856. this._lightSources.push(light);
  12857. }
  12858. }
  12859. this._markSubMeshesAsLightDirty();
  12860. };
  12861. AbstractMesh.prototype._resyncLighSource = function (light) {
  12862. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12863. var index = this._lightSources.indexOf(light);
  12864. if (index === -1) {
  12865. if (!isIn) {
  12866. return;
  12867. }
  12868. this._lightSources.push(light);
  12869. }
  12870. else {
  12871. if (isIn) {
  12872. return;
  12873. }
  12874. this._lightSources.splice(index, 1);
  12875. }
  12876. this._markSubMeshesAsLightDirty();
  12877. };
  12878. AbstractMesh.prototype._removeLightSource = function (light) {
  12879. var index = this._lightSources.indexOf(light);
  12880. if (index === -1) {
  12881. return;
  12882. }
  12883. this._lightSources.splice(index, 1);
  12884. };
  12885. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12886. if (!this.subMeshes) {
  12887. return;
  12888. }
  12889. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12890. var subMesh = _a[_i];
  12891. if (subMesh._materialDefines) {
  12892. func(subMesh._materialDefines);
  12893. }
  12894. }
  12895. };
  12896. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12897. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12898. };
  12899. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12900. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12901. };
  12902. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12903. if (!this.subMeshes) {
  12904. return;
  12905. }
  12906. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12907. var subMesh = _a[_i];
  12908. var material = subMesh.getMaterial();
  12909. if (material) {
  12910. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12911. }
  12912. }
  12913. };
  12914. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12915. /**
  12916. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12917. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12918. * Default : (0.0, 0.0, 0.0)
  12919. */
  12920. get: function () {
  12921. return this._rotation;
  12922. },
  12923. set: function (newRotation) {
  12924. this._rotation = newRotation;
  12925. },
  12926. enumerable: true,
  12927. configurable: true
  12928. });
  12929. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12930. /**
  12931. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12932. * Default : (1.0, 1.0, 1.0)
  12933. */
  12934. get: function () {
  12935. return this._scaling;
  12936. },
  12937. set: function (newScaling) {
  12938. this._scaling = newScaling;
  12939. if (this.physicsImpostor) {
  12940. this.physicsImpostor.forceUpdate();
  12941. }
  12942. },
  12943. enumerable: true,
  12944. configurable: true
  12945. });
  12946. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12947. /**
  12948. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12949. * It's null by default.
  12950. * 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)
  12951. */
  12952. get: function () {
  12953. return this._rotationQuaternion;
  12954. },
  12955. set: function (quaternion) {
  12956. this._rotationQuaternion = quaternion;
  12957. //reset the rotation vector.
  12958. if (quaternion && this.rotation.length()) {
  12959. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12960. }
  12961. },
  12962. enumerable: true,
  12963. configurable: true
  12964. });
  12965. // Methods
  12966. /**
  12967. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12968. * Returns the AbstractMesh.
  12969. */
  12970. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12971. this._poseMatrix.copyFrom(matrix);
  12972. return this;
  12973. };
  12974. /**
  12975. * Returns the mesh Pose matrix.
  12976. * Returned object : Matrix
  12977. */
  12978. AbstractMesh.prototype.getPoseMatrix = function () {
  12979. return this._poseMatrix;
  12980. };
  12981. /**
  12982. * Disables the mesh edger rendering mode.
  12983. * Returns the AbstractMesh.
  12984. */
  12985. AbstractMesh.prototype.disableEdgesRendering = function () {
  12986. if (this._edgesRenderer !== undefined) {
  12987. this._edgesRenderer.dispose();
  12988. this._edgesRenderer = undefined;
  12989. }
  12990. return this;
  12991. };
  12992. /**
  12993. * Enables the edge rendering mode on the mesh.
  12994. * This mode makes the mesh edges visible.
  12995. * Returns the AbstractMesh.
  12996. */
  12997. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12998. if (epsilon === void 0) { epsilon = 0.95; }
  12999. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  13000. this.disableEdgesRendering();
  13001. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  13002. return this;
  13003. };
  13004. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  13005. /**
  13006. * Returns true if the mesh is blocked. Used by the class Mesh.
  13007. * Returns the boolean `false` by default.
  13008. */
  13009. get: function () {
  13010. return false;
  13011. },
  13012. enumerable: true,
  13013. configurable: true
  13014. });
  13015. /**
  13016. * Returns the mesh itself by default, used by the class Mesh.
  13017. * Returned type : AbstractMesh
  13018. */
  13019. AbstractMesh.prototype.getLOD = function (camera) {
  13020. return this;
  13021. };
  13022. /**
  13023. * Returns 0 by default, used by the class Mesh.
  13024. * Returns an integer.
  13025. */
  13026. AbstractMesh.prototype.getTotalVertices = function () {
  13027. return 0;
  13028. };
  13029. /**
  13030. * Returns null by default, used by the class Mesh.
  13031. * Returned type : integer array
  13032. */
  13033. AbstractMesh.prototype.getIndices = function () {
  13034. return null;
  13035. };
  13036. /**
  13037. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  13038. * Returned type : float array or Float32Array
  13039. */
  13040. AbstractMesh.prototype.getVerticesData = function (kind) {
  13041. return null;
  13042. };
  13043. /**
  13044. * Sets the vertex data of the mesh geometry for the requested `kind`.
  13045. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  13046. * The `data` are either a numeric array either a Float32Array.
  13047. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  13048. * 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).
  13049. * Note that a new underlying VertexBuffer object is created each call.
  13050. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  13051. *
  13052. * Possible `kind` values :
  13053. * - BABYLON.VertexBuffer.PositionKind
  13054. * - BABYLON.VertexBuffer.UVKind
  13055. * - BABYLON.VertexBuffer.UV2Kind
  13056. * - BABYLON.VertexBuffer.UV3Kind
  13057. * - BABYLON.VertexBuffer.UV4Kind
  13058. * - BABYLON.VertexBuffer.UV5Kind
  13059. * - BABYLON.VertexBuffer.UV6Kind
  13060. * - BABYLON.VertexBuffer.ColorKind
  13061. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13062. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13063. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13064. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13065. *
  13066. * Returns the Mesh.
  13067. */
  13068. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  13069. return null;
  13070. };
  13071. /**
  13072. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  13073. * If the mesh has no geometry, it is simply returned as it is.
  13074. * The `data` are either a numeric array either a Float32Array.
  13075. * No new underlying VertexBuffer object is created.
  13076. * 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.
  13077. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  13078. *
  13079. * Possible `kind` values :
  13080. * - BABYLON.VertexBuffer.PositionKind
  13081. * - BABYLON.VertexBuffer.UVKind
  13082. * - BABYLON.VertexBuffer.UV2Kind
  13083. * - BABYLON.VertexBuffer.UV3Kind
  13084. * - BABYLON.VertexBuffer.UV4Kind
  13085. * - BABYLON.VertexBuffer.UV5Kind
  13086. * - BABYLON.VertexBuffer.UV6Kind
  13087. * - BABYLON.VertexBuffer.ColorKind
  13088. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13089. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13090. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13091. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13092. *
  13093. * Returns the Mesh.
  13094. */
  13095. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  13096. return null;
  13097. };
  13098. /**
  13099. * Sets the mesh indices.
  13100. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  13101. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  13102. * This method creates a new index buffer each call.
  13103. * Returns the Mesh.
  13104. */
  13105. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  13106. return null;
  13107. };
  13108. /** Returns false by default, used by the class Mesh.
  13109. * Returns a boolean
  13110. */
  13111. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  13112. return false;
  13113. };
  13114. /**
  13115. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  13116. * Returns a BoundingInfo
  13117. */
  13118. AbstractMesh.prototype.getBoundingInfo = function () {
  13119. if (this._masterMesh) {
  13120. return this._masterMesh.getBoundingInfo();
  13121. }
  13122. if (!this._boundingInfo) {
  13123. this._updateBoundingInfo();
  13124. }
  13125. return this._boundingInfo;
  13126. };
  13127. /**
  13128. * Sets a mesh new object BoundingInfo.
  13129. * Returns the AbstractMesh.
  13130. */
  13131. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  13132. this._boundingInfo = boundingInfo;
  13133. return this;
  13134. };
  13135. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  13136. get: function () {
  13137. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  13138. },
  13139. enumerable: true,
  13140. configurable: true
  13141. });
  13142. AbstractMesh.prototype._preActivate = function () {
  13143. };
  13144. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  13145. };
  13146. AbstractMesh.prototype._activate = function (renderId) {
  13147. this._renderId = renderId;
  13148. };
  13149. /**
  13150. * Returns the last update of the World matrix
  13151. * Returns a Matrix.
  13152. */
  13153. AbstractMesh.prototype.getWorldMatrix = function () {
  13154. if (this._masterMesh) {
  13155. return this._masterMesh.getWorldMatrix();
  13156. }
  13157. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  13158. this.computeWorldMatrix();
  13159. }
  13160. return this._worldMatrix;
  13161. };
  13162. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  13163. /**
  13164. * Returns directly the last state of the mesh World matrix.
  13165. * A Matrix is returned.
  13166. */
  13167. get: function () {
  13168. return this._worldMatrix;
  13169. },
  13170. enumerable: true,
  13171. configurable: true
  13172. });
  13173. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  13174. /**
  13175. * Returns the current mesh absolute position.
  13176. * Retuns a Vector3.
  13177. */
  13178. get: function () {
  13179. return this._absolutePosition;
  13180. },
  13181. enumerable: true,
  13182. configurable: true
  13183. });
  13184. /**
  13185. * Prevents the World matrix to be computed any longer.
  13186. * Returns the AbstractMesh.
  13187. */
  13188. AbstractMesh.prototype.freezeWorldMatrix = function () {
  13189. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13190. this.computeWorldMatrix(true);
  13191. this._isWorldMatrixFrozen = true;
  13192. return this;
  13193. };
  13194. /**
  13195. * Allows back the World matrix computation.
  13196. * Returns the AbstractMesh.
  13197. */
  13198. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  13199. this._isWorldMatrixFrozen = false;
  13200. this.computeWorldMatrix(true);
  13201. return this;
  13202. };
  13203. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  13204. /**
  13205. * True if the World matrix has been frozen.
  13206. * Returns a boolean.
  13207. */
  13208. get: function () {
  13209. return this._isWorldMatrixFrozen;
  13210. },
  13211. enumerable: true,
  13212. configurable: true
  13213. });
  13214. /**
  13215. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13216. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13217. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13218. * The passed axis is also normalized.
  13219. * Returns the AbstractMesh.
  13220. */
  13221. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  13222. axis.normalize();
  13223. if (!this.rotationQuaternion) {
  13224. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13225. this.rotation = BABYLON.Vector3.Zero();
  13226. }
  13227. var rotationQuaternion;
  13228. if (!space || space === BABYLON.Space.LOCAL) {
  13229. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13230. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13231. }
  13232. else {
  13233. if (this.parent) {
  13234. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13235. invertParentWorldMatrix.invert();
  13236. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13237. }
  13238. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13239. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13240. }
  13241. return this;
  13242. };
  13243. /**
  13244. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13245. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13246. * The passed axis is also normalized.
  13247. * Returns the AbstractMesh.
  13248. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13249. */
  13250. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  13251. axis.normalize();
  13252. if (!this.rotationQuaternion) {
  13253. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13254. this.rotation.copyFromFloats(0, 0, 0);
  13255. }
  13256. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13257. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13258. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13259. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13260. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13261. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13262. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13263. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13264. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13265. return this;
  13266. };
  13267. /**
  13268. * Translates the mesh along the axis vector for the passed distance in the given space.
  13269. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13270. * Returns the AbstractMesh.
  13271. */
  13272. AbstractMesh.prototype.translate = function (axis, distance, space) {
  13273. var displacementVector = axis.scale(distance);
  13274. if (!space || space === BABYLON.Space.LOCAL) {
  13275. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13276. this.setPositionWithLocalVector(tempV3);
  13277. }
  13278. else {
  13279. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13280. }
  13281. return this;
  13282. };
  13283. /**
  13284. * Adds a rotation step to the mesh current rotation.
  13285. * x, y, z are Euler angles expressed in radians.
  13286. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13287. * This means this rotation is made in the mesh local space only.
  13288. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13289. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13290. * ```javascript
  13291. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13292. * ```
  13293. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13294. * 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.
  13295. * Returns the AbstractMesh.
  13296. */
  13297. AbstractMesh.prototype.addRotation = function (x, y, z) {
  13298. var rotationQuaternion;
  13299. if (this.rotationQuaternion) {
  13300. rotationQuaternion = this.rotationQuaternion;
  13301. }
  13302. else {
  13303. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13304. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13305. }
  13306. var accumulation = BABYLON.Tmp.Quaternion[0];
  13307. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13308. rotationQuaternion.multiplyInPlace(accumulation);
  13309. if (!this.rotationQuaternion) {
  13310. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13311. }
  13312. return this;
  13313. };
  13314. /**
  13315. * Retuns the mesh absolute position in the World.
  13316. * Returns a Vector3.
  13317. */
  13318. AbstractMesh.prototype.getAbsolutePosition = function () {
  13319. this.computeWorldMatrix();
  13320. return this._absolutePosition;
  13321. };
  13322. /**
  13323. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13324. * Returns the AbstractMesh.
  13325. */
  13326. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13327. if (!absolutePosition) {
  13328. return this;
  13329. }
  13330. var absolutePositionX;
  13331. var absolutePositionY;
  13332. var absolutePositionZ;
  13333. if (absolutePosition.x === undefined) {
  13334. if (arguments.length < 3) {
  13335. return this;
  13336. }
  13337. absolutePositionX = arguments[0];
  13338. absolutePositionY = arguments[1];
  13339. absolutePositionZ = arguments[2];
  13340. }
  13341. else {
  13342. absolutePositionX = absolutePosition.x;
  13343. absolutePositionY = absolutePosition.y;
  13344. absolutePositionZ = absolutePosition.z;
  13345. }
  13346. if (this.parent) {
  13347. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13348. invertParentWorldMatrix.invert();
  13349. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13350. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13351. }
  13352. else {
  13353. this.position.x = absolutePositionX;
  13354. this.position.y = absolutePositionY;
  13355. this.position.z = absolutePositionZ;
  13356. }
  13357. return this;
  13358. };
  13359. // ================================== Point of View Movement =================================
  13360. /**
  13361. * Perform relative position change from the point of view of behind the front of the mesh.
  13362. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13363. * Supports definition of mesh facing forward or backward.
  13364. * @param {number} amountRight
  13365. * @param {number} amountUp
  13366. * @param {number} amountForward
  13367. *
  13368. * Returns the AbstractMesh.
  13369. */
  13370. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13371. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13372. return this;
  13373. };
  13374. /**
  13375. * Calculate relative position change from the point of view of behind the front of the mesh.
  13376. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13377. * Supports definition of mesh facing forward or backward.
  13378. * @param {number} amountRight
  13379. * @param {number} amountUp
  13380. * @param {number} amountForward
  13381. *
  13382. * Returns a new Vector3.
  13383. */
  13384. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13385. var rotMatrix = new BABYLON.Matrix();
  13386. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13387. rotQuaternion.toRotationMatrix(rotMatrix);
  13388. var translationDelta = BABYLON.Vector3.Zero();
  13389. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13390. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13391. return translationDelta;
  13392. };
  13393. // ================================== Point of View Rotation =================================
  13394. /**
  13395. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13396. * Supports definition of mesh facing forward or backward.
  13397. * @param {number} flipBack
  13398. * @param {number} twirlClockwise
  13399. * @param {number} tiltRight
  13400. *
  13401. * Returns the AbstractMesh.
  13402. */
  13403. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13404. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13405. return this;
  13406. };
  13407. /**
  13408. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13409. * Supports definition of mesh facing forward or backward.
  13410. * @param {number} flipBack
  13411. * @param {number} twirlClockwise
  13412. * @param {number} tiltRight
  13413. *
  13414. * Returns a new Vector3.
  13415. */
  13416. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13417. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13418. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13419. };
  13420. /**
  13421. * Sets a new pivot matrix to the mesh.
  13422. * Returns the AbstractMesh.
  13423. */
  13424. AbstractMesh.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13425. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13426. this._pivotMatrix = matrix.clone();
  13427. this._cache.pivotMatrixUpdated = true;
  13428. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13429. if (this._postMultiplyPivotMatrix) {
  13430. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13431. }
  13432. return this;
  13433. };
  13434. /**
  13435. * Returns the mesh pivot matrix.
  13436. * Default : Identity.
  13437. * A Matrix is returned.
  13438. */
  13439. AbstractMesh.prototype.getPivotMatrix = function () {
  13440. return this._pivotMatrix;
  13441. };
  13442. AbstractMesh.prototype._isSynchronized = function () {
  13443. if (this._isDirty) {
  13444. return false;
  13445. }
  13446. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13447. return false;
  13448. if (this._cache.pivotMatrixUpdated) {
  13449. return false;
  13450. }
  13451. if (this.infiniteDistance) {
  13452. return false;
  13453. }
  13454. if (!this._cache.position.equals(this.position))
  13455. return false;
  13456. if (this.rotationQuaternion) {
  13457. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13458. return false;
  13459. }
  13460. if (!this._cache.rotation.equals(this.rotation))
  13461. return false;
  13462. if (!this._cache.scaling.equals(this.scaling))
  13463. return false;
  13464. return true;
  13465. };
  13466. AbstractMesh.prototype._initCache = function () {
  13467. _super.prototype._initCache.call(this);
  13468. this._cache.localMatrixUpdated = false;
  13469. this._cache.position = BABYLON.Vector3.Zero();
  13470. this._cache.scaling = BABYLON.Vector3.Zero();
  13471. this._cache.rotation = BABYLON.Vector3.Zero();
  13472. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13473. this._cache.billboardMode = -1;
  13474. };
  13475. AbstractMesh.prototype.markAsDirty = function (property) {
  13476. if (property === "rotation") {
  13477. this.rotationQuaternion = null;
  13478. }
  13479. this._currentRenderId = Number.MAX_VALUE;
  13480. this._isDirty = true;
  13481. return this;
  13482. };
  13483. /**
  13484. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  13485. */
  13486. AbstractMesh.prototype.getHierarchyBoundingVectors = function () {
  13487. this.computeWorldMatrix(true);
  13488. var min;
  13489. var max;
  13490. if (!this.subMeshes) {
  13491. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13492. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13493. }
  13494. else {
  13495. min = this.getBoundingInfo().boundingBox.minimumWorld;
  13496. max = this.getBoundingInfo().boundingBox.maximumWorld;
  13497. }
  13498. var descendants = this.getDescendants(false);
  13499. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  13500. var descendant = descendants_1[_i];
  13501. var childMesh = descendant;
  13502. childMesh.computeWorldMatrix(true);
  13503. if (childMesh.getTotalVertices() === 0) {
  13504. continue;
  13505. }
  13506. var boundingBox = childMesh.getBoundingInfo().boundingBox;
  13507. var minBox = boundingBox.minimumWorld;
  13508. var maxBox = boundingBox.maximumWorld;
  13509. BABYLON.Tools.CheckExtends(minBox, min, max);
  13510. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13511. }
  13512. return {
  13513. min: min,
  13514. max: max
  13515. };
  13516. };
  13517. /**
  13518. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  13519. * Returns the AbstractMesh.
  13520. */
  13521. AbstractMesh.prototype._updateBoundingInfo = function () {
  13522. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  13523. this._boundingInfo.update(this.worldMatrixFromCache);
  13524. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13525. return this;
  13526. };
  13527. /**
  13528. * Update a mesh's children BoundingInfo objects only.
  13529. * Returns the AbstractMesh.
  13530. */
  13531. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  13532. if (!this.subMeshes) {
  13533. return this;
  13534. }
  13535. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  13536. var subMesh = this.subMeshes[subIndex];
  13537. if (!subMesh.IsGlobal) {
  13538. subMesh.updateBoundingInfo(matrix);
  13539. }
  13540. }
  13541. return this;
  13542. };
  13543. /**
  13544. * Computes the mesh World matrix and returns it.
  13545. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13546. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13547. * If the parameter `force`is set to `true`, the actual computation is done.
  13548. * Returns the mesh World Matrix.
  13549. */
  13550. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13551. if (this._isWorldMatrixFrozen) {
  13552. return this._worldMatrix;
  13553. }
  13554. if (!force && this.isSynchronized(true)) {
  13555. this._currentRenderId = this.getScene().getRenderId();
  13556. return this._worldMatrix;
  13557. }
  13558. this._cache.position.copyFrom(this.position);
  13559. this._cache.scaling.copyFrom(this.scaling);
  13560. this._cache.pivotMatrixUpdated = false;
  13561. this._cache.billboardMode = this.billboardMode;
  13562. this._currentRenderId = this.getScene().getRenderId();
  13563. this._isDirty = false;
  13564. // Scaling
  13565. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13566. // Rotation
  13567. //rotate, if quaternion is set and rotation was used
  13568. if (this.rotationQuaternion) {
  13569. var len = this.rotation.length();
  13570. if (len) {
  13571. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13572. this.rotation.copyFromFloats(0, 0, 0);
  13573. }
  13574. }
  13575. if (this.rotationQuaternion) {
  13576. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13577. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13578. }
  13579. else {
  13580. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13581. this._cache.rotation.copyFrom(this.rotation);
  13582. }
  13583. // Translation
  13584. if (this.infiniteDistance && !this.parent) {
  13585. var camera = this.getScene().activeCamera;
  13586. if (camera) {
  13587. var cameraWorldMatrix = camera.getWorldMatrix();
  13588. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13589. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13590. }
  13591. }
  13592. else {
  13593. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13594. }
  13595. // Composing transformations
  13596. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13597. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13598. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13599. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  13600. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13601. // Need to decompose each rotation here
  13602. var currentPosition = BABYLON.Tmp.Vector3[3];
  13603. if (this.parent && this.parent.getWorldMatrix) {
  13604. if (this._meshToBoneReferal) {
  13605. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13606. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13607. }
  13608. else {
  13609. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13610. }
  13611. }
  13612. else {
  13613. currentPosition.copyFrom(this.position);
  13614. }
  13615. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  13616. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13617. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13618. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13619. }
  13620. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13621. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13622. }
  13623. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13624. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13625. }
  13626. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13627. }
  13628. else {
  13629. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  13630. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13631. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13632. }
  13633. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13634. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13635. }
  13636. // Local world
  13637. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13638. // Parent
  13639. if (this.parent && this.parent.getWorldMatrix) {
  13640. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13641. if (this._meshToBoneReferal) {
  13642. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13643. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13644. }
  13645. else {
  13646. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13647. }
  13648. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13649. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13650. this._worldMatrix.copyFrom(this._localWorld);
  13651. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13652. }
  13653. else {
  13654. if (this._meshToBoneReferal) {
  13655. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13656. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13657. }
  13658. else {
  13659. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13660. }
  13661. }
  13662. this._markSyncedWithParent();
  13663. }
  13664. else {
  13665. this._worldMatrix.copyFrom(this._localWorld);
  13666. }
  13667. // Post multiply inverse of pivotMatrix
  13668. if (this._postMultiplyPivotMatrix) {
  13669. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  13670. }
  13671. // Bounding info
  13672. this._updateBoundingInfo();
  13673. // Absolute position
  13674. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13675. // Callbacks
  13676. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13677. if (!this._poseMatrix) {
  13678. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13679. }
  13680. return this._worldMatrix;
  13681. };
  13682. /**
  13683. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13684. * @param func: callback function to add
  13685. *
  13686. * Returns the AbstractMesh.
  13687. */
  13688. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13689. this.onAfterWorldMatrixUpdateObservable.add(func);
  13690. return this;
  13691. };
  13692. /**
  13693. * Removes a registered callback function.
  13694. * Returns the AbstractMesh.
  13695. */
  13696. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13697. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13698. return this;
  13699. };
  13700. /**
  13701. * Sets the mesh position in its local space.
  13702. * Returns the AbstractMesh.
  13703. */
  13704. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13705. this.computeWorldMatrix();
  13706. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13707. return this;
  13708. };
  13709. /**
  13710. * Returns the mesh position in the local space from the current World matrix values.
  13711. * Returns a new Vector3.
  13712. */
  13713. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13714. this.computeWorldMatrix();
  13715. var invLocalWorldMatrix = this._localWorld.clone();
  13716. invLocalWorldMatrix.invert();
  13717. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13718. };
  13719. /**
  13720. * Translates the mesh along the passed Vector3 in its local space.
  13721. * Returns the AbstractMesh.
  13722. */
  13723. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13724. this.computeWorldMatrix(true);
  13725. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13726. return this;
  13727. };
  13728. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13729. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13730. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13731. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13732. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13733. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13734. /// <returns>Mesh oriented towards targetMesh</returns>
  13735. if (yawCor === void 0) { yawCor = 0; }
  13736. if (pitchCor === void 0) { pitchCor = 0; }
  13737. if (rollCor === void 0) { rollCor = 0; }
  13738. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13739. var dv = AbstractMesh._lookAtVectorCache;
  13740. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13741. targetPoint.subtractToRef(pos, dv);
  13742. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13743. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13744. var pitch = Math.atan2(dv.y, len);
  13745. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13746. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13747. return this;
  13748. };
  13749. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13750. this._meshToBoneReferal = affectedMesh;
  13751. this.parent = bone;
  13752. if (bone.getWorldMatrix().determinant() < 0) {
  13753. this.scalingDeterminant *= -1;
  13754. }
  13755. return this;
  13756. };
  13757. AbstractMesh.prototype.detachFromBone = function () {
  13758. if (this.parent.getWorldMatrix().determinant() < 0) {
  13759. this.scalingDeterminant *= -1;
  13760. }
  13761. this._meshToBoneReferal = null;
  13762. this.parent = null;
  13763. return this;
  13764. };
  13765. /**
  13766. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13767. * A mesh is in the frustum if its bounding box intersects the frustum.
  13768. * Boolean returned.
  13769. */
  13770. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13771. return this._boundingInfo.isInFrustum(frustumPlanes);
  13772. };
  13773. /**
  13774. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13775. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13776. * Boolean returned.
  13777. */
  13778. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13779. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13780. ;
  13781. };
  13782. /**
  13783. * True if the mesh intersects another mesh or a SolidParticle object.
  13784. * 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)
  13785. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  13786. * Returns a boolean.
  13787. */
  13788. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  13789. if (!this._boundingInfo || !mesh._boundingInfo) {
  13790. return false;
  13791. }
  13792. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  13793. return true;
  13794. }
  13795. if (includeDescendants) {
  13796. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  13797. var child = _a[_i];
  13798. if (child.intersectsMesh(mesh, precise, true)) {
  13799. return true;
  13800. }
  13801. }
  13802. }
  13803. return false;
  13804. };
  13805. /**
  13806. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13807. * Returns a boolean.
  13808. */
  13809. AbstractMesh.prototype.intersectsPoint = function (point) {
  13810. if (!this._boundingInfo) {
  13811. return false;
  13812. }
  13813. return this._boundingInfo.intersectsPoint(point);
  13814. };
  13815. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13816. return this.physicsImpostor;
  13817. };
  13818. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13819. if (!camera) {
  13820. camera = this.getScene().activeCamera;
  13821. }
  13822. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13823. };
  13824. /**
  13825. * Returns the distance from the mesh to the active camera.
  13826. * Returns a float.
  13827. */
  13828. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13829. if (!camera) {
  13830. camera = this.getScene().activeCamera;
  13831. }
  13832. return this.absolutePosition.subtract(camera.position).length();
  13833. };
  13834. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13835. if (!this.physicsImpostor) {
  13836. return this;
  13837. }
  13838. this.physicsImpostor.applyImpulse(force, contactPoint);
  13839. return this;
  13840. };
  13841. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13842. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13843. return this;
  13844. }
  13845. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13846. mainPivot: pivot1,
  13847. connectedPivot: pivot2,
  13848. nativeParams: options
  13849. });
  13850. return this;
  13851. };
  13852. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13853. // Collisions
  13854. /**
  13855. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13856. * Default `false`.
  13857. */
  13858. get: function () {
  13859. return this._checkCollisions;
  13860. },
  13861. set: function (collisionEnabled) {
  13862. this._checkCollisions = collisionEnabled;
  13863. if (this.getScene().workerCollisions) {
  13864. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13865. }
  13866. },
  13867. enumerable: true,
  13868. configurable: true
  13869. });
  13870. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  13871. var globalPosition = this.getAbsolutePosition();
  13872. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13873. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13874. if (!this._collider) {
  13875. this._collider = new BABYLON.Collider();
  13876. }
  13877. this._collider.radius = this.ellipsoid;
  13878. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13879. return this;
  13880. };
  13881. // Submeshes octree
  13882. /**
  13883. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13884. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13885. * Returns an Octree of submeshes.
  13886. */
  13887. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13888. if (maxCapacity === void 0) { maxCapacity = 64; }
  13889. if (maxDepth === void 0) { maxDepth = 2; }
  13890. if (!this._submeshesOctree) {
  13891. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13892. }
  13893. this.computeWorldMatrix(true);
  13894. // Update octree
  13895. var bbox = this.getBoundingInfo().boundingBox;
  13896. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13897. return this._submeshesOctree;
  13898. };
  13899. // Collisions
  13900. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13901. this._generatePointsArray();
  13902. // Transformation
  13903. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13904. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13905. subMesh._lastColliderWorldVertices = [];
  13906. subMesh._trianglePlanes = [];
  13907. var start = subMesh.verticesStart;
  13908. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13909. for (var i = start; i < end; i++) {
  13910. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13911. }
  13912. }
  13913. // Collide
  13914. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13915. if (collider.collisionFound) {
  13916. collider.collidedMesh = this;
  13917. }
  13918. return this;
  13919. };
  13920. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13921. var subMeshes;
  13922. var len;
  13923. // Octrees
  13924. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13925. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13926. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13927. len = intersections.length;
  13928. subMeshes = intersections.data;
  13929. }
  13930. else {
  13931. subMeshes = this.subMeshes;
  13932. len = subMeshes.length;
  13933. }
  13934. for (var index = 0; index < len; index++) {
  13935. var subMesh = subMeshes[index];
  13936. // Bounding test
  13937. if (len > 1 && !subMesh._checkCollision(collider))
  13938. continue;
  13939. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13940. }
  13941. return this;
  13942. };
  13943. AbstractMesh.prototype._checkCollision = function (collider) {
  13944. // Bounding box test
  13945. if (!this._boundingInfo._checkCollision(collider))
  13946. return this;
  13947. // Transformation matrix
  13948. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13949. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13950. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13951. return this;
  13952. };
  13953. // Picking
  13954. AbstractMesh.prototype._generatePointsArray = function () {
  13955. return false;
  13956. };
  13957. /**
  13958. * Checks if the passed Ray intersects with the mesh.
  13959. * Returns an object PickingInfo.
  13960. */
  13961. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13962. var pickingInfo = new BABYLON.PickingInfo();
  13963. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13964. return pickingInfo;
  13965. }
  13966. if (!this._generatePointsArray()) {
  13967. return pickingInfo;
  13968. }
  13969. var intersectInfo = null;
  13970. // Octrees
  13971. var subMeshes;
  13972. var len;
  13973. if (this._submeshesOctree && this.useOctreeForPicking) {
  13974. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13975. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13976. len = intersections.length;
  13977. subMeshes = intersections.data;
  13978. }
  13979. else {
  13980. subMeshes = this.subMeshes;
  13981. len = subMeshes.length;
  13982. }
  13983. for (var index = 0; index < len; index++) {
  13984. var subMesh = subMeshes[index];
  13985. // Bounding test
  13986. if (len > 1 && !subMesh.canIntersects(ray))
  13987. continue;
  13988. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13989. if (currentIntersectInfo) {
  13990. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13991. intersectInfo = currentIntersectInfo;
  13992. intersectInfo.subMeshId = index;
  13993. if (fastCheck) {
  13994. break;
  13995. }
  13996. }
  13997. }
  13998. }
  13999. if (intersectInfo) {
  14000. // Get picked point
  14001. var world = this.getWorldMatrix();
  14002. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  14003. var direction = ray.direction.clone();
  14004. direction = direction.scale(intersectInfo.distance);
  14005. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  14006. var pickedPoint = worldOrigin.add(worldDirection);
  14007. // Return result
  14008. pickingInfo.hit = true;
  14009. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  14010. pickingInfo.pickedPoint = pickedPoint;
  14011. pickingInfo.pickedMesh = this;
  14012. pickingInfo.bu = intersectInfo.bu;
  14013. pickingInfo.bv = intersectInfo.bv;
  14014. pickingInfo.faceId = intersectInfo.faceId;
  14015. pickingInfo.subMeshId = intersectInfo.subMeshId;
  14016. return pickingInfo;
  14017. }
  14018. return pickingInfo;
  14019. };
  14020. /**
  14021. * Clones the mesh, used by the class Mesh.
  14022. * Just returns `null` for an AbstractMesh.
  14023. */
  14024. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14025. return null;
  14026. };
  14027. /**
  14028. * Disposes all the mesh submeshes.
  14029. * Returns the AbstractMesh.
  14030. */
  14031. AbstractMesh.prototype.releaseSubMeshes = function () {
  14032. if (this.subMeshes) {
  14033. while (this.subMeshes.length) {
  14034. this.subMeshes[0].dispose();
  14035. }
  14036. }
  14037. else {
  14038. this.subMeshes = new Array();
  14039. }
  14040. return this;
  14041. };
  14042. /**
  14043. * Disposes the AbstractMesh.
  14044. * Some internal references are kept for further use.
  14045. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  14046. * Returns nothing.
  14047. */
  14048. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  14049. var _this = this;
  14050. var index;
  14051. // Action manager
  14052. if (this.actionManager) {
  14053. this.actionManager.dispose();
  14054. this.actionManager = null;
  14055. }
  14056. // Skeleton
  14057. this.skeleton = null;
  14058. // Animations
  14059. this.getScene().stopAnimation(this);
  14060. // Physics
  14061. if (this.physicsImpostor) {
  14062. this.physicsImpostor.dispose();
  14063. }
  14064. // Intersections in progress
  14065. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  14066. var other = this._intersectionsInProgress[index];
  14067. var pos = other._intersectionsInProgress.indexOf(this);
  14068. other._intersectionsInProgress.splice(pos, 1);
  14069. }
  14070. this._intersectionsInProgress = [];
  14071. // Lights
  14072. var lights = this.getScene().lights;
  14073. lights.forEach(function (light) {
  14074. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  14075. if (meshIndex !== -1) {
  14076. light.includedOnlyMeshes.splice(meshIndex, 1);
  14077. }
  14078. meshIndex = light.excludedMeshes.indexOf(_this);
  14079. if (meshIndex !== -1) {
  14080. light.excludedMeshes.splice(meshIndex, 1);
  14081. }
  14082. // Shadow generators
  14083. var generator = light.getShadowGenerator();
  14084. if (generator) {
  14085. var shadowMap = generator.getShadowMap();
  14086. meshIndex = shadowMap.renderList.indexOf(_this);
  14087. if (meshIndex !== -1) {
  14088. shadowMap.renderList.splice(meshIndex, 1);
  14089. }
  14090. }
  14091. });
  14092. // Edges
  14093. if (this._edgesRenderer) {
  14094. this._edgesRenderer.dispose();
  14095. this._edgesRenderer = null;
  14096. }
  14097. // SubMeshes
  14098. if (this.getClassName() !== "InstancedMesh") {
  14099. this.releaseSubMeshes();
  14100. }
  14101. // Octree
  14102. var sceneOctree = this.getScene().selectionOctree;
  14103. if (sceneOctree) {
  14104. var index = sceneOctree.dynamicContent.indexOf(this);
  14105. if (index !== -1) {
  14106. sceneOctree.dynamicContent.splice(index, 1);
  14107. }
  14108. }
  14109. // Query
  14110. var engine = this.getScene().getEngine();
  14111. if (this._occlusionQuery) {
  14112. this._isOcclusionQueryInProgress = false;
  14113. engine.deleteQuery(this._occlusionQuery);
  14114. this._occlusionQuery = null;
  14115. }
  14116. // Engine
  14117. engine.wipeCaches();
  14118. // Remove from scene
  14119. this.getScene().removeMesh(this);
  14120. if (!doNotRecurse) {
  14121. // Particles
  14122. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  14123. if (this.getScene().particleSystems[index].emitter === this) {
  14124. this.getScene().particleSystems[index].dispose();
  14125. index--;
  14126. }
  14127. }
  14128. // Children
  14129. var objects = this.getDescendants(true);
  14130. for (index = 0; index < objects.length; index++) {
  14131. objects[index].dispose();
  14132. }
  14133. }
  14134. else {
  14135. var childMeshes = this.getChildMeshes(true);
  14136. for (index = 0; index < childMeshes.length; index++) {
  14137. var child = childMeshes[index];
  14138. child.parent = null;
  14139. child.computeWorldMatrix(true);
  14140. }
  14141. }
  14142. // facet data
  14143. if (this._facetDataEnabled) {
  14144. this.disableFacetData();
  14145. }
  14146. this.onAfterWorldMatrixUpdateObservable.clear();
  14147. this.onCollideObservable.clear();
  14148. this.onCollisionPositionChangeObservable.clear();
  14149. this._isDisposed = true;
  14150. _super.prototype.dispose.call(this);
  14151. };
  14152. /**
  14153. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14154. * This Vector3 is expressed in the World space.
  14155. */
  14156. AbstractMesh.prototype.getDirection = function (localAxis) {
  14157. var result = BABYLON.Vector3.Zero();
  14158. this.getDirectionToRef(localAxis, result);
  14159. return result;
  14160. };
  14161. /**
  14162. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14163. * localAxis is expressed in the mesh local space.
  14164. * result is computed in the Wordl space from the mesh World matrix.
  14165. * Returns the AbstractMesh.
  14166. */
  14167. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  14168. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14169. return this;
  14170. };
  14171. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  14172. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14173. if (this.getScene().getRenderId() == 0) {
  14174. this.computeWorldMatrix(true);
  14175. }
  14176. var wm = this.getWorldMatrix();
  14177. if (space == BABYLON.Space.WORLD) {
  14178. var tmat = BABYLON.Tmp.Matrix[0];
  14179. wm.invertToRef(tmat);
  14180. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14181. }
  14182. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14183. this._pivotMatrix.m[12] = -point.x;
  14184. this._pivotMatrix.m[13] = -point.y;
  14185. this._pivotMatrix.m[14] = -point.z;
  14186. this._cache.pivotMatrixUpdated = true;
  14187. return this;
  14188. };
  14189. /**
  14190. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14191. */
  14192. AbstractMesh.prototype.getPivotPoint = function () {
  14193. var point = BABYLON.Vector3.Zero();
  14194. this.getPivotPointToRef(point);
  14195. return point;
  14196. };
  14197. /**
  14198. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14199. * Returns the AbstractMesh.
  14200. */
  14201. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  14202. result.x = -this._pivotMatrix.m[12];
  14203. result.y = -this._pivotMatrix.m[13];
  14204. result.z = -this._pivotMatrix.m[14];
  14205. return this;
  14206. };
  14207. /**
  14208. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14209. */
  14210. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  14211. var point = BABYLON.Vector3.Zero();
  14212. this.getAbsolutePivotPointToRef(point);
  14213. return point;
  14214. };
  14215. /**
  14216. * Defines the passed mesh as the parent of the current mesh.
  14217. * Returns the AbstractMesh.
  14218. */
  14219. AbstractMesh.prototype.setParent = function (mesh) {
  14220. var child = this;
  14221. var parent = mesh;
  14222. if (mesh == null) {
  14223. var rotation = BABYLON.Tmp.Quaternion[0];
  14224. var position = BABYLON.Tmp.Vector3[0];
  14225. var scale = BABYLON.Tmp.Vector3[1];
  14226. child.getWorldMatrix().decompose(scale, rotation, position);
  14227. if (child.rotationQuaternion) {
  14228. child.rotationQuaternion.copyFrom(rotation);
  14229. }
  14230. else {
  14231. rotation.toEulerAnglesToRef(child.rotation);
  14232. }
  14233. child.position.x = position.x;
  14234. child.position.y = position.y;
  14235. child.position.z = position.z;
  14236. }
  14237. else {
  14238. var position = BABYLON.Tmp.Vector3[0];
  14239. var m1 = BABYLON.Tmp.Matrix[0];
  14240. parent.getWorldMatrix().invertToRef(m1);
  14241. BABYLON.Vector3.TransformCoordinatesToRef(child.position, m1, position);
  14242. child.position.copyFrom(position);
  14243. }
  14244. child.parent = parent;
  14245. return this;
  14246. };
  14247. /**
  14248. * Adds the passed mesh as a child to the current mesh.
  14249. * Returns the AbstractMesh.
  14250. */
  14251. AbstractMesh.prototype.addChild = function (mesh) {
  14252. mesh.setParent(this);
  14253. return this;
  14254. };
  14255. /**
  14256. * Removes the passed mesh from the current mesh children list.
  14257. * Returns the AbstractMesh.
  14258. */
  14259. AbstractMesh.prototype.removeChild = function (mesh) {
  14260. mesh.setParent(null);
  14261. return this;
  14262. };
  14263. /**
  14264. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14265. * Returns the AbstractMesh.
  14266. */
  14267. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  14268. result.x = this._pivotMatrix.m[12];
  14269. result.y = this._pivotMatrix.m[13];
  14270. result.z = this._pivotMatrix.m[14];
  14271. this.getPivotPointToRef(result);
  14272. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14273. return this;
  14274. };
  14275. // Facet data
  14276. /**
  14277. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  14278. * Returns the AbstractMesh.
  14279. */
  14280. AbstractMesh.prototype._initFacetData = function () {
  14281. if (!this._facetNormals) {
  14282. this._facetNormals = new Array();
  14283. }
  14284. if (!this._facetPositions) {
  14285. this._facetPositions = new Array();
  14286. }
  14287. if (!this._facetPartitioning) {
  14288. this._facetPartitioning = new Array();
  14289. }
  14290. this._facetNb = this.getIndices().length / 3;
  14291. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  14292. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  14293. for (var f = 0; f < this._facetNb; f++) {
  14294. this._facetNormals[f] = BABYLON.Vector3.Zero();
  14295. this._facetPositions[f] = BABYLON.Vector3.Zero();
  14296. }
  14297. this._facetDataEnabled = true;
  14298. return this;
  14299. };
  14300. /**
  14301. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  14302. * This method can be called within the render loop.
  14303. * 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.
  14304. * Returns the AbstractMesh.
  14305. */
  14306. AbstractMesh.prototype.updateFacetData = function () {
  14307. if (!this._facetDataEnabled) {
  14308. this._initFacetData();
  14309. }
  14310. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14311. var indices = this.getIndices();
  14312. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14313. var bInfo = this.getBoundingInfo();
  14314. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  14315. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  14316. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  14317. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  14318. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  14319. this._subDiv.max = this._partitioningSubdivisions;
  14320. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  14321. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  14322. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  14323. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  14324. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  14325. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  14326. // set the parameters for ComputeNormals()
  14327. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  14328. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  14329. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  14330. this._facetParameters.bInfo = bInfo;
  14331. this._facetParameters.bbSize = this._bbSize;
  14332. this._facetParameters.subDiv = this._subDiv;
  14333. this._facetParameters.ratio = this.partitioningBBoxRatio;
  14334. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  14335. return this;
  14336. };
  14337. /**
  14338. * Returns the facetLocalNormals array.
  14339. * The normals are expressed in the mesh local space.
  14340. */
  14341. AbstractMesh.prototype.getFacetLocalNormals = function () {
  14342. if (!this._facetNormals) {
  14343. this.updateFacetData();
  14344. }
  14345. return this._facetNormals;
  14346. };
  14347. /**
  14348. * Returns the facetLocalPositions array.
  14349. * The facet positions are expressed in the mesh local space.
  14350. */
  14351. AbstractMesh.prototype.getFacetLocalPositions = function () {
  14352. if (!this._facetPositions) {
  14353. this.updateFacetData();
  14354. }
  14355. return this._facetPositions;
  14356. };
  14357. /**
  14358. * Returns the facetLocalPartioning array.
  14359. */
  14360. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14361. if (!this._facetPartitioning) {
  14362. this.updateFacetData();
  14363. }
  14364. return this._facetPartitioning;
  14365. };
  14366. /**
  14367. * Returns the i-th facet position in the world system.
  14368. * This method allocates a new Vector3 per call.
  14369. */
  14370. AbstractMesh.prototype.getFacetPosition = function (i) {
  14371. var pos = BABYLON.Vector3.Zero();
  14372. this.getFacetPositionToRef(i, pos);
  14373. return pos;
  14374. };
  14375. /**
  14376. * Sets the reference Vector3 with the i-th facet position in the world system.
  14377. * Returns the AbstractMesh.
  14378. */
  14379. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14380. var localPos = (this.getFacetLocalPositions())[i];
  14381. var world = this.getWorldMatrix();
  14382. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14383. return this;
  14384. };
  14385. /**
  14386. * Returns the i-th facet normal in the world system.
  14387. * This method allocates a new Vector3 per call.
  14388. */
  14389. AbstractMesh.prototype.getFacetNormal = function (i) {
  14390. var norm = BABYLON.Vector3.Zero();
  14391. this.getFacetNormalToRef(i, norm);
  14392. return norm;
  14393. };
  14394. /**
  14395. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14396. * Returns the AbstractMesh.
  14397. */
  14398. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14399. var localNorm = (this.getFacetLocalNormals())[i];
  14400. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14401. return this;
  14402. };
  14403. /**
  14404. * 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).
  14405. */
  14406. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14407. var bInfo = this.getBoundingInfo();
  14408. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14409. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14410. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14411. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14412. return null;
  14413. }
  14414. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14415. };
  14416. /**
  14417. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14418. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14419. * 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.
  14420. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14421. * 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.
  14422. */
  14423. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14424. if (checkFace === void 0) { checkFace = false; }
  14425. if (facing === void 0) { facing = true; }
  14426. var world = this.getWorldMatrix();
  14427. var invMat = BABYLON.Tmp.Matrix[5];
  14428. world.invertToRef(invMat);
  14429. var invVect = BABYLON.Tmp.Vector3[8];
  14430. var closest = null;
  14431. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14432. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14433. if (projected) {
  14434. // tranform the local computed projected vector to world coordinates
  14435. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  14436. }
  14437. return closest;
  14438. };
  14439. /**
  14440. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  14441. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  14442. * 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.
  14443. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14444. * 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.
  14445. */
  14446. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  14447. if (checkFace === void 0) { checkFace = false; }
  14448. if (facing === void 0) { facing = true; }
  14449. var closest = null;
  14450. var tmpx = 0.0;
  14451. var tmpy = 0.0;
  14452. var tmpz = 0.0;
  14453. var d = 0.0; // tmp dot facet normal * facet position
  14454. var t0 = 0.0;
  14455. var projx = 0.0;
  14456. var projy = 0.0;
  14457. var projz = 0.0;
  14458. // Get all the facets in the same partitioning block than (x, y, z)
  14459. var facetPositions = this.getFacetLocalPositions();
  14460. var facetNormals = this.getFacetLocalNormals();
  14461. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  14462. if (!facetsInBlock) {
  14463. return null;
  14464. }
  14465. // Get the closest facet to (x, y, z)
  14466. var shortest = Number.MAX_VALUE; // init distance vars
  14467. var tmpDistance = shortest;
  14468. var fib; // current facet in the block
  14469. var norm; // current facet normal
  14470. var p0; // current facet barycenter position
  14471. // loop on all the facets in the current partitioning block
  14472. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  14473. fib = facetsInBlock[idx];
  14474. norm = facetNormals[fib];
  14475. p0 = facetPositions[fib];
  14476. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  14477. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  14478. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  14479. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  14480. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  14481. projx = x + norm.x * t0;
  14482. projy = y + norm.y * t0;
  14483. projz = z + norm.z * t0;
  14484. tmpx = projx - x;
  14485. tmpy = projy - y;
  14486. tmpz = projz - z;
  14487. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  14488. if (tmpDistance < shortest) {
  14489. shortest = tmpDistance;
  14490. closest = fib;
  14491. if (projected) {
  14492. projected.x = projx;
  14493. projected.y = projy;
  14494. projected.z = projz;
  14495. }
  14496. }
  14497. }
  14498. }
  14499. return closest;
  14500. };
  14501. /**
  14502. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  14503. */
  14504. AbstractMesh.prototype.getFacetDataParameters = function () {
  14505. return this._facetParameters;
  14506. };
  14507. /**
  14508. * Disables the feature FacetData and frees the related memory.
  14509. * Returns the AbstractMesh.
  14510. */
  14511. AbstractMesh.prototype.disableFacetData = function () {
  14512. if (this._facetDataEnabled) {
  14513. this._facetDataEnabled = false;
  14514. this._facetPositions = null;
  14515. this._facetNormals = null;
  14516. this._facetPartitioning = null;
  14517. this._facetParameters = null;
  14518. }
  14519. return this;
  14520. };
  14521. /**
  14522. * Creates new normals data for the mesh.
  14523. * @param updatable.
  14524. */
  14525. AbstractMesh.prototype.createNormals = function (updatable) {
  14526. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14527. var indices = this.getIndices();
  14528. var normals;
  14529. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14530. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14531. }
  14532. else {
  14533. normals = [];
  14534. }
  14535. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  14536. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  14537. };
  14538. AbstractMesh.prototype.checkOcclusionQuery = function () {
  14539. var engine = this.getEngine();
  14540. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  14541. this._isOccluded = false;
  14542. return;
  14543. }
  14544. if (this.isOcclusionQueryInProgress) {
  14545. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  14546. if (isOcclusionQueryAvailable) {
  14547. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  14548. this._isOcclusionQueryInProgress = false;
  14549. this._occlusionInternalRetryCounter = 0;
  14550. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  14551. }
  14552. else {
  14553. this._occlusionInternalRetryCounter++;
  14554. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  14555. this._isOcclusionQueryInProgress = false;
  14556. this._occlusionInternalRetryCounter = 0;
  14557. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  14558. // if strict continue the last state of the object.
  14559. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  14560. }
  14561. else {
  14562. return;
  14563. }
  14564. }
  14565. }
  14566. var scene = this.getScene();
  14567. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  14568. if (!this._occlusionQuery) {
  14569. this._occlusionQuery = engine.createQuery();
  14570. }
  14571. engine.beginQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  14572. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  14573. engine.endQuery(this.occlusionQueryAlgorithmType);
  14574. this._isOcclusionQueryInProgress = true;
  14575. };
  14576. // Statics
  14577. AbstractMesh._BILLBOARDMODE_NONE = 0;
  14578. AbstractMesh._BILLBOARDMODE_X = 1;
  14579. AbstractMesh._BILLBOARDMODE_Y = 2;
  14580. AbstractMesh._BILLBOARDMODE_Z = 4;
  14581. AbstractMesh._BILLBOARDMODE_ALL = 7;
  14582. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  14583. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  14584. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  14585. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  14586. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  14587. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  14588. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14589. return AbstractMesh;
  14590. }(BABYLON.Node));
  14591. BABYLON.AbstractMesh = AbstractMesh;
  14592. })(BABYLON || (BABYLON = {}));
  14593. //# sourceMappingURL=babylon.abstractMesh.js.map
  14594. var BABYLON;
  14595. (function (BABYLON) {
  14596. var Light = (function (_super) {
  14597. __extends(Light, _super);
  14598. /**
  14599. * Creates a Light object in the scene.
  14600. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14601. */
  14602. function Light(name, scene) {
  14603. var _this = _super.call(this, name, scene) || this;
  14604. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  14605. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  14606. _this.intensity = 1.0;
  14607. _this.range = Number.MAX_VALUE;
  14608. /**
  14609. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  14610. * of light.
  14611. */
  14612. _this._photometricScale = 1.0;
  14613. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  14614. _this._radius = 0.00001;
  14615. _this.renderPriority = 0;
  14616. /**
  14617. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  14618. * the current shadow generator.
  14619. */
  14620. _this.shadowEnabled = true;
  14621. _this._excludeWithLayerMask = 0;
  14622. _this._includeOnlyWithLayerMask = 0;
  14623. _this._lightmapMode = 0;
  14624. _this._excludedMeshesIds = new Array();
  14625. _this._includedOnlyMeshesIds = new Array();
  14626. _this.getScene().addLight(_this);
  14627. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  14628. _this._buildUniformLayout();
  14629. _this.includedOnlyMeshes = new Array();
  14630. _this.excludedMeshes = new Array();
  14631. _this._resyncMeshes();
  14632. return _this;
  14633. }
  14634. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14635. /**
  14636. * If every light affecting the material is in this lightmapMode,
  14637. * material.lightmapTexture adds or multiplies
  14638. * (depends on material.useLightmapAsShadowmap)
  14639. * after every other light calculations.
  14640. */
  14641. get: function () {
  14642. return Light._LIGHTMAP_DEFAULT;
  14643. },
  14644. enumerable: true,
  14645. configurable: true
  14646. });
  14647. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14648. /**
  14649. * material.lightmapTexture as only diffuse lighting from this light
  14650. * adds pnly specular lighting from this light
  14651. * adds dynamic shadows
  14652. */
  14653. get: function () {
  14654. return Light._LIGHTMAP_SPECULAR;
  14655. },
  14656. enumerable: true,
  14657. configurable: true
  14658. });
  14659. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14660. /**
  14661. * material.lightmapTexture as only lighting
  14662. * no light calculation from this light
  14663. * only adds dynamic shadows from this light
  14664. */
  14665. get: function () {
  14666. return Light._LIGHTMAP_SHADOWSONLY;
  14667. },
  14668. enumerable: true,
  14669. configurable: true
  14670. });
  14671. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  14672. /**
  14673. * Each light type uses the default quantity according to its type:
  14674. * point/spot lights use luminous intensity
  14675. * directional lights use illuminance
  14676. */
  14677. get: function () {
  14678. return Light._INTENSITYMODE_AUTOMATIC;
  14679. },
  14680. enumerable: true,
  14681. configurable: true
  14682. });
  14683. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  14684. /**
  14685. * lumen (lm)
  14686. */
  14687. get: function () {
  14688. return Light._INTENSITYMODE_LUMINOUSPOWER;
  14689. },
  14690. enumerable: true,
  14691. configurable: true
  14692. });
  14693. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  14694. /**
  14695. * candela (lm/sr)
  14696. */
  14697. get: function () {
  14698. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  14699. },
  14700. enumerable: true,
  14701. configurable: true
  14702. });
  14703. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  14704. /**
  14705. * lux (lm/m^2)
  14706. */
  14707. get: function () {
  14708. return Light._INTENSITYMODE_ILLUMINANCE;
  14709. },
  14710. enumerable: true,
  14711. configurable: true
  14712. });
  14713. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  14714. /**
  14715. * nit (cd/m^2)
  14716. */
  14717. get: function () {
  14718. return Light._INTENSITYMODE_LUMINANCE;
  14719. },
  14720. enumerable: true,
  14721. configurable: true
  14722. });
  14723. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  14724. /**
  14725. * Light type const id of the point light.
  14726. */
  14727. get: function () {
  14728. return Light._LIGHTTYPEID_POINTLIGHT;
  14729. },
  14730. enumerable: true,
  14731. configurable: true
  14732. });
  14733. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  14734. /**
  14735. * Light type const id of the directional light.
  14736. */
  14737. get: function () {
  14738. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  14739. },
  14740. enumerable: true,
  14741. configurable: true
  14742. });
  14743. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  14744. /**
  14745. * Light type const id of the spot light.
  14746. */
  14747. get: function () {
  14748. return Light._LIGHTTYPEID_SPOTLIGHT;
  14749. },
  14750. enumerable: true,
  14751. configurable: true
  14752. });
  14753. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  14754. /**
  14755. * Light type const id of the hemispheric light.
  14756. */
  14757. get: function () {
  14758. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  14759. },
  14760. enumerable: true,
  14761. configurable: true
  14762. });
  14763. Object.defineProperty(Light.prototype, "intensityMode", {
  14764. /**
  14765. * Gets the photometric scale used to interpret the intensity.
  14766. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14767. */
  14768. get: function () {
  14769. return this._intensityMode;
  14770. },
  14771. /**
  14772. * Sets the photometric scale used to interpret the intensity.
  14773. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14774. */
  14775. set: function (value) {
  14776. this._intensityMode = value;
  14777. this._computePhotometricScale();
  14778. },
  14779. enumerable: true,
  14780. configurable: true
  14781. });
  14782. ;
  14783. ;
  14784. Object.defineProperty(Light.prototype, "radius", {
  14785. /**
  14786. * Gets the light radius used by PBR Materials to simulate soft area lights.
  14787. */
  14788. get: function () {
  14789. return this._radius;
  14790. },
  14791. /**
  14792. * sets the light radius used by PBR Materials to simulate soft area lights.
  14793. */
  14794. set: function (value) {
  14795. this._radius = value;
  14796. this._computePhotometricScale();
  14797. },
  14798. enumerable: true,
  14799. configurable: true
  14800. });
  14801. ;
  14802. ;
  14803. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14804. get: function () {
  14805. return this._includedOnlyMeshes;
  14806. },
  14807. set: function (value) {
  14808. this._includedOnlyMeshes = value;
  14809. this._hookArrayForIncludedOnly(value);
  14810. },
  14811. enumerable: true,
  14812. configurable: true
  14813. });
  14814. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14815. get: function () {
  14816. return this._excludedMeshes;
  14817. },
  14818. set: function (value) {
  14819. this._excludedMeshes = value;
  14820. this._hookArrayForExcluded(value);
  14821. },
  14822. enumerable: true,
  14823. configurable: true
  14824. });
  14825. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14826. get: function () {
  14827. return this._excludeWithLayerMask;
  14828. },
  14829. set: function (value) {
  14830. this._excludeWithLayerMask = value;
  14831. this._resyncMeshes();
  14832. },
  14833. enumerable: true,
  14834. configurable: true
  14835. });
  14836. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14837. get: function () {
  14838. return this._includeOnlyWithLayerMask;
  14839. },
  14840. set: function (value) {
  14841. this._includeOnlyWithLayerMask = value;
  14842. this._resyncMeshes();
  14843. },
  14844. enumerable: true,
  14845. configurable: true
  14846. });
  14847. Object.defineProperty(Light.prototype, "lightmapMode", {
  14848. get: function () {
  14849. return this._lightmapMode;
  14850. },
  14851. set: function (value) {
  14852. if (this._lightmapMode === value) {
  14853. return;
  14854. }
  14855. this._lightmapMode = value;
  14856. this._markMeshesAsLightDirty();
  14857. },
  14858. enumerable: true,
  14859. configurable: true
  14860. });
  14861. Light.prototype._buildUniformLayout = function () {
  14862. // Overridden
  14863. };
  14864. /**
  14865. * Returns the string "Light".
  14866. */
  14867. Light.prototype.getClassName = function () {
  14868. return "Light";
  14869. };
  14870. /**
  14871. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14872. */
  14873. Light.prototype.toString = function (fullDetails) {
  14874. var ret = "Name: " + this.name;
  14875. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14876. if (this.animations) {
  14877. for (var i = 0; i < this.animations.length; i++) {
  14878. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14879. }
  14880. }
  14881. if (fullDetails) {
  14882. }
  14883. return ret;
  14884. };
  14885. /**
  14886. * Set the enabled state of this node.
  14887. * @param {boolean} value - the new enabled state
  14888. * @see isEnabled
  14889. */
  14890. Light.prototype.setEnabled = function (value) {
  14891. _super.prototype.setEnabled.call(this, value);
  14892. this._resyncMeshes();
  14893. };
  14894. /**
  14895. * Returns the Light associated shadow generator.
  14896. */
  14897. Light.prototype.getShadowGenerator = function () {
  14898. return this._shadowGenerator;
  14899. };
  14900. /**
  14901. * Returns a Vector3, the absolute light position in the World.
  14902. */
  14903. Light.prototype.getAbsolutePosition = function () {
  14904. return BABYLON.Vector3.Zero();
  14905. };
  14906. Light.prototype.transferToEffect = function (effect, lightIndex) {
  14907. };
  14908. Light.prototype._getWorldMatrix = function () {
  14909. return BABYLON.Matrix.Identity();
  14910. };
  14911. /**
  14912. * Boolean : True if the light will affect the passed mesh.
  14913. */
  14914. Light.prototype.canAffectMesh = function (mesh) {
  14915. if (!mesh) {
  14916. return true;
  14917. }
  14918. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14919. return false;
  14920. }
  14921. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14922. return false;
  14923. }
  14924. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14925. return false;
  14926. }
  14927. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14928. return false;
  14929. }
  14930. return true;
  14931. };
  14932. /**
  14933. * Returns the light World matrix.
  14934. */
  14935. Light.prototype.getWorldMatrix = function () {
  14936. this._currentRenderId = this.getScene().getRenderId();
  14937. var worldMatrix = this._getWorldMatrix();
  14938. if (this.parent && this.parent.getWorldMatrix) {
  14939. if (!this._parentedWorldMatrix) {
  14940. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14941. }
  14942. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14943. this._markSyncedWithParent();
  14944. return this._parentedWorldMatrix;
  14945. }
  14946. return worldMatrix;
  14947. };
  14948. /**
  14949. * Sort function to order lights for rendering.
  14950. * @param a First Light object to compare to second.
  14951. * @param b Second Light object to compare first.
  14952. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  14953. */
  14954. Light.compareLightsPriority = function (a, b) {
  14955. //shadow-casting lights have priority over non-shadow-casting lights
  14956. //the renderPrioirty is a secondary sort criterion
  14957. if (a.shadowEnabled !== b.shadowEnabled) {
  14958. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  14959. }
  14960. return b.renderPriority - a.renderPriority;
  14961. };
  14962. /**
  14963. * Disposes the light.
  14964. */
  14965. Light.prototype.dispose = function () {
  14966. if (this._shadowGenerator) {
  14967. this._shadowGenerator.dispose();
  14968. this._shadowGenerator = null;
  14969. }
  14970. // Animations
  14971. this.getScene().stopAnimation(this);
  14972. // Remove from meshes
  14973. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14974. var mesh = _a[_i];
  14975. mesh._removeLightSource(this);
  14976. }
  14977. this._uniformBuffer.dispose();
  14978. // Remove from scene
  14979. this.getScene().removeLight(this);
  14980. _super.prototype.dispose.call(this);
  14981. };
  14982. /**
  14983. * Returns the light type ID (integer).
  14984. */
  14985. Light.prototype.getTypeID = function () {
  14986. return 0;
  14987. };
  14988. /**
  14989. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  14990. */
  14991. Light.prototype.getScaledIntensity = function () {
  14992. return this._photometricScale * this.intensity;
  14993. };
  14994. /**
  14995. * Returns a new Light object, named "name", from the current one.
  14996. */
  14997. Light.prototype.clone = function (name) {
  14998. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14999. };
  15000. /**
  15001. * Serializes the current light into a Serialization object.
  15002. * Returns the serialized object.
  15003. */
  15004. Light.prototype.serialize = function () {
  15005. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15006. // Type
  15007. serializationObject.type = this.getTypeID();
  15008. // Parent
  15009. if (this.parent) {
  15010. serializationObject.parentId = this.parent.id;
  15011. }
  15012. // Inclusion / exclusions
  15013. if (this.excludedMeshes.length > 0) {
  15014. serializationObject.excludedMeshesIds = [];
  15015. this.excludedMeshes.forEach(function (mesh) {
  15016. serializationObject.excludedMeshesIds.push(mesh.id);
  15017. });
  15018. }
  15019. if (this.includedOnlyMeshes.length > 0) {
  15020. serializationObject.includedOnlyMeshesIds = [];
  15021. this.includedOnlyMeshes.forEach(function (mesh) {
  15022. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  15023. });
  15024. }
  15025. // Animations
  15026. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15027. serializationObject.ranges = this.serializeAnimationRanges();
  15028. return serializationObject;
  15029. };
  15030. /**
  15031. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  15032. * This new light is named "name" and added to the passed scene.
  15033. */
  15034. Light.GetConstructorFromName = function (type, name, scene) {
  15035. switch (type) {
  15036. case 0:
  15037. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  15038. case 1:
  15039. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  15040. case 2:
  15041. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  15042. case 3:
  15043. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  15044. }
  15045. return null;
  15046. };
  15047. /**
  15048. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  15049. */
  15050. Light.Parse = function (parsedLight, scene) {
  15051. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  15052. // Inclusion / exclusions
  15053. if (parsedLight.excludedMeshesIds) {
  15054. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  15055. }
  15056. if (parsedLight.includedOnlyMeshesIds) {
  15057. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  15058. }
  15059. // Parent
  15060. if (parsedLight.parentId) {
  15061. light._waitingParentId = parsedLight.parentId;
  15062. }
  15063. // Animations
  15064. if (parsedLight.animations) {
  15065. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  15066. var parsedAnimation = parsedLight.animations[animationIndex];
  15067. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15068. }
  15069. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  15070. }
  15071. if (parsedLight.autoAnimate) {
  15072. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  15073. }
  15074. return light;
  15075. };
  15076. Light.prototype._hookArrayForExcluded = function (array) {
  15077. var _this = this;
  15078. var oldPush = array.push;
  15079. array.push = function () {
  15080. var items = [];
  15081. for (var _i = 0; _i < arguments.length; _i++) {
  15082. items[_i] = arguments[_i];
  15083. }
  15084. var result = oldPush.apply(array, items);
  15085. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  15086. var item = items_1[_a];
  15087. item._resyncLighSource(_this);
  15088. }
  15089. return result;
  15090. };
  15091. var oldSplice = array.splice;
  15092. array.splice = function (index, deleteCount) {
  15093. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15094. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  15095. var item = deleted_1[_i];
  15096. item._resyncLighSource(_this);
  15097. }
  15098. return deleted;
  15099. };
  15100. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  15101. var item = array_1[_i];
  15102. item._resyncLighSource(this);
  15103. }
  15104. };
  15105. Light.prototype._hookArrayForIncludedOnly = function (array) {
  15106. var _this = this;
  15107. var oldPush = array.push;
  15108. array.push = function () {
  15109. var items = [];
  15110. for (var _i = 0; _i < arguments.length; _i++) {
  15111. items[_i] = arguments[_i];
  15112. }
  15113. var result = oldPush.apply(array, items);
  15114. _this._resyncMeshes();
  15115. return result;
  15116. };
  15117. var oldSplice = array.splice;
  15118. array.splice = function (index, deleteCount) {
  15119. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15120. _this._resyncMeshes();
  15121. return deleted;
  15122. };
  15123. this._resyncMeshes();
  15124. };
  15125. Light.prototype._resyncMeshes = function () {
  15126. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15127. var mesh = _a[_i];
  15128. mesh._resyncLighSource(this);
  15129. }
  15130. };
  15131. Light.prototype._markMeshesAsLightDirty = function () {
  15132. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15133. var mesh = _a[_i];
  15134. if (mesh._lightSources.indexOf(this) !== -1) {
  15135. mesh._markSubMeshesAsLightDirty();
  15136. }
  15137. }
  15138. };
  15139. /**
  15140. * Recomputes the cached photometric scale if needed.
  15141. */
  15142. Light.prototype._computePhotometricScale = function () {
  15143. this._photometricScale = this._getPhotometricScale();
  15144. this.getScene().resetCachedMaterial();
  15145. };
  15146. /**
  15147. * Returns the Photometric Scale according to the light type and intensity mode.
  15148. */
  15149. Light.prototype._getPhotometricScale = function () {
  15150. var photometricScale = 0.0;
  15151. var lightTypeID = this.getTypeID();
  15152. //get photometric mode
  15153. var photometricMode = this.intensityMode;
  15154. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  15155. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  15156. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  15157. }
  15158. else {
  15159. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  15160. }
  15161. }
  15162. //compute photometric scale
  15163. switch (lightTypeID) {
  15164. case Light.LIGHTTYPEID_POINTLIGHT:
  15165. case Light.LIGHTTYPEID_SPOTLIGHT:
  15166. switch (photometricMode) {
  15167. case Light.INTENSITYMODE_LUMINOUSPOWER:
  15168. photometricScale = 1.0 / (4.0 * Math.PI);
  15169. break;
  15170. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  15171. photometricScale = 1.0;
  15172. break;
  15173. case Light.INTENSITYMODE_LUMINANCE:
  15174. photometricScale = this.radius * this.radius;
  15175. break;
  15176. }
  15177. break;
  15178. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  15179. switch (photometricMode) {
  15180. case Light.INTENSITYMODE_ILLUMINANCE:
  15181. photometricScale = 1.0;
  15182. break;
  15183. case Light.INTENSITYMODE_LUMINANCE:
  15184. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  15185. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  15186. var apexAngleRadians = this.radius;
  15187. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  15188. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  15189. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  15190. photometricScale = solidAngle;
  15191. break;
  15192. }
  15193. break;
  15194. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  15195. // No fall off in hemisperic light.
  15196. photometricScale = 1.0;
  15197. break;
  15198. }
  15199. return photometricScale;
  15200. };
  15201. Light.prototype._reorderLightsInScene = function () {
  15202. var scene = this.getScene();
  15203. if (this._renderPriority != 0) {
  15204. scene.requireLightSorting = true;
  15205. }
  15206. this.getScene().sortLightsByPriority();
  15207. };
  15208. //lightmapMode Consts
  15209. Light._LIGHTMAP_DEFAULT = 0;
  15210. Light._LIGHTMAP_SPECULAR = 1;
  15211. Light._LIGHTMAP_SHADOWSONLY = 2;
  15212. // Intensity Mode Consts
  15213. Light._INTENSITYMODE_AUTOMATIC = 0;
  15214. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  15215. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  15216. Light._INTENSITYMODE_ILLUMINANCE = 3;
  15217. Light._INTENSITYMODE_LUMINANCE = 4;
  15218. // Light types ids const.
  15219. Light._LIGHTTYPEID_POINTLIGHT = 0;
  15220. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  15221. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  15222. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  15223. __decorate([
  15224. BABYLON.serializeAsColor3()
  15225. ], Light.prototype, "diffuse", void 0);
  15226. __decorate([
  15227. BABYLON.serializeAsColor3()
  15228. ], Light.prototype, "specular", void 0);
  15229. __decorate([
  15230. BABYLON.serialize()
  15231. ], Light.prototype, "intensity", void 0);
  15232. __decorate([
  15233. BABYLON.serialize()
  15234. ], Light.prototype, "range", void 0);
  15235. __decorate([
  15236. BABYLON.serialize()
  15237. ], Light.prototype, "intensityMode", null);
  15238. __decorate([
  15239. BABYLON.serialize()
  15240. ], Light.prototype, "radius", null);
  15241. __decorate([
  15242. BABYLON.serialize()
  15243. ], Light.prototype, "_renderPriority", void 0);
  15244. __decorate([
  15245. BABYLON.expandToProperty("_reorderLightsInScene")
  15246. ], Light.prototype, "renderPriority", void 0);
  15247. __decorate([
  15248. BABYLON.serialize()
  15249. ], Light.prototype, "shadowEnabled", void 0);
  15250. __decorate([
  15251. BABYLON.serialize("excludeWithLayerMask")
  15252. ], Light.prototype, "_excludeWithLayerMask", void 0);
  15253. __decorate([
  15254. BABYLON.serialize("includeOnlyWithLayerMask")
  15255. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  15256. __decorate([
  15257. BABYLON.serialize("lightmapMode")
  15258. ], Light.prototype, "_lightmapMode", void 0);
  15259. return Light;
  15260. }(BABYLON.Node));
  15261. BABYLON.Light = Light;
  15262. })(BABYLON || (BABYLON = {}));
  15263. //# sourceMappingURL=babylon.light.js.map
  15264. var BABYLON;
  15265. (function (BABYLON) {
  15266. var Camera = (function (_super) {
  15267. __extends(Camera, _super);
  15268. function Camera(name, position, scene) {
  15269. var _this = _super.call(this, name, scene) || this;
  15270. _this.upVector = BABYLON.Vector3.Up();
  15271. _this.orthoLeft = null;
  15272. _this.orthoRight = null;
  15273. _this.orthoBottom = null;
  15274. _this.orthoTop = null;
  15275. _this.fov = 0.8;
  15276. _this.minZ = 1;
  15277. _this.maxZ = 10000.0;
  15278. _this.inertia = 0.9;
  15279. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15280. _this.isIntermediate = false;
  15281. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15282. _this.layerMask = 0x0FFFFFFF;
  15283. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15284. // Camera rig members
  15285. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15286. _this._rigCameras = new Array();
  15287. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15288. _this._skipRendering = false;
  15289. _this.customRenderTargets = new Array();
  15290. // Observables
  15291. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  15292. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  15293. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  15294. _this.onRestoreStateObservable = new BABYLON.Observable();
  15295. // Cache
  15296. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15297. _this._projectionMatrix = new BABYLON.Matrix();
  15298. _this._doNotComputeProjectionMatrix = false;
  15299. _this._postProcesses = new Array();
  15300. _this._transformMatrix = BABYLON.Matrix.Zero();
  15301. _this._activeMeshes = new BABYLON.SmartArray(256);
  15302. _this._globalPosition = BABYLON.Vector3.Zero();
  15303. _this._refreshFrustumPlanes = true;
  15304. _this.getScene().addCamera(_this);
  15305. if (!_this.getScene().activeCamera) {
  15306. _this.getScene().activeCamera = _this;
  15307. }
  15308. _this.position = position;
  15309. return _this;
  15310. }
  15311. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15312. get: function () {
  15313. return Camera._PERSPECTIVE_CAMERA;
  15314. },
  15315. enumerable: true,
  15316. configurable: true
  15317. });
  15318. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15319. get: function () {
  15320. return Camera._ORTHOGRAPHIC_CAMERA;
  15321. },
  15322. enumerable: true,
  15323. configurable: true
  15324. });
  15325. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15326. get: function () {
  15327. return Camera._FOVMODE_VERTICAL_FIXED;
  15328. },
  15329. enumerable: true,
  15330. configurable: true
  15331. });
  15332. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15333. get: function () {
  15334. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15335. },
  15336. enumerable: true,
  15337. configurable: true
  15338. });
  15339. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15340. get: function () {
  15341. return Camera._RIG_MODE_NONE;
  15342. },
  15343. enumerable: true,
  15344. configurable: true
  15345. });
  15346. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15347. get: function () {
  15348. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15349. },
  15350. enumerable: true,
  15351. configurable: true
  15352. });
  15353. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15354. get: function () {
  15355. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15356. },
  15357. enumerable: true,
  15358. configurable: true
  15359. });
  15360. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15361. get: function () {
  15362. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15363. },
  15364. enumerable: true,
  15365. configurable: true
  15366. });
  15367. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15368. get: function () {
  15369. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15370. },
  15371. enumerable: true,
  15372. configurable: true
  15373. });
  15374. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15375. get: function () {
  15376. return Camera._RIG_MODE_VR;
  15377. },
  15378. enumerable: true,
  15379. configurable: true
  15380. });
  15381. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15382. get: function () {
  15383. return Camera._RIG_MODE_WEBVR;
  15384. },
  15385. enumerable: true,
  15386. configurable: true
  15387. });
  15388. /**
  15389. * Store current camera state (fov, position, etc..)
  15390. */
  15391. Camera.prototype.storeState = function () {
  15392. this._stateStored = true;
  15393. this._storedFov = this.fov;
  15394. return this;
  15395. };
  15396. /**
  15397. * Restores the camera state values if it has been stored. You must call storeState() first
  15398. */
  15399. Camera.prototype._restoreStateValues = function () {
  15400. if (!this._stateStored) {
  15401. return false;
  15402. }
  15403. this.fov = this._storedFov;
  15404. return true;
  15405. };
  15406. /**
  15407. * Restored camera state. You must call storeState() first
  15408. */
  15409. Camera.prototype.restoreState = function () {
  15410. if (this._restoreStateValues()) {
  15411. this.onRestoreStateObservable.notifyObservers(this);
  15412. return true;
  15413. }
  15414. return false;
  15415. };
  15416. Camera.prototype.getClassName = function () {
  15417. return "Camera";
  15418. };
  15419. /**
  15420. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15421. */
  15422. Camera.prototype.toString = function (fullDetails) {
  15423. var ret = "Name: " + this.name;
  15424. ret += ", type: " + this.getClassName();
  15425. if (this.animations) {
  15426. for (var i = 0; i < this.animations.length; i++) {
  15427. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15428. }
  15429. }
  15430. if (fullDetails) {
  15431. }
  15432. return ret;
  15433. };
  15434. Object.defineProperty(Camera.prototype, "globalPosition", {
  15435. get: function () {
  15436. return this._globalPosition;
  15437. },
  15438. enumerable: true,
  15439. configurable: true
  15440. });
  15441. Camera.prototype.getActiveMeshes = function () {
  15442. return this._activeMeshes;
  15443. };
  15444. Camera.prototype.isActiveMesh = function (mesh) {
  15445. return (this._activeMeshes.indexOf(mesh) !== -1);
  15446. };
  15447. //Cache
  15448. Camera.prototype._initCache = function () {
  15449. _super.prototype._initCache.call(this);
  15450. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15451. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15452. this._cache.mode = undefined;
  15453. this._cache.minZ = undefined;
  15454. this._cache.maxZ = undefined;
  15455. this._cache.fov = undefined;
  15456. this._cache.fovMode = undefined;
  15457. this._cache.aspectRatio = undefined;
  15458. this._cache.orthoLeft = undefined;
  15459. this._cache.orthoRight = undefined;
  15460. this._cache.orthoBottom = undefined;
  15461. this._cache.orthoTop = undefined;
  15462. this._cache.renderWidth = undefined;
  15463. this._cache.renderHeight = undefined;
  15464. };
  15465. Camera.prototype._updateCache = function (ignoreParentClass) {
  15466. if (!ignoreParentClass) {
  15467. _super.prototype._updateCache.call(this);
  15468. }
  15469. this._cache.position.copyFrom(this.position);
  15470. this._cache.upVector.copyFrom(this.upVector);
  15471. };
  15472. // Synchronized
  15473. Camera.prototype._isSynchronized = function () {
  15474. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15475. };
  15476. Camera.prototype._isSynchronizedViewMatrix = function () {
  15477. if (!_super.prototype._isSynchronized.call(this))
  15478. return false;
  15479. return this._cache.position.equals(this.position)
  15480. && this._cache.upVector.equals(this.upVector)
  15481. && this.isSynchronizedWithParent();
  15482. };
  15483. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15484. var check = this._cache.mode === this.mode
  15485. && this._cache.minZ === this.minZ
  15486. && this._cache.maxZ === this.maxZ;
  15487. if (!check) {
  15488. return false;
  15489. }
  15490. var engine = this.getEngine();
  15491. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15492. check = this._cache.fov === this.fov
  15493. && this._cache.fovMode === this.fovMode
  15494. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15495. }
  15496. else {
  15497. check = this._cache.orthoLeft === this.orthoLeft
  15498. && this._cache.orthoRight === this.orthoRight
  15499. && this._cache.orthoBottom === this.orthoBottom
  15500. && this._cache.orthoTop === this.orthoTop
  15501. && this._cache.renderWidth === engine.getRenderWidth()
  15502. && this._cache.renderHeight === engine.getRenderHeight();
  15503. }
  15504. return check;
  15505. };
  15506. // Controls
  15507. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15508. };
  15509. Camera.prototype.detachControl = function (element) {
  15510. };
  15511. Camera.prototype.update = function () {
  15512. this._checkInputs();
  15513. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15514. this._updateRigCameras();
  15515. }
  15516. };
  15517. Camera.prototype._checkInputs = function () {
  15518. this.onAfterCheckInputsObservable.notifyObservers(this);
  15519. };
  15520. Object.defineProperty(Camera.prototype, "rigCameras", {
  15521. get: function () {
  15522. return this._rigCameras;
  15523. },
  15524. enumerable: true,
  15525. configurable: true
  15526. });
  15527. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  15528. get: function () {
  15529. return this._rigPostProcess;
  15530. },
  15531. enumerable: true,
  15532. configurable: true
  15533. });
  15534. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15535. // invalidate framebuffer
  15536. if (this._postProcesses.length > 0) {
  15537. this._postProcesses[0].markTextureDirty();
  15538. }
  15539. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15540. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15541. var cam = this._rigCameras[i];
  15542. var rigPostProcess = cam._rigPostProcess;
  15543. // for VR rig, there does not have to be a post process
  15544. if (rigPostProcess) {
  15545. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15546. if (isPass) {
  15547. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15548. cam.isIntermediate = this._postProcesses.length === 0;
  15549. }
  15550. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15551. rigPostProcess.markTextureDirty();
  15552. }
  15553. else {
  15554. cam._postProcesses = this._postProcesses.slice(0);
  15555. }
  15556. }
  15557. };
  15558. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15559. if (insertAt === void 0) { insertAt = null; }
  15560. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15561. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15562. return 0;
  15563. }
  15564. if (insertAt == null || insertAt < 0) {
  15565. this._postProcesses.push(postProcess);
  15566. }
  15567. else {
  15568. this._postProcesses.splice(insertAt, 0, postProcess);
  15569. }
  15570. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15571. return this._postProcesses.indexOf(postProcess);
  15572. };
  15573. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15574. if (atIndices === void 0) { atIndices = null; }
  15575. var result = [];
  15576. var i;
  15577. var index;
  15578. if (!atIndices) {
  15579. var idx = this._postProcesses.indexOf(postProcess);
  15580. if (idx !== -1) {
  15581. this._postProcesses.splice(idx, 1);
  15582. }
  15583. }
  15584. else {
  15585. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15586. // iterate descending, so can just splice as we go
  15587. for (i = atIndices.length - 1; i >= 0; i--) {
  15588. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15589. result.push(i);
  15590. continue;
  15591. }
  15592. index = atIndices[i];
  15593. this._postProcesses.splice(index, 1);
  15594. }
  15595. }
  15596. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15597. return result;
  15598. };
  15599. Camera.prototype.getWorldMatrix = function () {
  15600. if (!this._worldMatrix) {
  15601. this._worldMatrix = BABYLON.Matrix.Identity();
  15602. }
  15603. var viewMatrix = this.getViewMatrix();
  15604. viewMatrix.invertToRef(this._worldMatrix);
  15605. return this._worldMatrix;
  15606. };
  15607. Camera.prototype._getViewMatrix = function () {
  15608. return BABYLON.Matrix.Identity();
  15609. };
  15610. Camera.prototype.getViewMatrix = function (force) {
  15611. if (!force && this._isSynchronizedViewMatrix()) {
  15612. return this._computedViewMatrix;
  15613. }
  15614. this.updateCache();
  15615. this._computedViewMatrix = this._getViewMatrix();
  15616. this._currentRenderId = this.getScene().getRenderId();
  15617. this._refreshFrustumPlanes = true;
  15618. if (!this.parent || !this.parent.getWorldMatrix) {
  15619. this._globalPosition.copyFrom(this.position);
  15620. }
  15621. else {
  15622. if (!this._worldMatrix) {
  15623. this._worldMatrix = BABYLON.Matrix.Identity();
  15624. }
  15625. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15626. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15627. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15628. this._computedViewMatrix.invert();
  15629. this._markSyncedWithParent();
  15630. }
  15631. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15632. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15633. }
  15634. this.onViewMatrixChangedObservable.notifyObservers(this);
  15635. return this._computedViewMatrix;
  15636. };
  15637. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15638. this._doNotComputeProjectionMatrix = true;
  15639. if (projection !== undefined) {
  15640. this._projectionMatrix = projection;
  15641. }
  15642. };
  15643. ;
  15644. Camera.prototype.unfreezeProjectionMatrix = function () {
  15645. this._doNotComputeProjectionMatrix = false;
  15646. };
  15647. ;
  15648. Camera.prototype.getProjectionMatrix = function (force) {
  15649. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15650. return this._projectionMatrix;
  15651. }
  15652. // Cache
  15653. this._cache.mode = this.mode;
  15654. this._cache.minZ = this.minZ;
  15655. this._cache.maxZ = this.maxZ;
  15656. // Matrix
  15657. this._refreshFrustumPlanes = true;
  15658. var engine = this.getEngine();
  15659. var scene = this.getScene();
  15660. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15661. this._cache.fov = this.fov;
  15662. this._cache.fovMode = this.fovMode;
  15663. this._cache.aspectRatio = engine.getAspectRatio(this);
  15664. if (this.minZ <= 0) {
  15665. this.minZ = 0.1;
  15666. }
  15667. if (scene.useRightHandedSystem) {
  15668. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15669. }
  15670. else {
  15671. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15672. }
  15673. }
  15674. else {
  15675. var halfWidth = engine.getRenderWidth() / 2.0;
  15676. var halfHeight = engine.getRenderHeight() / 2.0;
  15677. if (scene.useRightHandedSystem) {
  15678. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15679. }
  15680. else {
  15681. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15682. }
  15683. this._cache.orthoLeft = this.orthoLeft;
  15684. this._cache.orthoRight = this.orthoRight;
  15685. this._cache.orthoBottom = this.orthoBottom;
  15686. this._cache.orthoTop = this.orthoTop;
  15687. this._cache.renderWidth = engine.getRenderWidth();
  15688. this._cache.renderHeight = engine.getRenderHeight();
  15689. }
  15690. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  15691. return this._projectionMatrix;
  15692. };
  15693. Camera.prototype.getTranformationMatrix = function () {
  15694. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15695. return this._transformMatrix;
  15696. };
  15697. Camera.prototype.updateFrustumPlanes = function () {
  15698. if (!this._refreshFrustumPlanes) {
  15699. return;
  15700. }
  15701. this.getTranformationMatrix();
  15702. if (!this._frustumPlanes) {
  15703. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15704. }
  15705. else {
  15706. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15707. }
  15708. this._refreshFrustumPlanes = false;
  15709. };
  15710. Camera.prototype.isInFrustum = function (target) {
  15711. this.updateFrustumPlanes();
  15712. return target.isInFrustum(this._frustumPlanes);
  15713. };
  15714. Camera.prototype.isCompletelyInFrustum = function (target) {
  15715. this.updateFrustumPlanes();
  15716. return target.isCompletelyInFrustum(this._frustumPlanes);
  15717. };
  15718. Camera.prototype.getForwardRay = function (length, transform, origin) {
  15719. if (length === void 0) { length = 100; }
  15720. if (!transform) {
  15721. transform = this.getWorldMatrix();
  15722. }
  15723. if (!origin) {
  15724. origin = this.position;
  15725. }
  15726. var forward = new BABYLON.Vector3(0, 0, 1);
  15727. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  15728. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  15729. return new BABYLON.Ray(origin, direction, length);
  15730. };
  15731. Camera.prototype.dispose = function () {
  15732. // Observables
  15733. this.onViewMatrixChangedObservable.clear();
  15734. this.onProjectionMatrixChangedObservable.clear();
  15735. this.onAfterCheckInputsObservable.clear();
  15736. this.onRestoreStateObservable.clear();
  15737. // Inputs
  15738. if (this.inputs) {
  15739. this.inputs.clear();
  15740. }
  15741. // Animations
  15742. this.getScene().stopAnimation(this);
  15743. // Remove from scene
  15744. this.getScene().removeCamera(this);
  15745. while (this._rigCameras.length > 0) {
  15746. this._rigCameras.pop().dispose();
  15747. }
  15748. // Postprocesses
  15749. if (this._rigPostProcess) {
  15750. this._rigPostProcess.dispose(this);
  15751. this._rigPostProcess = null;
  15752. this._postProcesses = [];
  15753. }
  15754. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15755. this._rigPostProcess = null;
  15756. this._postProcesses = [];
  15757. }
  15758. else {
  15759. var i = this._postProcesses.length;
  15760. while (--i >= 0) {
  15761. this._postProcesses[i].dispose(this);
  15762. }
  15763. }
  15764. // Render targets
  15765. var i = this.customRenderTargets.length;
  15766. while (--i >= 0) {
  15767. this.customRenderTargets[i].dispose();
  15768. }
  15769. this.customRenderTargets = [];
  15770. // Active Meshes
  15771. this._activeMeshes.dispose();
  15772. _super.prototype.dispose.call(this);
  15773. };
  15774. Object.defineProperty(Camera.prototype, "leftCamera", {
  15775. // ---- Camera rigs section ----
  15776. get: function () {
  15777. if (this._rigCameras.length < 1) {
  15778. return undefined;
  15779. }
  15780. return this._rigCameras[0];
  15781. },
  15782. enumerable: true,
  15783. configurable: true
  15784. });
  15785. Object.defineProperty(Camera.prototype, "rightCamera", {
  15786. get: function () {
  15787. if (this._rigCameras.length < 2) {
  15788. return undefined;
  15789. }
  15790. return this._rigCameras[1];
  15791. },
  15792. enumerable: true,
  15793. configurable: true
  15794. });
  15795. Camera.prototype.getLeftTarget = function () {
  15796. if (this._rigCameras.length < 1) {
  15797. return undefined;
  15798. }
  15799. return this._rigCameras[0].getTarget();
  15800. };
  15801. Camera.prototype.getRightTarget = function () {
  15802. if (this._rigCameras.length < 2) {
  15803. return undefined;
  15804. }
  15805. return this._rigCameras[1].getTarget();
  15806. };
  15807. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15808. if (this.cameraRigMode === mode) {
  15809. return;
  15810. }
  15811. while (this._rigCameras.length > 0) {
  15812. this._rigCameras.pop().dispose();
  15813. }
  15814. this.cameraRigMode = mode;
  15815. this._cameraRigParams = {};
  15816. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15817. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15818. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15819. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15820. // create the rig cameras, unless none
  15821. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15822. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15823. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15824. }
  15825. switch (this.cameraRigMode) {
  15826. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15827. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15828. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15829. break;
  15830. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15831. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15832. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15833. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15834. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15835. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15836. break;
  15837. case Camera.RIG_MODE_VR:
  15838. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15839. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15840. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15841. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15842. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15843. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15844. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15845. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  15846. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15847. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15848. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  15849. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  15850. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  15851. if (metrics.compensateDistortion) {
  15852. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  15853. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  15854. }
  15855. break;
  15856. case Camera.RIG_MODE_WEBVR:
  15857. if (rigParams.vrDisplay) {
  15858. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  15859. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  15860. //Left eye
  15861. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15862. this._rigCameras[0].setCameraRigParameter("left", true);
  15863. //leaving this for future reference
  15864. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  15865. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  15866. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  15867. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15868. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15869. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15870. this._rigCameras[0].parent = this;
  15871. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15872. //Right eye
  15873. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15874. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  15875. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  15876. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15877. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15878. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15879. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15880. this._rigCameras[1].parent = this;
  15881. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  15882. if (Camera.UseAlternateWebVRRendering) {
  15883. this._rigCameras[1]._skipRendering = true;
  15884. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  15885. }
  15886. }
  15887. break;
  15888. }
  15889. this._cascadePostProcessesToRigCams();
  15890. this.update();
  15891. };
  15892. Camera.prototype._getVRProjectionMatrix = function () {
  15893. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15894. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15895. return this._projectionMatrix;
  15896. };
  15897. Camera.prototype._updateCameraRotationMatrix = function () {
  15898. //Here for WebVR
  15899. };
  15900. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  15901. //Here for WebVR
  15902. };
  15903. /**
  15904. * This function MUST be overwritten by the different WebVR cameras available.
  15905. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15906. */
  15907. Camera.prototype._getWebVRProjectionMatrix = function () {
  15908. return BABYLON.Matrix.Identity();
  15909. };
  15910. /**
  15911. * This function MUST be overwritten by the different WebVR cameras available.
  15912. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15913. */
  15914. Camera.prototype._getWebVRViewMatrix = function () {
  15915. return BABYLON.Matrix.Identity();
  15916. };
  15917. Camera.prototype.setCameraRigParameter = function (name, value) {
  15918. if (!this._cameraRigParams) {
  15919. this._cameraRigParams = {};
  15920. }
  15921. this._cameraRigParams[name] = value;
  15922. //provisionnally:
  15923. if (name === "interaxialDistance") {
  15924. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  15925. }
  15926. };
  15927. /**
  15928. * needs to be overridden by children so sub has required properties to be copied
  15929. */
  15930. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  15931. return null;
  15932. };
  15933. /**
  15934. * May need to be overridden by children
  15935. */
  15936. Camera.prototype._updateRigCameras = function () {
  15937. for (var i = 0; i < this._rigCameras.length; i++) {
  15938. this._rigCameras[i].minZ = this.minZ;
  15939. this._rigCameras[i].maxZ = this.maxZ;
  15940. this._rigCameras[i].fov = this.fov;
  15941. }
  15942. // only update viewport when ANAGLYPH
  15943. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15944. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15945. }
  15946. };
  15947. Camera.prototype._setupInputs = function () {
  15948. };
  15949. Camera.prototype.serialize = function () {
  15950. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15951. // Type
  15952. serializationObject.type = this.getClassName();
  15953. // Parent
  15954. if (this.parent) {
  15955. serializationObject.parentId = this.parent.id;
  15956. }
  15957. if (this.inputs) {
  15958. this.inputs.serialize(serializationObject);
  15959. }
  15960. // Animations
  15961. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15962. serializationObject.ranges = this.serializeAnimationRanges();
  15963. return serializationObject;
  15964. };
  15965. Camera.prototype.clone = function (name) {
  15966. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15967. };
  15968. Camera.prototype.getDirection = function (localAxis) {
  15969. var result = BABYLON.Vector3.Zero();
  15970. this.getDirectionToRef(localAxis, result);
  15971. return result;
  15972. };
  15973. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15974. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15975. };
  15976. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15977. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15978. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15979. switch (type) {
  15980. case "ArcRotateCamera":
  15981. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  15982. case "DeviceOrientationCamera":
  15983. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  15984. case "FollowCamera":
  15985. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  15986. case "ArcFollowCamera":
  15987. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  15988. case "GamepadCamera":
  15989. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15990. case "TouchCamera":
  15991. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  15992. case "VirtualJoysticksCamera":
  15993. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  15994. case "WebVRFreeCamera":
  15995. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15996. case "WebVRGamepadCamera":
  15997. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15998. case "VRDeviceOrientationFreeCamera":
  15999. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16000. case "VRDeviceOrientationGamepadCamera":
  16001. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16002. case "AnaglyphArcRotateCamera":
  16003. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16004. case "AnaglyphFreeCamera":
  16005. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16006. case "AnaglyphGamepadCamera":
  16007. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16008. case "AnaglyphUniversalCamera":
  16009. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16010. case "StereoscopicArcRotateCamera":
  16011. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16012. case "StereoscopicFreeCamera":
  16013. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16014. case "StereoscopicGamepadCamera":
  16015. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16016. case "StereoscopicUniversalCamera":
  16017. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16018. case "FreeCamera":// Forcing Universal here
  16019. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16020. default:// Universal Camera is the default value
  16021. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16022. }
  16023. };
  16024. Camera.Parse = function (parsedCamera, scene) {
  16025. var type = parsedCamera.type;
  16026. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16027. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16028. // Parent
  16029. if (parsedCamera.parentId) {
  16030. camera._waitingParentId = parsedCamera.parentId;
  16031. }
  16032. //If camera has an input manager, let it parse inputs settings
  16033. if (camera.inputs) {
  16034. camera.inputs.parse(parsedCamera);
  16035. camera._setupInputs();
  16036. }
  16037. if (camera.setPosition) {
  16038. camera.position.copyFromFloats(0, 0, 0);
  16039. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  16040. }
  16041. // Target
  16042. if (parsedCamera.target) {
  16043. if (camera.setTarget) {
  16044. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16045. }
  16046. }
  16047. // Apply 3d rig, when found
  16048. if (parsedCamera.cameraRigMode) {
  16049. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16050. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16051. }
  16052. // Animations
  16053. if (parsedCamera.animations) {
  16054. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16055. var parsedAnimation = parsedCamera.animations[animationIndex];
  16056. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16057. }
  16058. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16059. }
  16060. if (parsedCamera.autoAnimate) {
  16061. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16062. }
  16063. return camera;
  16064. };
  16065. // Statics
  16066. Camera._PERSPECTIVE_CAMERA = 0;
  16067. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16068. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16069. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16070. Camera._RIG_MODE_NONE = 0;
  16071. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16072. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16073. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16074. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16075. Camera._RIG_MODE_VR = 20;
  16076. Camera._RIG_MODE_WEBVR = 21;
  16077. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16078. Camera.UseAlternateWebVRRendering = false;
  16079. __decorate([
  16080. BABYLON.serializeAsVector3()
  16081. ], Camera.prototype, "position", void 0);
  16082. __decorate([
  16083. BABYLON.serializeAsVector3()
  16084. ], Camera.prototype, "upVector", void 0);
  16085. __decorate([
  16086. BABYLON.serialize()
  16087. ], Camera.prototype, "orthoLeft", void 0);
  16088. __decorate([
  16089. BABYLON.serialize()
  16090. ], Camera.prototype, "orthoRight", void 0);
  16091. __decorate([
  16092. BABYLON.serialize()
  16093. ], Camera.prototype, "orthoBottom", void 0);
  16094. __decorate([
  16095. BABYLON.serialize()
  16096. ], Camera.prototype, "orthoTop", void 0);
  16097. __decorate([
  16098. BABYLON.serialize()
  16099. ], Camera.prototype, "fov", void 0);
  16100. __decorate([
  16101. BABYLON.serialize()
  16102. ], Camera.prototype, "minZ", void 0);
  16103. __decorate([
  16104. BABYLON.serialize()
  16105. ], Camera.prototype, "maxZ", void 0);
  16106. __decorate([
  16107. BABYLON.serialize()
  16108. ], Camera.prototype, "inertia", void 0);
  16109. __decorate([
  16110. BABYLON.serialize()
  16111. ], Camera.prototype, "mode", void 0);
  16112. __decorate([
  16113. BABYLON.serialize()
  16114. ], Camera.prototype, "layerMask", void 0);
  16115. __decorate([
  16116. BABYLON.serialize()
  16117. ], Camera.prototype, "fovMode", void 0);
  16118. __decorate([
  16119. BABYLON.serialize()
  16120. ], Camera.prototype, "cameraRigMode", void 0);
  16121. __decorate([
  16122. BABYLON.serialize()
  16123. ], Camera.prototype, "interaxialDistance", void 0);
  16124. __decorate([
  16125. BABYLON.serialize()
  16126. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16127. return Camera;
  16128. }(BABYLON.Node));
  16129. BABYLON.Camera = Camera;
  16130. })(BABYLON || (BABYLON = {}));
  16131. //# sourceMappingURL=babylon.camera.js.map
  16132. var BABYLON;
  16133. (function (BABYLON) {
  16134. var RenderingManager = (function () {
  16135. function RenderingManager(scene) {
  16136. this._renderingGroups = new Array();
  16137. this._autoClearDepthStencil = {};
  16138. this._customOpaqueSortCompareFn = {};
  16139. this._customAlphaTestSortCompareFn = {};
  16140. this._customTransparentSortCompareFn = {};
  16141. this._renderinGroupInfo = null;
  16142. this._scene = scene;
  16143. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16144. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16145. }
  16146. }
  16147. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16148. if (depth === void 0) { depth = true; }
  16149. if (stencil === void 0) { stencil = true; }
  16150. if (this._depthStencilBufferAlreadyCleaned) {
  16151. return;
  16152. }
  16153. this._scene.getEngine().clear(null, false, depth, stencil);
  16154. this._depthStencilBufferAlreadyCleaned = true;
  16155. };
  16156. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16157. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16158. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16159. var info = null;
  16160. if (observable) {
  16161. if (!this._renderinGroupInfo) {
  16162. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16163. }
  16164. info = this._renderinGroupInfo;
  16165. info.scene = this._scene;
  16166. info.camera = this._scene.activeCamera;
  16167. }
  16168. // Dispatch sprites
  16169. if (renderSprites) {
  16170. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  16171. var manager = this._scene.spriteManagers[index];
  16172. this.dispatchSprites(manager);
  16173. }
  16174. }
  16175. // Render
  16176. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16177. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16178. var renderingGroup = this._renderingGroups[index];
  16179. if (!renderingGroup && !observable)
  16180. continue;
  16181. this._currentIndex = index;
  16182. var renderingGroupMask = 0;
  16183. // Fire PRECLEAR stage
  16184. if (observable) {
  16185. renderingGroupMask = Math.pow(2, index);
  16186. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16187. info.renderingGroupId = index;
  16188. observable.notifyObservers(info, renderingGroupMask);
  16189. }
  16190. // Clear depth/stencil if needed
  16191. if (RenderingManager.AUTOCLEAR) {
  16192. var autoClear = this._autoClearDepthStencil[index];
  16193. if (autoClear && autoClear.autoClear) {
  16194. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16195. }
  16196. }
  16197. if (observable) {
  16198. // Fire PREOPAQUE stage
  16199. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16200. observable.notifyObservers(info, renderingGroupMask);
  16201. // Fire PRETRANSPARENT stage
  16202. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16203. observable.notifyObservers(info, renderingGroupMask);
  16204. }
  16205. if (renderingGroup)
  16206. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16207. // Fire POSTTRANSPARENT stage
  16208. if (observable) {
  16209. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16210. observable.notifyObservers(info, renderingGroupMask);
  16211. }
  16212. }
  16213. };
  16214. RenderingManager.prototype.reset = function () {
  16215. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16216. var renderingGroup = this._renderingGroups[index];
  16217. if (renderingGroup) {
  16218. renderingGroup.prepare();
  16219. }
  16220. }
  16221. };
  16222. RenderingManager.prototype.dispose = function () {
  16223. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16224. var renderingGroup = this._renderingGroups[index];
  16225. if (renderingGroup) {
  16226. renderingGroup.dispose();
  16227. }
  16228. }
  16229. this._renderingGroups.length = 0;
  16230. };
  16231. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16232. if (!this._renderingGroups[renderingGroupId]) {
  16233. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16234. }
  16235. };
  16236. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16237. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16238. this._prepareRenderingGroup(renderingGroupId);
  16239. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16240. };
  16241. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16242. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16243. this._prepareRenderingGroup(renderingGroupId);
  16244. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16245. };
  16246. RenderingManager.prototype.dispatch = function (subMesh) {
  16247. var mesh = subMesh.getMesh();
  16248. var renderingGroupId = mesh.renderingGroupId || 0;
  16249. this._prepareRenderingGroup(renderingGroupId);
  16250. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16251. };
  16252. /**
  16253. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16254. * This allowed control for front to back rendering or reversly depending of the special needs.
  16255. *
  16256. * @param renderingGroupId The rendering group id corresponding to its index
  16257. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16258. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16259. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16260. */
  16261. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16262. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16263. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16264. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16265. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16266. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16267. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16268. if (this._renderingGroups[renderingGroupId]) {
  16269. var group = this._renderingGroups[renderingGroupId];
  16270. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16271. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16272. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16273. }
  16274. };
  16275. /**
  16276. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16277. *
  16278. * @param renderingGroupId The rendering group id corresponding to its index
  16279. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16280. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16281. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16282. */
  16283. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16284. if (depth === void 0) { depth = true; }
  16285. if (stencil === void 0) { stencil = true; }
  16286. this._autoClearDepthStencil[renderingGroupId] = {
  16287. autoClear: autoClearDepthStencil,
  16288. depth: depth,
  16289. stencil: stencil
  16290. };
  16291. };
  16292. /**
  16293. * The max id used for rendering groups (not included)
  16294. */
  16295. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16296. /**
  16297. * The min id used for rendering groups (included)
  16298. */
  16299. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16300. /**
  16301. * Used to globally prevent autoclearing scenes.
  16302. */
  16303. RenderingManager.AUTOCLEAR = true;
  16304. return RenderingManager;
  16305. }());
  16306. BABYLON.RenderingManager = RenderingManager;
  16307. })(BABYLON || (BABYLON = {}));
  16308. //# sourceMappingURL=babylon.renderingManager.js.map
  16309. var BABYLON;
  16310. (function (BABYLON) {
  16311. var RenderingGroup = (function () {
  16312. /**
  16313. * Creates a new rendering group.
  16314. * @param index The rendering group index
  16315. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16316. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16317. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16318. */
  16319. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16320. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16321. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16322. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16323. this.index = index;
  16324. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16325. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16326. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16327. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  16328. this._particleSystems = new BABYLON.SmartArray(256);
  16329. this._spriteManagers = new BABYLON.SmartArray(256);
  16330. this._edgesRenderers = new BABYLON.SmartArray(16);
  16331. this._scene = scene;
  16332. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16333. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16334. this.transparentSortCompareFn = transparentSortCompareFn;
  16335. }
  16336. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16337. /**
  16338. * Set the opaque sort comparison function.
  16339. * If null the sub meshes will be render in the order they were created
  16340. */
  16341. set: function (value) {
  16342. this._opaqueSortCompareFn = value;
  16343. if (value) {
  16344. this._renderOpaque = this.renderOpaqueSorted;
  16345. }
  16346. else {
  16347. this._renderOpaque = RenderingGroup.renderUnsorted;
  16348. }
  16349. },
  16350. enumerable: true,
  16351. configurable: true
  16352. });
  16353. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16354. /**
  16355. * Set the alpha test sort comparison function.
  16356. * If null the sub meshes will be render in the order they were created
  16357. */
  16358. set: function (value) {
  16359. this._alphaTestSortCompareFn = value;
  16360. if (value) {
  16361. this._renderAlphaTest = this.renderAlphaTestSorted;
  16362. }
  16363. else {
  16364. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16365. }
  16366. },
  16367. enumerable: true,
  16368. configurable: true
  16369. });
  16370. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16371. /**
  16372. * Set the transparent sort comparison function.
  16373. * If null the sub meshes will be render in the order they were created
  16374. */
  16375. set: function (value) {
  16376. if (value) {
  16377. this._transparentSortCompareFn = value;
  16378. }
  16379. else {
  16380. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16381. }
  16382. this._renderTransparent = this.renderTransparentSorted;
  16383. },
  16384. enumerable: true,
  16385. configurable: true
  16386. });
  16387. /**
  16388. * Render all the sub meshes contained in the group.
  16389. * @param customRenderFunction Used to override the default render behaviour of the group.
  16390. * @returns true if rendered some submeshes.
  16391. */
  16392. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16393. if (customRenderFunction) {
  16394. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  16395. return;
  16396. }
  16397. var engine = this._scene.getEngine();
  16398. // Depth only
  16399. if (this._depthOnlySubMeshes.length !== 0) {
  16400. engine.setAlphaTesting(true);
  16401. engine.setColorWrite(false);
  16402. this._renderAlphaTest(this._depthOnlySubMeshes);
  16403. engine.setAlphaTesting(false);
  16404. engine.setColorWrite(true);
  16405. }
  16406. // Opaque
  16407. if (this._opaqueSubMeshes.length !== 0) {
  16408. this._renderOpaque(this._opaqueSubMeshes);
  16409. }
  16410. // Alpha test
  16411. if (this._alphaTestSubMeshes.length !== 0) {
  16412. engine.setAlphaTesting(true);
  16413. this._renderAlphaTest(this._alphaTestSubMeshes);
  16414. engine.setAlphaTesting(false);
  16415. }
  16416. var stencilState = engine.getStencilBuffer();
  16417. engine.setStencilBuffer(false);
  16418. // Sprites
  16419. if (renderSprites) {
  16420. this._renderSprites();
  16421. }
  16422. // Particles
  16423. if (renderParticles) {
  16424. this._renderParticles(activeMeshes);
  16425. }
  16426. if (this.onBeforeTransparentRendering) {
  16427. this.onBeforeTransparentRendering();
  16428. }
  16429. // Transparent
  16430. if (this._transparentSubMeshes.length !== 0) {
  16431. this._renderTransparent(this._transparentSubMeshes);
  16432. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16433. }
  16434. // Set back stencil to false in case it changes before the edge renderer.
  16435. engine.setStencilBuffer(false);
  16436. // Edges
  16437. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16438. this._edgesRenderers.data[edgesRendererIndex].render();
  16439. }
  16440. // Restore Stencil state.
  16441. engine.setStencilBuffer(stencilState);
  16442. };
  16443. /**
  16444. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16445. * @param subMeshes The submeshes to render
  16446. */
  16447. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16448. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16449. };
  16450. /**
  16451. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16452. * @param subMeshes The submeshes to render
  16453. */
  16454. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16455. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16456. };
  16457. /**
  16458. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16459. * @param subMeshes The submeshes to render
  16460. */
  16461. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16462. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16463. };
  16464. /**
  16465. * Renders the submeshes in a specified order.
  16466. * @param subMeshes The submeshes to sort before render
  16467. * @param sortCompareFn The comparison function use to sort
  16468. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16469. * @param transparent Specifies to activate blending if true
  16470. */
  16471. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16472. var subIndex = 0;
  16473. var subMesh;
  16474. for (; subIndex < subMeshes.length; subIndex++) {
  16475. subMesh = subMeshes.data[subIndex];
  16476. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16477. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16478. }
  16479. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16480. sortedArray.sort(sortCompareFn);
  16481. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16482. subMesh = sortedArray[subIndex];
  16483. if (transparent) {
  16484. var material = subMesh.getMaterial();
  16485. if (material.needDepthPrePass) {
  16486. var engine = material.getScene().getEngine();
  16487. engine.setColorWrite(false);
  16488. engine.setAlphaTesting(true);
  16489. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16490. subMesh.render(false);
  16491. engine.setAlphaTesting(false);
  16492. engine.setColorWrite(true);
  16493. }
  16494. }
  16495. subMesh.render(transparent);
  16496. }
  16497. };
  16498. /**
  16499. * Renders the submeshes in the order they were dispatched (no sort applied).
  16500. * @param subMeshes The submeshes to render
  16501. */
  16502. RenderingGroup.renderUnsorted = function (subMeshes) {
  16503. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16504. var submesh = subMeshes.data[subIndex];
  16505. submesh.render(false);
  16506. }
  16507. };
  16508. /**
  16509. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16510. * are rendered back to front if in the same alpha index.
  16511. *
  16512. * @param a The first submesh
  16513. * @param b The second submesh
  16514. * @returns The result of the comparison
  16515. */
  16516. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16517. // Alpha index first
  16518. if (a._alphaIndex > b._alphaIndex) {
  16519. return 1;
  16520. }
  16521. if (a._alphaIndex < b._alphaIndex) {
  16522. return -1;
  16523. }
  16524. // Then distance to camera
  16525. return RenderingGroup.backToFrontSortCompare(a, b);
  16526. };
  16527. /**
  16528. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16529. * are rendered back to front.
  16530. *
  16531. * @param a The first submesh
  16532. * @param b The second submesh
  16533. * @returns The result of the comparison
  16534. */
  16535. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16536. // Then distance to camera
  16537. if (a._distanceToCamera < b._distanceToCamera) {
  16538. return 1;
  16539. }
  16540. if (a._distanceToCamera > b._distanceToCamera) {
  16541. return -1;
  16542. }
  16543. return 0;
  16544. };
  16545. /**
  16546. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16547. * are rendered front to back (prevent overdraw).
  16548. *
  16549. * @param a The first submesh
  16550. * @param b The second submesh
  16551. * @returns The result of the comparison
  16552. */
  16553. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16554. // Then distance to camera
  16555. if (a._distanceToCamera < b._distanceToCamera) {
  16556. return -1;
  16557. }
  16558. if (a._distanceToCamera > b._distanceToCamera) {
  16559. return 1;
  16560. }
  16561. return 0;
  16562. };
  16563. /**
  16564. * Resets the different lists of submeshes to prepare a new frame.
  16565. */
  16566. RenderingGroup.prototype.prepare = function () {
  16567. this._opaqueSubMeshes.reset();
  16568. this._transparentSubMeshes.reset();
  16569. this._alphaTestSubMeshes.reset();
  16570. this._depthOnlySubMeshes.reset();
  16571. this._particleSystems.reset();
  16572. this._spriteManagers.reset();
  16573. this._edgesRenderers.reset();
  16574. };
  16575. RenderingGroup.prototype.dispose = function () {
  16576. this._opaqueSubMeshes.dispose();
  16577. this._transparentSubMeshes.dispose();
  16578. this._alphaTestSubMeshes.dispose();
  16579. this._depthOnlySubMeshes.dispose();
  16580. this._particleSystems.dispose();
  16581. this._spriteManagers.dispose();
  16582. this._edgesRenderers.dispose();
  16583. };
  16584. /**
  16585. * Inserts the submesh in its correct queue depending on its material.
  16586. * @param subMesh The submesh to dispatch
  16587. */
  16588. RenderingGroup.prototype.dispatch = function (subMesh) {
  16589. var material = subMesh.getMaterial();
  16590. var mesh = subMesh.getMesh();
  16591. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16592. this._transparentSubMeshes.push(subMesh);
  16593. }
  16594. else if (material.needAlphaTesting()) {
  16595. if (material.needDepthPrePass) {
  16596. this._depthOnlySubMeshes.push(subMesh);
  16597. }
  16598. this._alphaTestSubMeshes.push(subMesh);
  16599. }
  16600. else {
  16601. if (material.needDepthPrePass) {
  16602. this._depthOnlySubMeshes.push(subMesh);
  16603. }
  16604. this._opaqueSubMeshes.push(subMesh); // Opaque
  16605. }
  16606. if (mesh._edgesRenderer) {
  16607. this._edgesRenderers.push(mesh._edgesRenderer);
  16608. }
  16609. };
  16610. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  16611. this._spriteManagers.push(spriteManager);
  16612. };
  16613. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  16614. this._particleSystems.push(particleSystem);
  16615. };
  16616. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  16617. if (this._particleSystems.length === 0) {
  16618. return;
  16619. }
  16620. // Particles
  16621. var activeCamera = this._scene.activeCamera;
  16622. this._scene._particlesDuration.beginMonitoring();
  16623. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16624. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16625. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16626. continue;
  16627. }
  16628. var emitter = particleSystem.emitter;
  16629. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  16630. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16631. }
  16632. }
  16633. this._scene._particlesDuration.endMonitoring(false);
  16634. };
  16635. RenderingGroup.prototype._renderSprites = function () {
  16636. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16637. return;
  16638. }
  16639. // Sprites
  16640. var activeCamera = this._scene.activeCamera;
  16641. this._scene._spritesDuration.beginMonitoring();
  16642. for (var id = 0; id < this._spriteManagers.length; id++) {
  16643. var spriteManager = this._spriteManagers.data[id];
  16644. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16645. spriteManager.render();
  16646. }
  16647. }
  16648. this._scene._spritesDuration.endMonitoring(false);
  16649. };
  16650. return RenderingGroup;
  16651. }());
  16652. BABYLON.RenderingGroup = RenderingGroup;
  16653. })(BABYLON || (BABYLON = {}));
  16654. //# sourceMappingURL=babylon.renderingGroup.js.map
  16655. var BABYLON;
  16656. (function (BABYLON) {
  16657. var ClickInfo = (function () {
  16658. function ClickInfo() {
  16659. this._singleClick = false;
  16660. this._doubleClick = false;
  16661. this._hasSwiped = false;
  16662. this._ignore = false;
  16663. }
  16664. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  16665. get: function () {
  16666. return this._singleClick;
  16667. },
  16668. set: function (b) {
  16669. this._singleClick = b;
  16670. },
  16671. enumerable: true,
  16672. configurable: true
  16673. });
  16674. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  16675. get: function () {
  16676. return this._doubleClick;
  16677. },
  16678. set: function (b) {
  16679. this._doubleClick = b;
  16680. },
  16681. enumerable: true,
  16682. configurable: true
  16683. });
  16684. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  16685. get: function () {
  16686. return this._hasSwiped;
  16687. },
  16688. set: function (b) {
  16689. this._hasSwiped = b;
  16690. },
  16691. enumerable: true,
  16692. configurable: true
  16693. });
  16694. Object.defineProperty(ClickInfo.prototype, "ignore", {
  16695. get: function () {
  16696. return this._ignore;
  16697. },
  16698. set: function (b) {
  16699. this._ignore = b;
  16700. },
  16701. enumerable: true,
  16702. configurable: true
  16703. });
  16704. return ClickInfo;
  16705. }());
  16706. /**
  16707. * This class is used by the onRenderingGroupObservable
  16708. */
  16709. var RenderingGroupInfo = (function () {
  16710. function RenderingGroupInfo() {
  16711. }
  16712. /**
  16713. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16714. * This stage will be fired no matter what
  16715. */
  16716. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16717. /**
  16718. * Called before opaque object are rendered.
  16719. * This stage will be fired only if there's 3D Opaque content to render
  16720. */
  16721. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16722. /**
  16723. * Called after the opaque objects are rendered and before the transparent ones
  16724. * This stage will be fired only if there's 3D transparent content to render
  16725. */
  16726. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16727. /**
  16728. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16729. * This stage will be fired no matter what
  16730. */
  16731. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16732. return RenderingGroupInfo;
  16733. }());
  16734. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16735. /**
  16736. * Represents a scene to be rendered by the engine.
  16737. * @see http://doc.babylonjs.com/page.php?p=21911
  16738. */
  16739. var Scene = (function () {
  16740. /**
  16741. * @constructor
  16742. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16743. */
  16744. function Scene(engine) {
  16745. // Members
  16746. this.autoClear = true;
  16747. this.autoClearDepthAndStencil = true;
  16748. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16749. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16750. this.forceWireframe = false;
  16751. this._forcePointsCloud = false;
  16752. this.forceShowBoundingBoxes = false;
  16753. this.animationsEnabled = true;
  16754. this.constantlyUpdateMeshUnderPointer = false;
  16755. this.hoverCursor = "pointer";
  16756. this.defaultCursor = "";
  16757. /**
  16758. * This is used to call preventDefault() on pointer down
  16759. * in order to block unwanted artifacts like system double clicks
  16760. */
  16761. this.preventDefaultOnPointerDown = true;
  16762. // Metadata
  16763. this.metadata = null;
  16764. /**
  16765. * An event triggered when the scene is disposed.
  16766. * @type {BABYLON.Observable}
  16767. */
  16768. this.onDisposeObservable = new BABYLON.Observable();
  16769. /**
  16770. * An event triggered before rendering the scene
  16771. * @type {BABYLON.Observable}
  16772. */
  16773. this.onBeforeRenderObservable = new BABYLON.Observable();
  16774. /**
  16775. * An event triggered after rendering the scene
  16776. * @type {BABYLON.Observable}
  16777. */
  16778. this.onAfterRenderObservable = new BABYLON.Observable();
  16779. /**
  16780. * An event triggered when the scene is ready
  16781. * @type {BABYLON.Observable}
  16782. */
  16783. this.onReadyObservable = new BABYLON.Observable();
  16784. /**
  16785. * An event triggered before rendering a camera
  16786. * @type {BABYLON.Observable}
  16787. */
  16788. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16789. /**
  16790. * An event triggered after rendering a camera
  16791. * @type {BABYLON.Observable}
  16792. */
  16793. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16794. /**
  16795. * An event triggered when a camera is created
  16796. * @type {BABYLON.Observable}
  16797. */
  16798. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16799. /**
  16800. * An event triggered when a camera is removed
  16801. * @type {BABYLON.Observable}
  16802. */
  16803. this.onCameraRemovedObservable = new BABYLON.Observable();
  16804. /**
  16805. * An event triggered when a light is created
  16806. * @type {BABYLON.Observable}
  16807. */
  16808. this.onNewLightAddedObservable = new BABYLON.Observable();
  16809. /**
  16810. * An event triggered when a light is removed
  16811. * @type {BABYLON.Observable}
  16812. */
  16813. this.onLightRemovedObservable = new BABYLON.Observable();
  16814. /**
  16815. * An event triggered when a geometry is created
  16816. * @type {BABYLON.Observable}
  16817. */
  16818. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16819. /**
  16820. * An event triggered when a geometry is removed
  16821. * @type {BABYLON.Observable}
  16822. */
  16823. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16824. /**
  16825. * An event triggered when a mesh is created
  16826. * @type {BABYLON.Observable}
  16827. */
  16828. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16829. /**
  16830. * An event triggered when a mesh is removed
  16831. * @type {BABYLON.Observable}
  16832. */
  16833. this.onMeshRemovedObservable = new BABYLON.Observable();
  16834. /**
  16835. * An event triggered before calculating deterministic simulation step
  16836. * @type {BABYLON.Observable}
  16837. */
  16838. this.onBeforeStepObservable = new BABYLON.Observable();
  16839. /**
  16840. * An event triggered after calculating deterministic simulation step
  16841. * @type {BABYLON.Observable}
  16842. */
  16843. this.onAfterStepObservable = new BABYLON.Observable();
  16844. /**
  16845. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16846. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16847. * 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)
  16848. */
  16849. this.onRenderingGroupObservable = new BABYLON.Observable();
  16850. // Animations
  16851. this.animations = [];
  16852. /**
  16853. * 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).
  16854. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  16855. */
  16856. this.onPrePointerObservable = new BABYLON.Observable();
  16857. /**
  16858. * Observable event triggered each time an input event is received from the rendering canvas
  16859. */
  16860. this.onPointerObservable = new BABYLON.Observable();
  16861. this._meshPickProceed = false;
  16862. this._previousHasSwiped = false;
  16863. this._currentPickResult = null;
  16864. this._previousPickResult = null;
  16865. this._totalPointersPressed = 0;
  16866. this._doubleClickOccured = false;
  16867. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  16868. this.cameraToUseForPointers = null;
  16869. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16870. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  16871. this._startingPointerTime = 0;
  16872. this._previousStartingPointerTime = 0;
  16873. // Deterministic lockstep
  16874. this._timeAccumulator = 0;
  16875. this._currentStepId = 0;
  16876. this._currentInternalStep = 0;
  16877. // Keyboard
  16878. /**
  16879. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  16880. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  16881. */
  16882. this.onPreKeyboardObservable = new BABYLON.Observable();
  16883. /**
  16884. * Observable event triggered each time an keyboard event is received from the hosting window
  16885. */
  16886. this.onKeyboardObservable = new BABYLON.Observable();
  16887. // Coordinate system
  16888. /**
  16889. * use right-handed coordinate system on this scene.
  16890. * @type {boolean}
  16891. */
  16892. this._useRightHandedSystem = false;
  16893. // Fog
  16894. this._fogEnabled = true;
  16895. this._fogMode = Scene.FOGMODE_NONE;
  16896. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16897. this.fogDensity = 0.1;
  16898. this.fogStart = 0;
  16899. this.fogEnd = 1000.0;
  16900. // Lights
  16901. /**
  16902. * is shadow enabled on this scene.
  16903. * @type {boolean}
  16904. */
  16905. this._shadowsEnabled = true;
  16906. /**
  16907. * is light enabled on this scene.
  16908. * @type {boolean}
  16909. */
  16910. this._lightsEnabled = true;
  16911. /**
  16912. * All of the lights added to this scene.
  16913. * @see BABYLON.Light
  16914. * @type {BABYLON.Light[]}
  16915. */
  16916. this.lights = new Array();
  16917. // Cameras
  16918. /** All of the cameras added to this scene. */
  16919. this.cameras = new Array();
  16920. /** All of the active cameras added to this scene. */
  16921. this.activeCameras = new Array();
  16922. // Meshes
  16923. /**
  16924. * All of the (abstract) meshes added to this scene.
  16925. * @see BABYLON.AbstractMesh
  16926. * @type {BABYLON.AbstractMesh[]}
  16927. */
  16928. this.meshes = new Array();
  16929. // Geometries
  16930. this._geometries = new Array();
  16931. this.materials = new Array();
  16932. this.multiMaterials = new Array();
  16933. // Textures
  16934. this._texturesEnabled = true;
  16935. this.textures = new Array();
  16936. // Particles
  16937. this.particlesEnabled = true;
  16938. this.particleSystems = new Array();
  16939. // Sprites
  16940. this.spritesEnabled = true;
  16941. this.spriteManagers = new Array();
  16942. // Layers
  16943. this.layers = new Array();
  16944. this.highlightLayers = new Array();
  16945. // Skeletons
  16946. this._skeletonsEnabled = true;
  16947. this.skeletons = new Array();
  16948. // Morph targets
  16949. this.morphTargetManagers = new Array();
  16950. // Lens flares
  16951. this.lensFlaresEnabled = true;
  16952. this.lensFlareSystems = new Array();
  16953. // Collisions
  16954. this.collisionsEnabled = true;
  16955. /** Defines the gravity applied to this scene */
  16956. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16957. // Postprocesses
  16958. this.postProcesses = new Array();
  16959. this.postProcessesEnabled = true;
  16960. // Customs render targets
  16961. this.renderTargetsEnabled = true;
  16962. this.dumpNextRenderTargets = false;
  16963. this.customRenderTargets = new Array();
  16964. // Imported meshes
  16965. this.importedMeshesFiles = new Array();
  16966. // Probes
  16967. this.probesEnabled = true;
  16968. this.reflectionProbes = new Array();
  16969. this._actionManagers = new Array();
  16970. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16971. // Procedural textures
  16972. this.proceduralTexturesEnabled = true;
  16973. this._proceduralTextures = new Array();
  16974. this.soundTracks = new Array();
  16975. this._audioEnabled = true;
  16976. this._headphone = false;
  16977. // Performance counters
  16978. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16979. this._totalLightsCounter = new BABYLON.PerfCounter();
  16980. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16981. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16982. this._totalVertices = new BABYLON.PerfCounter();
  16983. this._activeIndices = new BABYLON.PerfCounter();
  16984. this._activeParticles = new BABYLON.PerfCounter();
  16985. this._interFrameDuration = new BABYLON.PerfCounter();
  16986. this._lastFrameDuration = new BABYLON.PerfCounter();
  16987. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16988. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16989. this._particlesDuration = new BABYLON.PerfCounter();
  16990. this._renderDuration = new BABYLON.PerfCounter();
  16991. this._spritesDuration = new BABYLON.PerfCounter();
  16992. this._activeBones = new BABYLON.PerfCounter();
  16993. this._animationTime = 0;
  16994. this.animationTimeScale = 1;
  16995. this._renderId = 0;
  16996. this._executeWhenReadyTimeoutId = -1;
  16997. this._intermediateRendering = false;
  16998. this._viewUpdateFlag = -1;
  16999. this._projectionUpdateFlag = -1;
  17000. this._alternateViewUpdateFlag = -1;
  17001. this._alternateProjectionUpdateFlag = -1;
  17002. this._toBeDisposed = new BABYLON.SmartArray(256);
  17003. this._pendingData = new Array();
  17004. this._activeMeshes = new BABYLON.SmartArray(256);
  17005. this._processedMaterials = new BABYLON.SmartArray(256);
  17006. this._renderTargets = new BABYLON.SmartArray(256);
  17007. this._activeParticleSystems = new BABYLON.SmartArray(256);
  17008. this._activeSkeletons = new BABYLON.SmartArray(32);
  17009. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  17010. this._activeAnimatables = new Array();
  17011. this._transformMatrix = BABYLON.Matrix.Zero();
  17012. this._useAlternateCameraConfiguration = false;
  17013. this._alternateRendering = false;
  17014. this.requireLightSorting = false;
  17015. this._activeMeshesFrozen = false;
  17016. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  17017. this._engine.scenes.push(this);
  17018. this._uid = null;
  17019. this._renderingManager = new BABYLON.RenderingManager(this);
  17020. this.postProcessManager = new BABYLON.PostProcessManager(this);
  17021. if (BABYLON.OutlineRenderer) {
  17022. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  17023. }
  17024. if (BABYLON.Tools.IsWindowObjectExist()) {
  17025. this.attachControl();
  17026. }
  17027. //simplification queue
  17028. if (BABYLON.SimplificationQueue) {
  17029. this.simplificationQueue = new BABYLON.SimplificationQueue();
  17030. }
  17031. //collision coordinator initialization. For now legacy per default.
  17032. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  17033. // Uniform Buffer
  17034. this._createUbo();
  17035. // Default Image processing definition.
  17036. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  17037. }
  17038. Object.defineProperty(Scene, "FOGMODE_NONE", {
  17039. /** The fog is deactivated */
  17040. get: function () {
  17041. return Scene._FOGMODE_NONE;
  17042. },
  17043. enumerable: true,
  17044. configurable: true
  17045. });
  17046. Object.defineProperty(Scene, "FOGMODE_EXP", {
  17047. /** The fog density is following an exponential function */
  17048. get: function () {
  17049. return Scene._FOGMODE_EXP;
  17050. },
  17051. enumerable: true,
  17052. configurable: true
  17053. });
  17054. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  17055. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  17056. get: function () {
  17057. return Scene._FOGMODE_EXP2;
  17058. },
  17059. enumerable: true,
  17060. configurable: true
  17061. });
  17062. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  17063. /** The fog density is following a linear function. */
  17064. get: function () {
  17065. return Scene._FOGMODE_LINEAR;
  17066. },
  17067. enumerable: true,
  17068. configurable: true
  17069. });
  17070. Object.defineProperty(Scene.prototype, "environmentTexture", {
  17071. /**
  17072. * Texture used in all pbr material as the reflection texture.
  17073. * As in the majority of the scene they are the same (exception for multi room and so on),
  17074. * this is easier to reference from here than from all the materials.
  17075. */
  17076. get: function () {
  17077. return this._environmentTexture;
  17078. },
  17079. /**
  17080. * Texture used in all pbr material as the reflection texture.
  17081. * As in the majority of the scene they are the same (exception for multi room and so on),
  17082. * this is easier to set here than in all the materials.
  17083. */
  17084. set: function (value) {
  17085. this._environmentTexture = value;
  17086. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17087. },
  17088. enumerable: true,
  17089. configurable: true
  17090. });
  17091. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  17092. /**
  17093. * Default image processing configuration used either in the rendering
  17094. * Forward main pass or through the imageProcessingPostProcess if present.
  17095. * As in the majority of the scene they are the same (exception for multi camera),
  17096. * this is easier to reference from here than from all the materials and post process.
  17097. *
  17098. * No setter as we it is a shared configuration, you can set the values instead.
  17099. */
  17100. get: function () {
  17101. return this._imageProcessingConfiguration;
  17102. },
  17103. enumerable: true,
  17104. configurable: true
  17105. });
  17106. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  17107. get: function () {
  17108. return this._forcePointsCloud;
  17109. },
  17110. set: function (value) {
  17111. if (this._forcePointsCloud === value) {
  17112. return;
  17113. }
  17114. this._forcePointsCloud = value;
  17115. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17116. },
  17117. enumerable: true,
  17118. configurable: true
  17119. });
  17120. Object.defineProperty(Scene.prototype, "onDispose", {
  17121. /** A function to be executed when this scene is disposed. */
  17122. set: function (callback) {
  17123. if (this._onDisposeObserver) {
  17124. this.onDisposeObservable.remove(this._onDisposeObserver);
  17125. }
  17126. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17127. },
  17128. enumerable: true,
  17129. configurable: true
  17130. });
  17131. Object.defineProperty(Scene.prototype, "beforeRender", {
  17132. /** A function to be executed before rendering this scene */
  17133. set: function (callback) {
  17134. if (this._onBeforeRenderObserver) {
  17135. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  17136. }
  17137. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  17138. },
  17139. enumerable: true,
  17140. configurable: true
  17141. });
  17142. Object.defineProperty(Scene.prototype, "afterRender", {
  17143. /** A function to be executed after rendering this scene */
  17144. set: function (callback) {
  17145. if (this._onAfterRenderObserver) {
  17146. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  17147. }
  17148. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  17149. },
  17150. enumerable: true,
  17151. configurable: true
  17152. });
  17153. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  17154. set: function (callback) {
  17155. if (this._onBeforeCameraRenderObserver) {
  17156. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  17157. }
  17158. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  17159. },
  17160. enumerable: true,
  17161. configurable: true
  17162. });
  17163. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  17164. set: function (callback) {
  17165. if (this._onAfterCameraRenderObserver) {
  17166. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  17167. }
  17168. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  17169. },
  17170. enumerable: true,
  17171. configurable: true
  17172. });
  17173. Object.defineProperty(Scene.prototype, "gamepadManager", {
  17174. get: function () {
  17175. if (!this._gamepadManager) {
  17176. this._gamepadManager = new BABYLON.GamepadManager();
  17177. }
  17178. return this._gamepadManager;
  17179. },
  17180. enumerable: true,
  17181. configurable: true
  17182. });
  17183. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  17184. get: function () {
  17185. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  17186. },
  17187. enumerable: true,
  17188. configurable: true
  17189. });
  17190. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  17191. get: function () {
  17192. return this._useRightHandedSystem;
  17193. },
  17194. set: function (value) {
  17195. if (this._useRightHandedSystem === value) {
  17196. return;
  17197. }
  17198. this._useRightHandedSystem = value;
  17199. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17200. },
  17201. enumerable: true,
  17202. configurable: true
  17203. });
  17204. Scene.prototype.setStepId = function (newStepId) {
  17205. this._currentStepId = newStepId;
  17206. };
  17207. ;
  17208. Scene.prototype.getStepId = function () {
  17209. return this._currentStepId;
  17210. };
  17211. ;
  17212. Scene.prototype.getInternalStep = function () {
  17213. return this._currentInternalStep;
  17214. };
  17215. ;
  17216. Object.defineProperty(Scene.prototype, "fogEnabled", {
  17217. get: function () {
  17218. return this._fogEnabled;
  17219. },
  17220. /**
  17221. * is fog enabled on this scene.
  17222. */
  17223. set: function (value) {
  17224. if (this._fogEnabled === value) {
  17225. return;
  17226. }
  17227. this._fogEnabled = value;
  17228. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17229. },
  17230. enumerable: true,
  17231. configurable: true
  17232. });
  17233. Object.defineProperty(Scene.prototype, "fogMode", {
  17234. get: function () {
  17235. return this._fogMode;
  17236. },
  17237. set: function (value) {
  17238. if (this._fogMode === value) {
  17239. return;
  17240. }
  17241. this._fogMode = value;
  17242. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17243. },
  17244. enumerable: true,
  17245. configurable: true
  17246. });
  17247. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  17248. get: function () {
  17249. return this._shadowsEnabled;
  17250. },
  17251. set: function (value) {
  17252. if (this._shadowsEnabled === value) {
  17253. return;
  17254. }
  17255. this._shadowsEnabled = value;
  17256. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17257. },
  17258. enumerable: true,
  17259. configurable: true
  17260. });
  17261. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  17262. get: function () {
  17263. return this._lightsEnabled;
  17264. },
  17265. set: function (value) {
  17266. if (this._lightsEnabled === value) {
  17267. return;
  17268. }
  17269. this._lightsEnabled = value;
  17270. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17271. },
  17272. enumerable: true,
  17273. configurable: true
  17274. });
  17275. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  17276. /** The default material used on meshes when no material is affected */
  17277. get: function () {
  17278. if (!this._defaultMaterial) {
  17279. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  17280. }
  17281. return this._defaultMaterial;
  17282. },
  17283. /** The default material used on meshes when no material is affected */
  17284. set: function (value) {
  17285. this._defaultMaterial = value;
  17286. },
  17287. enumerable: true,
  17288. configurable: true
  17289. });
  17290. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  17291. get: function () {
  17292. return this._texturesEnabled;
  17293. },
  17294. set: function (value) {
  17295. if (this._texturesEnabled === value) {
  17296. return;
  17297. }
  17298. this._texturesEnabled = value;
  17299. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17300. },
  17301. enumerable: true,
  17302. configurable: true
  17303. });
  17304. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  17305. get: function () {
  17306. return this._skeletonsEnabled;
  17307. },
  17308. set: function (value) {
  17309. if (this._skeletonsEnabled === value) {
  17310. return;
  17311. }
  17312. this._skeletonsEnabled = value;
  17313. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  17314. },
  17315. enumerable: true,
  17316. configurable: true
  17317. });
  17318. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  17319. get: function () {
  17320. if (!this._postProcessRenderPipelineManager) {
  17321. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  17322. }
  17323. return this._postProcessRenderPipelineManager;
  17324. },
  17325. enumerable: true,
  17326. configurable: true
  17327. });
  17328. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  17329. get: function () {
  17330. if (!this._mainSoundTrack) {
  17331. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  17332. }
  17333. return this._mainSoundTrack;
  17334. },
  17335. enumerable: true,
  17336. configurable: true
  17337. });
  17338. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  17339. get: function () {
  17340. return this._alternateRendering;
  17341. },
  17342. enumerable: true,
  17343. configurable: true
  17344. });
  17345. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17346. get: function () {
  17347. return this._frustumPlanes;
  17348. },
  17349. enumerable: true,
  17350. configurable: true
  17351. });
  17352. Object.defineProperty(Scene.prototype, "debugLayer", {
  17353. // Properties
  17354. get: function () {
  17355. if (!this._debugLayer) {
  17356. this._debugLayer = new BABYLON.DebugLayer(this);
  17357. }
  17358. return this._debugLayer;
  17359. },
  17360. enumerable: true,
  17361. configurable: true
  17362. });
  17363. Object.defineProperty(Scene.prototype, "workerCollisions", {
  17364. get: function () {
  17365. return this._workerCollisions;
  17366. },
  17367. set: function (enabled) {
  17368. if (!BABYLON.CollisionCoordinatorLegacy) {
  17369. return;
  17370. }
  17371. enabled = (enabled && !!Worker);
  17372. this._workerCollisions = enabled;
  17373. if (this.collisionCoordinator) {
  17374. this.collisionCoordinator.destroy();
  17375. }
  17376. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  17377. this.collisionCoordinator.init(this);
  17378. },
  17379. enumerable: true,
  17380. configurable: true
  17381. });
  17382. Object.defineProperty(Scene.prototype, "selectionOctree", {
  17383. get: function () {
  17384. return this._selectionOctree;
  17385. },
  17386. enumerable: true,
  17387. configurable: true
  17388. });
  17389. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  17390. /**
  17391. * The mesh that is currently under the pointer.
  17392. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  17393. */
  17394. get: function () {
  17395. return this._pointerOverMesh;
  17396. },
  17397. enumerable: true,
  17398. configurable: true
  17399. });
  17400. Object.defineProperty(Scene.prototype, "pointerX", {
  17401. /**
  17402. * Current on-screen X position of the pointer
  17403. * @return {number} X position of the pointer
  17404. */
  17405. get: function () {
  17406. return this._pointerX;
  17407. },
  17408. enumerable: true,
  17409. configurable: true
  17410. });
  17411. Object.defineProperty(Scene.prototype, "pointerY", {
  17412. /**
  17413. * Current on-screen Y position of the pointer
  17414. * @return {number} Y position of the pointer
  17415. */
  17416. get: function () {
  17417. return this._pointerY;
  17418. },
  17419. enumerable: true,
  17420. configurable: true
  17421. });
  17422. Scene.prototype.getCachedMaterial = function () {
  17423. return this._cachedMaterial;
  17424. };
  17425. Scene.prototype.getCachedEffect = function () {
  17426. return this._cachedEffect;
  17427. };
  17428. Scene.prototype.getCachedVisibility = function () {
  17429. return this._cachedVisibility;
  17430. };
  17431. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  17432. if (visibility === void 0) { visibility = 1; }
  17433. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  17434. };
  17435. Scene.prototype.getBoundingBoxRenderer = function () {
  17436. if (!this._boundingBoxRenderer) {
  17437. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  17438. }
  17439. return this._boundingBoxRenderer;
  17440. };
  17441. Scene.prototype.getOutlineRenderer = function () {
  17442. return this._outlineRenderer;
  17443. };
  17444. Scene.prototype.getEngine = function () {
  17445. return this._engine;
  17446. };
  17447. Scene.prototype.getTotalVertices = function () {
  17448. return this._totalVertices.current;
  17449. };
  17450. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17451. get: function () {
  17452. return this._totalVertices;
  17453. },
  17454. enumerable: true,
  17455. configurable: true
  17456. });
  17457. Scene.prototype.getActiveIndices = function () {
  17458. return this._activeIndices.current;
  17459. };
  17460. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17461. get: function () {
  17462. return this._activeIndices;
  17463. },
  17464. enumerable: true,
  17465. configurable: true
  17466. });
  17467. Scene.prototype.getActiveParticles = function () {
  17468. return this._activeParticles.current;
  17469. };
  17470. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17471. get: function () {
  17472. return this._activeParticles;
  17473. },
  17474. enumerable: true,
  17475. configurable: true
  17476. });
  17477. Scene.prototype.getActiveBones = function () {
  17478. return this._activeBones.current;
  17479. };
  17480. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17481. get: function () {
  17482. return this._activeBones;
  17483. },
  17484. enumerable: true,
  17485. configurable: true
  17486. });
  17487. // Stats
  17488. Scene.prototype.getInterFramePerfCounter = function () {
  17489. return this._interFrameDuration.current;
  17490. };
  17491. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  17492. get: function () {
  17493. return this._interFrameDuration;
  17494. },
  17495. enumerable: true,
  17496. configurable: true
  17497. });
  17498. Scene.prototype.getLastFrameDuration = function () {
  17499. return this._lastFrameDuration.current;
  17500. };
  17501. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17502. get: function () {
  17503. return this._lastFrameDuration;
  17504. },
  17505. enumerable: true,
  17506. configurable: true
  17507. });
  17508. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17509. return this._evaluateActiveMeshesDuration.current;
  17510. };
  17511. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17512. get: function () {
  17513. return this._evaluateActiveMeshesDuration;
  17514. },
  17515. enumerable: true,
  17516. configurable: true
  17517. });
  17518. Scene.prototype.getActiveMeshes = function () {
  17519. return this._activeMeshes;
  17520. };
  17521. Scene.prototype.getRenderTargetsDuration = function () {
  17522. return this._renderTargetsDuration.current;
  17523. };
  17524. Scene.prototype.getRenderDuration = function () {
  17525. return this._renderDuration.current;
  17526. };
  17527. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17528. get: function () {
  17529. return this._renderDuration;
  17530. },
  17531. enumerable: true,
  17532. configurable: true
  17533. });
  17534. Scene.prototype.getParticlesDuration = function () {
  17535. return this._particlesDuration.current;
  17536. };
  17537. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17538. get: function () {
  17539. return this._particlesDuration;
  17540. },
  17541. enumerable: true,
  17542. configurable: true
  17543. });
  17544. Scene.prototype.getSpritesDuration = function () {
  17545. return this._spritesDuration.current;
  17546. };
  17547. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17548. get: function () {
  17549. return this._spritesDuration;
  17550. },
  17551. enumerable: true,
  17552. configurable: true
  17553. });
  17554. Scene.prototype.getAnimationRatio = function () {
  17555. return this._animationRatio;
  17556. };
  17557. Scene.prototype.getRenderId = function () {
  17558. return this._renderId;
  17559. };
  17560. Scene.prototype.incrementRenderId = function () {
  17561. this._renderId++;
  17562. };
  17563. Scene.prototype._updatePointerPosition = function (evt) {
  17564. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17565. this._pointerX = evt.clientX - canvasRect.left;
  17566. this._pointerY = evt.clientY - canvasRect.top;
  17567. this._unTranslatedPointerX = this._pointerX;
  17568. this._unTranslatedPointerY = this._pointerY;
  17569. };
  17570. Scene.prototype._createUbo = function () {
  17571. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17572. this._sceneUbo.addUniform("viewProjection", 16);
  17573. this._sceneUbo.addUniform("view", 16);
  17574. };
  17575. Scene.prototype._createAlternateUbo = function () {
  17576. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17577. this._alternateSceneUbo.addUniform("viewProjection", 16);
  17578. this._alternateSceneUbo.addUniform("view", 16);
  17579. };
  17580. // Pointers handling
  17581. /**
  17582. * Use this method to simulate a pointer move on a mesh
  17583. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17584. */
  17585. Scene.prototype.simulatePointerMove = function (pickResult) {
  17586. var evt = new PointerEvent("pointermove");
  17587. return this._processPointerMove(pickResult, evt);
  17588. };
  17589. Scene.prototype._processPointerMove = function (pickResult, evt) {
  17590. var canvas = this._engine.getRenderingCanvas();
  17591. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17592. this.setPointerOverSprite(null);
  17593. this.setPointerOverMesh(pickResult.pickedMesh);
  17594. if (this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17595. if (this._pointerOverMesh.actionManager.hoverCursor) {
  17596. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  17597. }
  17598. else {
  17599. canvas.style.cursor = this.hoverCursor;
  17600. }
  17601. }
  17602. else {
  17603. canvas.style.cursor = this.defaultCursor;
  17604. }
  17605. }
  17606. else {
  17607. this.setPointerOverMesh(null);
  17608. // Sprites
  17609. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers);
  17610. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17611. this.setPointerOverSprite(pickResult.pickedSprite);
  17612. if (this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  17613. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  17614. }
  17615. else {
  17616. canvas.style.cursor = this.hoverCursor;
  17617. }
  17618. }
  17619. else {
  17620. this.setPointerOverSprite(null);
  17621. // Restore pointer
  17622. canvas.style.cursor = this.defaultCursor;
  17623. }
  17624. }
  17625. if (this.onPointerMove) {
  17626. this.onPointerMove(evt, pickResult);
  17627. }
  17628. if (this.onPointerObservable.hasObservers()) {
  17629. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17630. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17631. this.onPointerObservable.notifyObservers(pi, type);
  17632. }
  17633. return this;
  17634. };
  17635. /**
  17636. * Use this method to simulate a pointer down on a mesh
  17637. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17638. */
  17639. Scene.prototype.simulatePointerDown = function (pickResult) {
  17640. var evt = new PointerEvent("pointerdown");
  17641. return this._processPointerDown(pickResult, evt);
  17642. };
  17643. Scene.prototype._processPointerDown = function (pickResult, evt) {
  17644. var _this = this;
  17645. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17646. this._pickedDownMesh = pickResult.pickedMesh;
  17647. var actionManager = pickResult.pickedMesh.actionManager;
  17648. if (actionManager) {
  17649. if (actionManager.hasPickTriggers) {
  17650. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17651. switch (evt.button) {
  17652. case 0:
  17653. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17654. break;
  17655. case 1:
  17656. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17657. break;
  17658. case 2:
  17659. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17660. break;
  17661. }
  17662. }
  17663. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17664. window.setTimeout(function () {
  17665. 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);
  17666. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17667. if (_this._totalPointersPressed !== 0 &&
  17668. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  17669. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  17670. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  17671. _this._startingPointerTime = 0;
  17672. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17673. }
  17674. }
  17675. }, Scene.LongPressDelay);
  17676. }
  17677. }
  17678. }
  17679. if (this.onPointerDown) {
  17680. this.onPointerDown(evt, pickResult);
  17681. }
  17682. if (this.onPointerObservable.hasObservers()) {
  17683. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17684. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17685. this.onPointerObservable.notifyObservers(pi, type);
  17686. }
  17687. return this;
  17688. };
  17689. /**
  17690. * Use this method to simulate a pointer up on a mesh
  17691. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17692. */
  17693. Scene.prototype.simulatePointerUp = function (pickResult) {
  17694. var evt = new PointerEvent("pointerup");
  17695. var clickInfo = new ClickInfo();
  17696. clickInfo.singleClick = true;
  17697. return this._processPointerUp(pickResult, evt, clickInfo);
  17698. };
  17699. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  17700. if (pickResult && pickResult && pickResult.pickedMesh) {
  17701. this._pickedUpMesh = pickResult.pickedMesh;
  17702. if (this._pickedDownMesh === this._pickedUpMesh) {
  17703. if (this.onPointerPick) {
  17704. this.onPointerPick(evt, pickResult);
  17705. }
  17706. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  17707. var type = BABYLON.PointerEventTypes.POINTERPICK;
  17708. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17709. this.onPointerObservable.notifyObservers(pi, type);
  17710. }
  17711. }
  17712. if (pickResult.pickedMesh.actionManager) {
  17713. if (clickInfo.ignore) {
  17714. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17715. }
  17716. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  17717. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17718. }
  17719. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17720. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17721. }
  17722. }
  17723. }
  17724. if (this._pickedDownMesh &&
  17725. this._pickedDownMesh.actionManager &&
  17726. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  17727. this._pickedDownMesh !== this._pickedUpMesh) {
  17728. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  17729. }
  17730. if (this.onPointerUp) {
  17731. this.onPointerUp(evt, pickResult);
  17732. }
  17733. if (this.onPointerObservable.hasObservers()) {
  17734. if (!clickInfo.ignore) {
  17735. if (!clickInfo.hasSwiped) {
  17736. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17737. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17738. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17739. this.onPointerObservable.notifyObservers(pi, type);
  17740. }
  17741. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17742. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17743. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17744. this.onPointerObservable.notifyObservers(pi, type);
  17745. }
  17746. }
  17747. }
  17748. else {
  17749. var type = BABYLON.PointerEventTypes.POINTERUP;
  17750. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17751. this.onPointerObservable.notifyObservers(pi, type);
  17752. }
  17753. }
  17754. return this;
  17755. };
  17756. /**
  17757. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17758. * @param attachUp defines if you want to attach events to pointerup
  17759. * @param attachDown defines if you want to attach events to pointerdown
  17760. * @param attachMove defines if you want to attach events to pointermove
  17761. */
  17762. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17763. var _this = this;
  17764. if (attachUp === void 0) { attachUp = true; }
  17765. if (attachDown === void 0) { attachDown = true; }
  17766. if (attachMove === void 0) { attachMove = true; }
  17767. this._initActionManager = function (act, clickInfo) {
  17768. if (!_this._meshPickProceed) {
  17769. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17770. _this._currentPickResult = pickResult;
  17771. if (pickResult) {
  17772. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  17773. }
  17774. _this._meshPickProceed = true;
  17775. }
  17776. return act;
  17777. };
  17778. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  17779. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  17780. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  17781. btn !== _this._previousButtonPressed) {
  17782. _this._doubleClickOccured = false;
  17783. clickInfo.singleClick = true;
  17784. clickInfo.ignore = false;
  17785. cb(clickInfo, _this._currentPickResult);
  17786. }
  17787. };
  17788. this._initClickEvent = function (obs1, obs2, evt, cb) {
  17789. var clickInfo = new ClickInfo();
  17790. _this._currentPickResult = null;
  17791. var act;
  17792. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  17793. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  17794. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17795. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  17796. act = _this._initActionManager(act, clickInfo);
  17797. if (act)
  17798. checkPicking = act.hasPickTriggers;
  17799. }
  17800. if (checkPicking) {
  17801. var btn = evt.button;
  17802. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  17803. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  17804. if (!clickInfo.hasSwiped) {
  17805. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  17806. if (!checkSingleClickImmediately) {
  17807. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  17808. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17809. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17810. act = _this._initActionManager(act, clickInfo);
  17811. if (act)
  17812. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17813. }
  17814. }
  17815. if (checkSingleClickImmediately) {
  17816. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  17817. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  17818. btn !== _this._previousButtonPressed) {
  17819. clickInfo.singleClick = true;
  17820. cb(clickInfo, _this._currentPickResult);
  17821. }
  17822. }
  17823. else {
  17824. // wait that no double click has been raised during the double click delay
  17825. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17826. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  17827. }
  17828. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  17829. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17830. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17831. act = _this._initActionManager(act, clickInfo);
  17832. if (act)
  17833. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17834. }
  17835. if (checkDoubleClick) {
  17836. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  17837. if (btn === _this._previousButtonPressed &&
  17838. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  17839. !_this._doubleClickOccured) {
  17840. // pointer has not moved for 2 clicks, it's a double click
  17841. if (!clickInfo.hasSwiped &&
  17842. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  17843. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  17844. _this._previousStartingPointerTime = 0;
  17845. _this._doubleClickOccured = true;
  17846. clickInfo.doubleClick = true;
  17847. clickInfo.ignore = false;
  17848. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  17849. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  17850. }
  17851. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17852. cb(clickInfo, _this._currentPickResult);
  17853. }
  17854. else {
  17855. _this._doubleClickOccured = false;
  17856. _this._previousStartingPointerTime = _this._startingPointerTime;
  17857. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17858. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17859. _this._previousButtonPressed = btn;
  17860. _this._previousHasSwiped = clickInfo.hasSwiped;
  17861. if (Scene.ExclusiveDoubleClickMode) {
  17862. if (_this._previousDelayedSimpleClickTimeout) {
  17863. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  17864. }
  17865. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17866. cb(clickInfo, _this._previousPickResult);
  17867. }
  17868. else {
  17869. cb(clickInfo, _this._currentPickResult);
  17870. }
  17871. }
  17872. }
  17873. else {
  17874. _this._doubleClickOccured = false;
  17875. _this._previousStartingPointerTime = _this._startingPointerTime;
  17876. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17877. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17878. _this._previousButtonPressed = btn;
  17879. _this._previousHasSwiped = clickInfo.hasSwiped;
  17880. }
  17881. }
  17882. }
  17883. }
  17884. clickInfo.ignore = true;
  17885. cb(clickInfo, _this._currentPickResult);
  17886. };
  17887. this._spritePredicate = function (sprite) {
  17888. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17889. };
  17890. this._onPointerMove = function (evt) {
  17891. _this._updatePointerPosition(evt);
  17892. // PreObservable support
  17893. if (_this.onPrePointerObservable.hasObservers()) {
  17894. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17895. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17896. _this.onPrePointerObservable.notifyObservers(pi, type);
  17897. if (pi.skipOnPointerObservable) {
  17898. return;
  17899. }
  17900. }
  17901. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17902. return;
  17903. }
  17904. if (!_this.pointerMovePredicate) {
  17905. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  17906. }
  17907. // Meshes
  17908. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17909. _this._processPointerMove(pickResult, evt);
  17910. };
  17911. this._onPointerDown = function (evt) {
  17912. _this._totalPointersPressed++;
  17913. _this._pickedDownMesh = null;
  17914. _this._meshPickProceed = false;
  17915. _this._updatePointerPosition(evt);
  17916. if (_this.preventDefaultOnPointerDown) {
  17917. evt.preventDefault();
  17918. canvas.focus();
  17919. }
  17920. // PreObservable support
  17921. if (_this.onPrePointerObservable.hasObservers()) {
  17922. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17923. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17924. _this.onPrePointerObservable.notifyObservers(pi, type);
  17925. if (pi.skipOnPointerObservable) {
  17926. return;
  17927. }
  17928. }
  17929. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17930. return;
  17931. }
  17932. _this._startingPointerPosition.x = _this._pointerX;
  17933. _this._startingPointerPosition.y = _this._pointerY;
  17934. _this._startingPointerTime = new Date().getTime();
  17935. if (!_this.pointerDownPredicate) {
  17936. _this.pointerDownPredicate = function (mesh) {
  17937. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17938. };
  17939. }
  17940. // Meshes
  17941. _this._pickedDownMesh = null;
  17942. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17943. _this._processPointerDown(pickResult, evt);
  17944. // Sprites
  17945. _this._pickedDownSprite = null;
  17946. if (_this.spriteManagers.length > 0) {
  17947. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers);
  17948. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17949. if (pickResult.pickedSprite.actionManager) {
  17950. _this._pickedDownSprite = pickResult.pickedSprite;
  17951. switch (evt.button) {
  17952. case 0:
  17953. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17954. break;
  17955. case 1:
  17956. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17957. break;
  17958. case 2:
  17959. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17960. break;
  17961. }
  17962. if (pickResult.pickedSprite.actionManager) {
  17963. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17964. }
  17965. }
  17966. }
  17967. }
  17968. };
  17969. this._onPointerUp = function (evt) {
  17970. if (_this._totalPointersPressed === 0) {
  17971. return; // So we need to test it the pointer down was pressed before.
  17972. }
  17973. _this._totalPointersPressed--;
  17974. _this._pickedUpMesh = null;
  17975. _this._meshPickProceed = false;
  17976. _this._updatePointerPosition(evt);
  17977. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  17978. // PreObservable support
  17979. if (_this.onPrePointerObservable.hasObservers()) {
  17980. if (!clickInfo.ignore) {
  17981. if (!clickInfo.hasSwiped) {
  17982. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17983. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17984. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17985. _this.onPrePointerObservable.notifyObservers(pi, type);
  17986. if (pi.skipOnPointerObservable) {
  17987. return;
  17988. }
  17989. }
  17990. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17991. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17992. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17993. _this.onPrePointerObservable.notifyObservers(pi, type);
  17994. if (pi.skipOnPointerObservable) {
  17995. return;
  17996. }
  17997. }
  17998. }
  17999. }
  18000. else {
  18001. var type = BABYLON.PointerEventTypes.POINTERUP;
  18002. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18003. _this.onPrePointerObservable.notifyObservers(pi, type);
  18004. if (pi.skipOnPointerObservable) {
  18005. return;
  18006. }
  18007. }
  18008. }
  18009. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18010. return;
  18011. }
  18012. if (!_this.pointerUpPredicate) {
  18013. _this.pointerUpPredicate = function (mesh) {
  18014. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18015. };
  18016. }
  18017. // Meshes
  18018. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  18019. _this._initActionManager(null, clickInfo);
  18020. }
  18021. if (!pickResult) {
  18022. pickResult = _this._currentPickResult;
  18023. }
  18024. _this._processPointerUp(pickResult, evt, clickInfo);
  18025. // Sprites
  18026. if (_this.spriteManagers.length > 0) {
  18027. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers);
  18028. if (pickResult.hit && pickResult.pickedSprite) {
  18029. if (pickResult.pickedSprite.actionManager) {
  18030. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18031. if (pickResult.pickedSprite.actionManager) {
  18032. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  18033. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18034. }
  18035. }
  18036. }
  18037. }
  18038. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== pickResult.pickedSprite) {
  18039. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  18040. }
  18041. }
  18042. _this._previousPickResult = _this._currentPickResult;
  18043. });
  18044. };
  18045. this._onKeyDown = function (evt) {
  18046. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  18047. if (_this.onPreKeyboardObservable.hasObservers()) {
  18048. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18049. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18050. if (pi.skipOnPointerObservable) {
  18051. return;
  18052. }
  18053. }
  18054. if (_this.onKeyboardObservable.hasObservers()) {
  18055. var pi = new BABYLON.KeyboardInfo(type, evt);
  18056. _this.onKeyboardObservable.notifyObservers(pi, type);
  18057. }
  18058. if (_this.actionManager) {
  18059. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18060. }
  18061. };
  18062. this._onKeyUp = function (evt) {
  18063. var type = BABYLON.KeyboardEventTypes.KEYUP;
  18064. if (_this.onPreKeyboardObservable.hasObservers()) {
  18065. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18066. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18067. if (pi.skipOnPointerObservable) {
  18068. return;
  18069. }
  18070. }
  18071. if (_this.onKeyboardObservable.hasObservers()) {
  18072. var pi = new BABYLON.KeyboardInfo(type, evt);
  18073. _this.onKeyboardObservable.notifyObservers(pi, type);
  18074. }
  18075. if (_this.actionManager) {
  18076. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18077. }
  18078. };
  18079. var engine = this.getEngine();
  18080. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  18081. canvas.addEventListener("keydown", _this._onKeyDown, false);
  18082. canvas.addEventListener("keyup", _this._onKeyUp, false);
  18083. });
  18084. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  18085. canvas.removeEventListener("keydown", _this._onKeyDown);
  18086. canvas.removeEventListener("keyup", _this._onKeyUp);
  18087. });
  18088. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18089. var canvas = this._engine.getRenderingCanvas();
  18090. if (attachMove) {
  18091. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  18092. // Wheel
  18093. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  18094. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  18095. }
  18096. if (attachDown) {
  18097. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  18098. }
  18099. if (attachUp) {
  18100. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  18101. }
  18102. canvas.tabIndex = 1;
  18103. };
  18104. Scene.prototype.detachControl = function () {
  18105. var engine = this.getEngine();
  18106. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18107. var canvas = engine.getRenderingCanvas();
  18108. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  18109. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  18110. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  18111. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  18112. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  18113. // Wheel
  18114. canvas.removeEventListener('mousewheel', this._onPointerMove);
  18115. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  18116. // Keyboard
  18117. canvas.removeEventListener("keydown", this._onKeyDown);
  18118. canvas.removeEventListener("keyup", this._onKeyUp);
  18119. // Observables
  18120. this.onKeyboardObservable.clear();
  18121. this.onPreKeyboardObservable.clear();
  18122. this.onPointerObservable.clear();
  18123. this.onPrePointerObservable.clear();
  18124. };
  18125. // Ready
  18126. Scene.prototype.isReady = function () {
  18127. if (this._pendingData.length > 0) {
  18128. return false;
  18129. }
  18130. var index;
  18131. // Geometries
  18132. for (index = 0; index < this._geometries.length; index++) {
  18133. var geometry = this._geometries[index];
  18134. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18135. return false;
  18136. }
  18137. }
  18138. // Meshes
  18139. for (index = 0; index < this.meshes.length; index++) {
  18140. var mesh = this.meshes[index];
  18141. if (!mesh.isEnabled()) {
  18142. continue;
  18143. }
  18144. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  18145. continue;
  18146. }
  18147. if (!mesh.isReady()) {
  18148. return false;
  18149. }
  18150. var mat = mesh.material;
  18151. if (mat) {
  18152. if (!mat.isReady(mesh)) {
  18153. return false;
  18154. }
  18155. }
  18156. }
  18157. return true;
  18158. };
  18159. Scene.prototype.resetCachedMaterial = function () {
  18160. this._cachedMaterial = null;
  18161. this._cachedEffect = null;
  18162. this._cachedVisibility = null;
  18163. };
  18164. Scene.prototype.registerBeforeRender = function (func) {
  18165. this.onBeforeRenderObservable.add(func);
  18166. };
  18167. Scene.prototype.unregisterBeforeRender = function (func) {
  18168. this.onBeforeRenderObservable.removeCallback(func);
  18169. };
  18170. Scene.prototype.registerAfterRender = function (func) {
  18171. this.onAfterRenderObservable.add(func);
  18172. };
  18173. Scene.prototype.unregisterAfterRender = function (func) {
  18174. this.onAfterRenderObservable.removeCallback(func);
  18175. };
  18176. Scene.prototype._addPendingData = function (data) {
  18177. this._pendingData.push(data);
  18178. };
  18179. Scene.prototype._removePendingData = function (data) {
  18180. var index = this._pendingData.indexOf(data);
  18181. if (index !== -1) {
  18182. this._pendingData.splice(index, 1);
  18183. }
  18184. };
  18185. Scene.prototype.getWaitingItemsCount = function () {
  18186. return this._pendingData.length;
  18187. };
  18188. /**
  18189. * Registers a function to be executed when the scene is ready.
  18190. * @param {Function} func - the function to be executed.
  18191. */
  18192. Scene.prototype.executeWhenReady = function (func) {
  18193. var _this = this;
  18194. this.onReadyObservable.add(func);
  18195. if (this._executeWhenReadyTimeoutId !== -1) {
  18196. return;
  18197. }
  18198. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18199. _this._checkIsReady();
  18200. }, 150);
  18201. };
  18202. Scene.prototype._checkIsReady = function () {
  18203. var _this = this;
  18204. if (this.isReady()) {
  18205. this.onReadyObservable.notifyObservers(this);
  18206. this.onReadyObservable.clear();
  18207. this._executeWhenReadyTimeoutId = -1;
  18208. return;
  18209. }
  18210. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18211. _this._checkIsReady();
  18212. }, 150);
  18213. };
  18214. // Animations
  18215. /**
  18216. * Will start the animation sequence of a given target
  18217. * @param target - the target
  18218. * @param {number} from - from which frame should animation start
  18219. * @param {number} to - till which frame should animation run.
  18220. * @param {boolean} [loop] - should the animation loop
  18221. * @param {number} [speedRatio] - the speed in which to run the animation
  18222. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  18223. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  18224. * Returns {BABYLON.Animatable} the animatable object created for this animation
  18225. * See BABYLON.Animatable
  18226. */
  18227. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  18228. if (speedRatio === void 0) { speedRatio = 1.0; }
  18229. if (from > to && speedRatio > 0) {
  18230. speedRatio *= -1;
  18231. }
  18232. this.stopAnimation(target);
  18233. if (!animatable) {
  18234. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  18235. }
  18236. // Local animations
  18237. if (target.animations) {
  18238. animatable.appendAnimations(target, target.animations);
  18239. }
  18240. // Children animations
  18241. if (target.getAnimatables) {
  18242. var animatables = target.getAnimatables();
  18243. for (var index = 0; index < animatables.length; index++) {
  18244. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  18245. }
  18246. }
  18247. animatable.reset();
  18248. return animatable;
  18249. };
  18250. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  18251. if (speedRatio === undefined) {
  18252. speedRatio = 1.0;
  18253. }
  18254. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  18255. return animatable;
  18256. };
  18257. Scene.prototype.getAnimatableByTarget = function (target) {
  18258. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18259. if (this._activeAnimatables[index].target === target) {
  18260. return this._activeAnimatables[index];
  18261. }
  18262. }
  18263. return null;
  18264. };
  18265. Object.defineProperty(Scene.prototype, "Animatables", {
  18266. get: function () {
  18267. return this._activeAnimatables;
  18268. },
  18269. enumerable: true,
  18270. configurable: true
  18271. });
  18272. /**
  18273. * Will stop the animation of the given target
  18274. * @param target - the target
  18275. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  18276. * @see beginAnimation
  18277. */
  18278. Scene.prototype.stopAnimation = function (target, animationName) {
  18279. var animatable = this.getAnimatableByTarget(target);
  18280. if (animatable) {
  18281. animatable.stop(animationName);
  18282. }
  18283. };
  18284. Scene.prototype._animate = function () {
  18285. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  18286. return;
  18287. }
  18288. // Getting time
  18289. var now = BABYLON.Tools.Now;
  18290. if (!this._animationTimeLast) {
  18291. if (this._pendingData.length > 0) {
  18292. return;
  18293. }
  18294. this._animationTimeLast = now;
  18295. }
  18296. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  18297. this._animationTime += deltaTime;
  18298. this._animationTimeLast = now;
  18299. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18300. this._activeAnimatables[index]._animate(this._animationTime);
  18301. }
  18302. };
  18303. // Matrix
  18304. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  18305. this._useAlternateCameraConfiguration = active;
  18306. };
  18307. Scene.prototype.getViewMatrix = function () {
  18308. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  18309. };
  18310. Scene.prototype.getProjectionMatrix = function () {
  18311. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  18312. };
  18313. Scene.prototype.getTransformMatrix = function () {
  18314. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  18315. };
  18316. Scene.prototype.setTransformMatrix = function (view, projection) {
  18317. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  18318. return;
  18319. }
  18320. this._viewUpdateFlag = view.updateFlag;
  18321. this._projectionUpdateFlag = projection.updateFlag;
  18322. this._viewMatrix = view;
  18323. this._projectionMatrix = projection;
  18324. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18325. // Update frustum
  18326. if (!this._frustumPlanes) {
  18327. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18328. }
  18329. else {
  18330. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18331. }
  18332. if (this.activeCamera._alternateCamera) {
  18333. var otherCamera = this.activeCamera._alternateCamera;
  18334. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  18335. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  18336. }
  18337. if (this._sceneUbo.useUbo) {
  18338. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  18339. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  18340. this._sceneUbo.update();
  18341. }
  18342. };
  18343. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  18344. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  18345. return;
  18346. }
  18347. this._alternateViewUpdateFlag = view.updateFlag;
  18348. this._alternateProjectionUpdateFlag = projection.updateFlag;
  18349. this._alternateViewMatrix = view;
  18350. this._alternateProjectionMatrix = projection;
  18351. if (!this._alternateTransformMatrix) {
  18352. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  18353. }
  18354. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  18355. if (!this._alternateSceneUbo) {
  18356. this._createAlternateUbo();
  18357. }
  18358. if (this._alternateSceneUbo.useUbo) {
  18359. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  18360. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  18361. this._alternateSceneUbo.update();
  18362. }
  18363. };
  18364. Scene.prototype.getSceneUniformBuffer = function () {
  18365. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  18366. };
  18367. // Methods
  18368. Scene.prototype.getUniqueId = function () {
  18369. var result = Scene._uniqueIdCounter;
  18370. Scene._uniqueIdCounter++;
  18371. return result;
  18372. };
  18373. Scene.prototype.addMesh = function (newMesh) {
  18374. this.meshes.push(newMesh);
  18375. //notify the collision coordinator
  18376. if (this.collisionCoordinator) {
  18377. this.collisionCoordinator.onMeshAdded(newMesh);
  18378. }
  18379. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  18380. };
  18381. Scene.prototype.removeMesh = function (toRemove) {
  18382. var index = this.meshes.indexOf(toRemove);
  18383. if (index !== -1) {
  18384. // Remove from the scene if mesh found
  18385. this.meshes.splice(index, 1);
  18386. }
  18387. //notify the collision coordinator
  18388. if (this.collisionCoordinator) {
  18389. this.collisionCoordinator.onMeshRemoved(toRemove);
  18390. }
  18391. this.onMeshRemovedObservable.notifyObservers(toRemove);
  18392. return index;
  18393. };
  18394. Scene.prototype.removeSkeleton = function (toRemove) {
  18395. var index = this.skeletons.indexOf(toRemove);
  18396. if (index !== -1) {
  18397. // Remove from the scene if found
  18398. this.skeletons.splice(index, 1);
  18399. }
  18400. return index;
  18401. };
  18402. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  18403. var index = this.morphTargetManagers.indexOf(toRemove);
  18404. if (index !== -1) {
  18405. // Remove from the scene if found
  18406. this.morphTargetManagers.splice(index, 1);
  18407. }
  18408. return index;
  18409. };
  18410. Scene.prototype.removeLight = function (toRemove) {
  18411. var index = this.lights.indexOf(toRemove);
  18412. if (index !== -1) {
  18413. // Remove from the scene if mesh found
  18414. this.lights.splice(index, 1);
  18415. this.sortLightsByPriority();
  18416. }
  18417. this.onLightRemovedObservable.notifyObservers(toRemove);
  18418. return index;
  18419. };
  18420. Scene.prototype.removeCamera = function (toRemove) {
  18421. var index = this.cameras.indexOf(toRemove);
  18422. if (index !== -1) {
  18423. // Remove from the scene if mesh found
  18424. this.cameras.splice(index, 1);
  18425. }
  18426. // Remove from activeCameras
  18427. var index2 = this.activeCameras.indexOf(toRemove);
  18428. if (index2 !== -1) {
  18429. // Remove from the scene if mesh found
  18430. this.activeCameras.splice(index2, 1);
  18431. }
  18432. // Reset the activeCamera
  18433. if (this.activeCamera === toRemove) {
  18434. if (this.cameras.length > 0) {
  18435. this.activeCamera = this.cameras[0];
  18436. }
  18437. else {
  18438. this.activeCamera = null;
  18439. }
  18440. }
  18441. this.onCameraRemovedObservable.notifyObservers(toRemove);
  18442. return index;
  18443. };
  18444. Scene.prototype.addLight = function (newLight) {
  18445. this.lights.push(newLight);
  18446. this.sortLightsByPriority();
  18447. this.onNewLightAddedObservable.notifyObservers(newLight);
  18448. };
  18449. Scene.prototype.sortLightsByPriority = function () {
  18450. if (this.requireLightSorting) {
  18451. this.lights.sort(BABYLON.Light.compareLightsPriority);
  18452. }
  18453. };
  18454. Scene.prototype.addCamera = function (newCamera) {
  18455. this.cameras.push(newCamera);
  18456. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  18457. };
  18458. /**
  18459. * Switch active camera
  18460. * @param {Camera} newCamera - new active camera
  18461. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  18462. */
  18463. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  18464. if (attachControl === void 0) { attachControl = true; }
  18465. var canvas = this._engine.getRenderingCanvas();
  18466. this.activeCamera.detachControl(canvas);
  18467. this.activeCamera = newCamera;
  18468. if (attachControl) {
  18469. newCamera.attachControl(canvas);
  18470. }
  18471. };
  18472. /**
  18473. * sets the active camera of the scene using its ID
  18474. * @param {string} id - the camera's ID
  18475. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18476. * @see activeCamera
  18477. */
  18478. Scene.prototype.setActiveCameraByID = function (id) {
  18479. var camera = this.getCameraByID(id);
  18480. if (camera) {
  18481. this.activeCamera = camera;
  18482. return camera;
  18483. }
  18484. return null;
  18485. };
  18486. /**
  18487. * sets the active camera of the scene using its name
  18488. * @param {string} name - the camera's name
  18489. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18490. * @see activeCamera
  18491. */
  18492. Scene.prototype.setActiveCameraByName = function (name) {
  18493. var camera = this.getCameraByName(name);
  18494. if (camera) {
  18495. this.activeCamera = camera;
  18496. return camera;
  18497. }
  18498. return null;
  18499. };
  18500. /**
  18501. * get a material using its id
  18502. * @param {string} the material's ID
  18503. * @return {BABYLON.Material|null} the material or null if none found.
  18504. */
  18505. Scene.prototype.getMaterialByID = function (id) {
  18506. for (var index = 0; index < this.materials.length; index++) {
  18507. if (this.materials[index].id === id) {
  18508. return this.materials[index];
  18509. }
  18510. }
  18511. return null;
  18512. };
  18513. /**
  18514. * get a material using its name
  18515. * @param {string} the material's name
  18516. * @return {BABYLON.Material|null} the material or null if none found.
  18517. */
  18518. Scene.prototype.getMaterialByName = function (name) {
  18519. for (var index = 0; index < this.materials.length; index++) {
  18520. if (this.materials[index].name === name) {
  18521. return this.materials[index];
  18522. }
  18523. }
  18524. return null;
  18525. };
  18526. Scene.prototype.getLensFlareSystemByName = function (name) {
  18527. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18528. if (this.lensFlareSystems[index].name === name) {
  18529. return this.lensFlareSystems[index];
  18530. }
  18531. }
  18532. return null;
  18533. };
  18534. Scene.prototype.getLensFlareSystemByID = function (id) {
  18535. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18536. if (this.lensFlareSystems[index].id === id) {
  18537. return this.lensFlareSystems[index];
  18538. }
  18539. }
  18540. return null;
  18541. };
  18542. Scene.prototype.getCameraByID = function (id) {
  18543. for (var index = 0; index < this.cameras.length; index++) {
  18544. if (this.cameras[index].id === id) {
  18545. return this.cameras[index];
  18546. }
  18547. }
  18548. return null;
  18549. };
  18550. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  18551. for (var index = 0; index < this.cameras.length; index++) {
  18552. if (this.cameras[index].uniqueId === uniqueId) {
  18553. return this.cameras[index];
  18554. }
  18555. }
  18556. return null;
  18557. };
  18558. /**
  18559. * get a camera using its name
  18560. * @param {string} the camera's name
  18561. * @return {BABYLON.Camera|null} the camera or null if none found.
  18562. */
  18563. Scene.prototype.getCameraByName = function (name) {
  18564. for (var index = 0; index < this.cameras.length; index++) {
  18565. if (this.cameras[index].name === name) {
  18566. return this.cameras[index];
  18567. }
  18568. }
  18569. return null;
  18570. };
  18571. /**
  18572. * get a bone using its id
  18573. * @param {string} the bone's id
  18574. * @return {BABYLON.Bone|null} the bone or null if not found
  18575. */
  18576. Scene.prototype.getBoneByID = function (id) {
  18577. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18578. var skeleton = this.skeletons[skeletonIndex];
  18579. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18580. if (skeleton.bones[boneIndex].id === id) {
  18581. return skeleton.bones[boneIndex];
  18582. }
  18583. }
  18584. }
  18585. return null;
  18586. };
  18587. /**
  18588. * get a bone using its id
  18589. * @param {string} the bone's name
  18590. * @return {BABYLON.Bone|null} the bone or null if not found
  18591. */
  18592. Scene.prototype.getBoneByName = function (name) {
  18593. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18594. var skeleton = this.skeletons[skeletonIndex];
  18595. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18596. if (skeleton.bones[boneIndex].name === name) {
  18597. return skeleton.bones[boneIndex];
  18598. }
  18599. }
  18600. }
  18601. return null;
  18602. };
  18603. /**
  18604. * get a light node using its name
  18605. * @param {string} the light's name
  18606. * @return {BABYLON.Light|null} the light or null if none found.
  18607. */
  18608. Scene.prototype.getLightByName = function (name) {
  18609. for (var index = 0; index < this.lights.length; index++) {
  18610. if (this.lights[index].name === name) {
  18611. return this.lights[index];
  18612. }
  18613. }
  18614. return null;
  18615. };
  18616. /**
  18617. * get a light node using its ID
  18618. * @param {string} the light's id
  18619. * @return {BABYLON.Light|null} the light or null if none found.
  18620. */
  18621. Scene.prototype.getLightByID = function (id) {
  18622. for (var index = 0; index < this.lights.length; index++) {
  18623. if (this.lights[index].id === id) {
  18624. return this.lights[index];
  18625. }
  18626. }
  18627. return null;
  18628. };
  18629. /**
  18630. * get a light node using its scene-generated unique ID
  18631. * @param {number} the light's unique id
  18632. * @return {BABYLON.Light|null} the light or null if none found.
  18633. */
  18634. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  18635. for (var index = 0; index < this.lights.length; index++) {
  18636. if (this.lights[index].uniqueId === uniqueId) {
  18637. return this.lights[index];
  18638. }
  18639. }
  18640. return null;
  18641. };
  18642. /**
  18643. * get a particle system by id
  18644. * @param id {number} the particle system id
  18645. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  18646. */
  18647. Scene.prototype.getParticleSystemByID = function (id) {
  18648. for (var index = 0; index < this.particleSystems.length; index++) {
  18649. if (this.particleSystems[index].id === id) {
  18650. return this.particleSystems[index];
  18651. }
  18652. }
  18653. return null;
  18654. };
  18655. /**
  18656. * get a geometry using its ID
  18657. * @param {string} the geometry's id
  18658. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  18659. */
  18660. Scene.prototype.getGeometryByID = function (id) {
  18661. for (var index = 0; index < this._geometries.length; index++) {
  18662. if (this._geometries[index].id === id) {
  18663. return this._geometries[index];
  18664. }
  18665. }
  18666. return null;
  18667. };
  18668. /**
  18669. * add a new geometry to this scene.
  18670. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  18671. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  18672. * @return {boolean} was the geometry added or not
  18673. */
  18674. Scene.prototype.pushGeometry = function (geometry, force) {
  18675. if (!force && this.getGeometryByID(geometry.id)) {
  18676. return false;
  18677. }
  18678. this._geometries.push(geometry);
  18679. //notify the collision coordinator
  18680. if (this.collisionCoordinator) {
  18681. this.collisionCoordinator.onGeometryAdded(geometry);
  18682. }
  18683. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  18684. return true;
  18685. };
  18686. /**
  18687. * Removes an existing geometry
  18688. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18689. * @return {boolean} was the geometry removed or not
  18690. */
  18691. Scene.prototype.removeGeometry = function (geometry) {
  18692. var index = this._geometries.indexOf(geometry);
  18693. if (index > -1) {
  18694. this._geometries.splice(index, 1);
  18695. //notify the collision coordinator
  18696. if (this.collisionCoordinator) {
  18697. this.collisionCoordinator.onGeometryDeleted(geometry);
  18698. }
  18699. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18700. return true;
  18701. }
  18702. return false;
  18703. };
  18704. Scene.prototype.getGeometries = function () {
  18705. return this._geometries;
  18706. };
  18707. /**
  18708. * Get the first added mesh found of a given ID
  18709. * @param {string} id - the id to search for
  18710. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18711. */
  18712. Scene.prototype.getMeshByID = function (id) {
  18713. for (var index = 0; index < this.meshes.length; index++) {
  18714. if (this.meshes[index].id === id) {
  18715. return this.meshes[index];
  18716. }
  18717. }
  18718. return null;
  18719. };
  18720. Scene.prototype.getMeshesByID = function (id) {
  18721. return this.meshes.filter(function (m) {
  18722. return m.id === id;
  18723. });
  18724. };
  18725. /**
  18726. * Get a mesh with its auto-generated unique id
  18727. * @param {number} uniqueId - the unique id to search for
  18728. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18729. */
  18730. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18731. for (var index = 0; index < this.meshes.length; index++) {
  18732. if (this.meshes[index].uniqueId === uniqueId) {
  18733. return this.meshes[index];
  18734. }
  18735. }
  18736. return null;
  18737. };
  18738. /**
  18739. * Get a the last added mesh found of a given ID
  18740. * @param {string} id - the id to search for
  18741. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18742. */
  18743. Scene.prototype.getLastMeshByID = function (id) {
  18744. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18745. if (this.meshes[index].id === id) {
  18746. return this.meshes[index];
  18747. }
  18748. }
  18749. return null;
  18750. };
  18751. /**
  18752. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18753. * @param {string} id - the id to search for
  18754. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18755. */
  18756. Scene.prototype.getLastEntryByID = function (id) {
  18757. var index;
  18758. for (index = this.meshes.length - 1; index >= 0; index--) {
  18759. if (this.meshes[index].id === id) {
  18760. return this.meshes[index];
  18761. }
  18762. }
  18763. for (index = this.cameras.length - 1; index >= 0; index--) {
  18764. if (this.cameras[index].id === id) {
  18765. return this.cameras[index];
  18766. }
  18767. }
  18768. for (index = this.lights.length - 1; index >= 0; index--) {
  18769. if (this.lights[index].id === id) {
  18770. return this.lights[index];
  18771. }
  18772. }
  18773. return null;
  18774. };
  18775. Scene.prototype.getNodeByID = function (id) {
  18776. var mesh = this.getMeshByID(id);
  18777. if (mesh) {
  18778. return mesh;
  18779. }
  18780. var light = this.getLightByID(id);
  18781. if (light) {
  18782. return light;
  18783. }
  18784. var camera = this.getCameraByID(id);
  18785. if (camera) {
  18786. return camera;
  18787. }
  18788. var bone = this.getBoneByID(id);
  18789. return bone;
  18790. };
  18791. Scene.prototype.getNodeByName = function (name) {
  18792. var mesh = this.getMeshByName(name);
  18793. if (mesh) {
  18794. return mesh;
  18795. }
  18796. var light = this.getLightByName(name);
  18797. if (light) {
  18798. return light;
  18799. }
  18800. var camera = this.getCameraByName(name);
  18801. if (camera) {
  18802. return camera;
  18803. }
  18804. var bone = this.getBoneByName(name);
  18805. return bone;
  18806. };
  18807. Scene.prototype.getMeshByName = function (name) {
  18808. for (var index = 0; index < this.meshes.length; index++) {
  18809. if (this.meshes[index].name === name) {
  18810. return this.meshes[index];
  18811. }
  18812. }
  18813. return null;
  18814. };
  18815. Scene.prototype.getSoundByName = function (name) {
  18816. var index;
  18817. if (BABYLON.AudioEngine) {
  18818. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18819. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18820. return this.mainSoundTrack.soundCollection[index];
  18821. }
  18822. }
  18823. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18824. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18825. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18826. return this.soundTracks[sdIndex].soundCollection[index];
  18827. }
  18828. }
  18829. }
  18830. }
  18831. return null;
  18832. };
  18833. Scene.prototype.getLastSkeletonByID = function (id) {
  18834. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18835. if (this.skeletons[index].id === id) {
  18836. return this.skeletons[index];
  18837. }
  18838. }
  18839. return null;
  18840. };
  18841. Scene.prototype.getSkeletonById = function (id) {
  18842. for (var index = 0; index < this.skeletons.length; index++) {
  18843. if (this.skeletons[index].id === id) {
  18844. return this.skeletons[index];
  18845. }
  18846. }
  18847. return null;
  18848. };
  18849. Scene.prototype.getSkeletonByName = function (name) {
  18850. for (var index = 0; index < this.skeletons.length; index++) {
  18851. if (this.skeletons[index].name === name) {
  18852. return this.skeletons[index];
  18853. }
  18854. }
  18855. return null;
  18856. };
  18857. Scene.prototype.getMorphTargetManagerById = function (id) {
  18858. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  18859. if (this.morphTargetManagers[index].uniqueId === id) {
  18860. return this.morphTargetManagers[index];
  18861. }
  18862. }
  18863. return null;
  18864. };
  18865. Scene.prototype.isActiveMesh = function (mesh) {
  18866. return (this._activeMeshes.indexOf(mesh) !== -1);
  18867. };
  18868. /**
  18869. * Return a the first highlight layer of the scene with a given name.
  18870. * @param name The name of the highlight layer to look for.
  18871. * @return The highlight layer if found otherwise null.
  18872. */
  18873. Scene.prototype.getHighlightLayerByName = function (name) {
  18874. for (var index = 0; index < this.highlightLayers.length; index++) {
  18875. if (this.highlightLayers[index].name === name) {
  18876. return this.highlightLayers[index];
  18877. }
  18878. }
  18879. return null;
  18880. };
  18881. Object.defineProperty(Scene.prototype, "uid", {
  18882. /**
  18883. * Return a unique id as a string which can serve as an identifier for the scene
  18884. */
  18885. get: function () {
  18886. if (!this._uid) {
  18887. this._uid = BABYLON.Tools.RandomId();
  18888. }
  18889. return this._uid;
  18890. },
  18891. enumerable: true,
  18892. configurable: true
  18893. });
  18894. /**
  18895. * Add an externaly attached data from its key.
  18896. * This method call will fail and return false, if such key already exists.
  18897. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18898. * @param key the unique key that identifies the data
  18899. * @param data the data object to associate to the key for this Engine instance
  18900. * @return true if no such key were already present and the data was added successfully, false otherwise
  18901. */
  18902. Scene.prototype.addExternalData = function (key, data) {
  18903. if (!this._externalData) {
  18904. this._externalData = new BABYLON.StringDictionary();
  18905. }
  18906. return this._externalData.add(key, data);
  18907. };
  18908. /**
  18909. * Get an externaly attached data from its key
  18910. * @param key the unique key that identifies the data
  18911. * @return the associated data, if present (can be null), or undefined if not present
  18912. */
  18913. Scene.prototype.getExternalData = function (key) {
  18914. if (!this._externalData) {
  18915. return null;
  18916. }
  18917. return this._externalData.get(key);
  18918. };
  18919. /**
  18920. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18921. * @param key the unique key that identifies the data
  18922. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18923. * @return the associated data, can be null if the factory returned null.
  18924. */
  18925. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18926. if (!this._externalData) {
  18927. this._externalData = new BABYLON.StringDictionary();
  18928. }
  18929. return this._externalData.getOrAddWithFactory(key, factory);
  18930. };
  18931. /**
  18932. * Remove an externaly attached data from the Engine instance
  18933. * @param key the unique key that identifies the data
  18934. * @return true if the data was successfully removed, false if it doesn't exist
  18935. */
  18936. Scene.prototype.removeExternalData = function (key) {
  18937. return this._externalData.remove(key);
  18938. };
  18939. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18940. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18941. var material = subMesh.getMaterial();
  18942. if (mesh.showSubMeshesBoundingBox) {
  18943. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  18944. }
  18945. if (material) {
  18946. // Render targets
  18947. if (material.getRenderTargetTextures) {
  18948. if (this._processedMaterials.indexOf(material) === -1) {
  18949. this._processedMaterials.push(material);
  18950. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18951. }
  18952. }
  18953. // Dispatch
  18954. this._activeIndices.addCount(subMesh.indexCount, false);
  18955. this._renderingManager.dispatch(subMesh);
  18956. }
  18957. }
  18958. };
  18959. Scene.prototype._isInIntermediateRendering = function () {
  18960. return this._intermediateRendering;
  18961. };
  18962. /**
  18963. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  18964. */
  18965. Scene.prototype.freezeActiveMeshes = function () {
  18966. this._evaluateActiveMeshes();
  18967. this._activeMeshesFrozen = true;
  18968. return this;
  18969. };
  18970. /**
  18971. * Use this function to restart evaluating active meshes on every frame
  18972. */
  18973. Scene.prototype.unfreezeActiveMeshes = function () {
  18974. this._activeMeshesFrozen = false;
  18975. return this;
  18976. };
  18977. Scene.prototype._evaluateActiveMeshes = function () {
  18978. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  18979. return;
  18980. }
  18981. this.activeCamera._activeMeshes.reset();
  18982. this._activeMeshes.reset();
  18983. this._renderingManager.reset();
  18984. this._processedMaterials.reset();
  18985. this._activeParticleSystems.reset();
  18986. this._activeSkeletons.reset();
  18987. this._softwareSkinnedMeshes.reset();
  18988. if (this._boundingBoxRenderer) {
  18989. this._boundingBoxRenderer.reset();
  18990. }
  18991. // Meshes
  18992. var meshes;
  18993. var len;
  18994. if (this._selectionOctree) {
  18995. var selection = this._selectionOctree.select(this._frustumPlanes);
  18996. meshes = selection.data;
  18997. len = selection.length;
  18998. }
  18999. else {
  19000. len = this.meshes.length;
  19001. meshes = this.meshes;
  19002. }
  19003. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  19004. var mesh = meshes[meshIndex];
  19005. if (mesh.isBlocked) {
  19006. continue;
  19007. }
  19008. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  19009. if (!mesh.isReady() || !mesh.isEnabled()) {
  19010. continue;
  19011. }
  19012. mesh.computeWorldMatrix();
  19013. // Intersections
  19014. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  19015. this._meshesForIntersections.pushNoDuplicate(mesh);
  19016. }
  19017. // Switch to current LOD
  19018. var meshLOD = mesh.getLOD(this.activeCamera);
  19019. if (!meshLOD) {
  19020. continue;
  19021. }
  19022. mesh._preActivate();
  19023. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  19024. this._activeMeshes.push(mesh);
  19025. this.activeCamera._activeMeshes.push(mesh);
  19026. mesh._activate(this._renderId);
  19027. if (meshLOD !== mesh) {
  19028. meshLOD._activate(this._renderId);
  19029. }
  19030. this._activeMesh(mesh, meshLOD);
  19031. }
  19032. }
  19033. // Particle systems
  19034. this._particlesDuration.beginMonitoring();
  19035. if (this.particlesEnabled) {
  19036. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  19037. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  19038. var particleSystem = this.particleSystems[particleIndex];
  19039. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  19040. continue;
  19041. }
  19042. var emitter = particleSystem.emitter;
  19043. if (!emitter.position || emitter.isEnabled()) {
  19044. this._activeParticleSystems.push(particleSystem);
  19045. particleSystem.animate();
  19046. this._renderingManager.dispatchParticles(particleSystem);
  19047. }
  19048. }
  19049. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  19050. }
  19051. this._particlesDuration.endMonitoring(false);
  19052. };
  19053. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  19054. if (mesh.skeleton && this.skeletonsEnabled) {
  19055. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  19056. mesh.skeleton.prepare();
  19057. }
  19058. if (!mesh.computeBonesUsingShaders) {
  19059. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  19060. }
  19061. }
  19062. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  19063. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  19064. }
  19065. if (mesh && mesh.subMeshes) {
  19066. // Submeshes Octrees
  19067. var len;
  19068. var subMeshes;
  19069. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  19070. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  19071. len = intersections.length;
  19072. subMeshes = intersections.data;
  19073. }
  19074. else {
  19075. subMeshes = mesh.subMeshes;
  19076. len = subMeshes.length;
  19077. }
  19078. for (var subIndex = 0; subIndex < len; subIndex++) {
  19079. var subMesh = subMeshes[subIndex];
  19080. this._evaluateSubMesh(subMesh, mesh);
  19081. }
  19082. }
  19083. };
  19084. Scene.prototype.updateTransformMatrix = function (force) {
  19085. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  19086. };
  19087. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  19088. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  19089. };
  19090. Scene.prototype._renderForCamera = function (camera) {
  19091. if (camera && camera._skipRendering) {
  19092. return;
  19093. }
  19094. var engine = this._engine;
  19095. this.activeCamera = camera;
  19096. if (!this.activeCamera)
  19097. throw new Error("Active camera not set");
  19098. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19099. // Viewport
  19100. engine.setViewport(this.activeCamera.viewport);
  19101. // Camera
  19102. this.resetCachedMaterial();
  19103. this._renderId++;
  19104. this.activeCamera.update();
  19105. this.updateTransformMatrix();
  19106. if (camera._alternateCamera) {
  19107. this.updateAlternateTransformMatrix(camera._alternateCamera);
  19108. this._alternateRendering = true;
  19109. }
  19110. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  19111. // Meshes
  19112. this._evaluateActiveMeshesDuration.beginMonitoring();
  19113. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  19114. this._evaluateActiveMeshes();
  19115. this._evaluateActiveMeshesDuration.endMonitoring(false);
  19116. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  19117. // Software skinning
  19118. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  19119. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  19120. mesh.applySkeleton(mesh.skeleton);
  19121. }
  19122. // Render targets
  19123. this._renderTargetsDuration.beginMonitoring();
  19124. var needsRestoreFrameBuffer = false;
  19125. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  19126. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  19127. }
  19128. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  19129. this._intermediateRendering = true;
  19130. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19131. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  19132. var renderTarget = this._renderTargets.data[renderIndex];
  19133. if (renderTarget._shouldRender()) {
  19134. this._renderId++;
  19135. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  19136. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  19137. }
  19138. }
  19139. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19140. this._intermediateRendering = false;
  19141. this._renderId++;
  19142. needsRestoreFrameBuffer = true; // Restore back buffer
  19143. }
  19144. // Render HighlightLayer Texture
  19145. var stencilState = this._engine.getStencilBuffer();
  19146. var renderhighlights = false;
  19147. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  19148. this._intermediateRendering = true;
  19149. for (var i = 0; i < this.highlightLayers.length; i++) {
  19150. var highlightLayer = this.highlightLayers[i];
  19151. if (highlightLayer.shouldRender() &&
  19152. (!highlightLayer.camera ||
  19153. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  19154. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  19155. renderhighlights = true;
  19156. var renderTarget = highlightLayer._mainTexture;
  19157. if (renderTarget._shouldRender()) {
  19158. this._renderId++;
  19159. renderTarget.render(false, false);
  19160. needsRestoreFrameBuffer = true;
  19161. }
  19162. }
  19163. }
  19164. this._intermediateRendering = false;
  19165. this._renderId++;
  19166. }
  19167. if (needsRestoreFrameBuffer) {
  19168. engine.restoreDefaultFramebuffer(); // Restore back buffer
  19169. }
  19170. this._renderTargetsDuration.endMonitoring(false);
  19171. // Prepare Frame
  19172. this.postProcessManager._prepareFrame();
  19173. this._renderDuration.beginMonitoring();
  19174. // Backgrounds
  19175. var layerIndex;
  19176. var layer;
  19177. if (this.layers.length) {
  19178. engine.setDepthBuffer(false);
  19179. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19180. layer = this.layers[layerIndex];
  19181. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19182. layer.render();
  19183. }
  19184. }
  19185. engine.setDepthBuffer(true);
  19186. }
  19187. // Render
  19188. BABYLON.Tools.StartPerformanceCounter("Main render");
  19189. // Activate HighlightLayer stencil
  19190. if (renderhighlights) {
  19191. this._engine.setStencilBuffer(true);
  19192. }
  19193. this._renderingManager.render(null, null, true, true);
  19194. // Restore HighlightLayer stencil
  19195. if (renderhighlights) {
  19196. this._engine.setStencilBuffer(stencilState);
  19197. }
  19198. BABYLON.Tools.EndPerformanceCounter("Main render");
  19199. // Bounding boxes
  19200. if (this._boundingBoxRenderer) {
  19201. this._boundingBoxRenderer.render();
  19202. }
  19203. // Lens flares
  19204. if (this.lensFlaresEnabled) {
  19205. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19206. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  19207. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  19208. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  19209. lensFlareSystem.render();
  19210. }
  19211. }
  19212. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19213. }
  19214. // Foregrounds
  19215. if (this.layers.length) {
  19216. engine.setDepthBuffer(false);
  19217. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19218. layer = this.layers[layerIndex];
  19219. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19220. layer.render();
  19221. }
  19222. }
  19223. engine.setDepthBuffer(true);
  19224. }
  19225. // Highlight Layer
  19226. if (renderhighlights) {
  19227. engine.setDepthBuffer(false);
  19228. for (var i = 0; i < this.highlightLayers.length; i++) {
  19229. if (this.highlightLayers[i].shouldRender()) {
  19230. this.highlightLayers[i].render();
  19231. }
  19232. }
  19233. engine.setDepthBuffer(true);
  19234. }
  19235. this._renderDuration.endMonitoring(false);
  19236. // Finalize frame
  19237. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  19238. // Reset some special arrays
  19239. this._renderTargets.reset();
  19240. this._alternateRendering = false;
  19241. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  19242. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19243. };
  19244. Scene.prototype._processSubCameras = function (camera) {
  19245. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  19246. this._renderForCamera(camera);
  19247. return;
  19248. }
  19249. // Update camera
  19250. this.activeCamera.update();
  19251. // rig cameras
  19252. for (var index = 0; index < camera._rigCameras.length; index++) {
  19253. this._renderForCamera(camera._rigCameras[index]);
  19254. }
  19255. this.activeCamera = camera;
  19256. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  19257. };
  19258. Scene.prototype._checkIntersections = function () {
  19259. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  19260. var sourceMesh = this._meshesForIntersections.data[index];
  19261. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  19262. var action = sourceMesh.actionManager.actions[actionIndex];
  19263. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19264. var parameters = action.getTriggerParameter();
  19265. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  19266. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  19267. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  19268. if (areIntersecting && currentIntersectionInProgress === -1) {
  19269. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  19270. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  19271. sourceMesh._intersectionsInProgress.push(otherMesh);
  19272. }
  19273. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19274. sourceMesh._intersectionsInProgress.push(otherMesh);
  19275. }
  19276. }
  19277. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  19278. //They intersected, and now they don't.
  19279. //is this trigger an exit trigger? execute an event.
  19280. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19281. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  19282. }
  19283. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  19284. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19285. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  19286. }
  19287. }
  19288. }
  19289. }
  19290. }
  19291. };
  19292. Scene.prototype.render = function () {
  19293. if (this.isDisposed) {
  19294. return;
  19295. }
  19296. this._interFrameDuration.endMonitoring();
  19297. this._lastFrameDuration.beginMonitoring();
  19298. this._particlesDuration.fetchNewFrame();
  19299. this._spritesDuration.fetchNewFrame();
  19300. this._activeParticles.fetchNewFrame();
  19301. this._renderDuration.fetchNewFrame();
  19302. this._renderTargetsDuration.fetchNewFrame();
  19303. this._evaluateActiveMeshesDuration.fetchNewFrame();
  19304. this._totalVertices.fetchNewFrame();
  19305. this._activeIndices.fetchNewFrame();
  19306. this._activeBones.fetchNewFrame();
  19307. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  19308. this._meshesForIntersections.reset();
  19309. this.resetCachedMaterial();
  19310. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  19311. // Actions
  19312. if (this.actionManager) {
  19313. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  19314. }
  19315. //Simplification Queue
  19316. if (this.simplificationQueue && !this.simplificationQueue.running) {
  19317. this.simplificationQueue.executeNext();
  19318. }
  19319. if (this._engine.isDeterministicLockStep()) {
  19320. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  19321. var defaultTimeStep = (60.0 / 1000.0);
  19322. if (this._physicsEngine) {
  19323. defaultTimeStep = this._physicsEngine.getTimeStep();
  19324. }
  19325. var maxSubSteps = this._engine.getLockstepMaxSteps();
  19326. this._timeAccumulator += deltaTime;
  19327. // compute the amount of fixed steps we should have taken since the last step
  19328. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  19329. internalSteps = Math.min(internalSteps, maxSubSteps);
  19330. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  19331. this.onBeforeStepObservable.notifyObservers(this);
  19332. // Animations
  19333. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  19334. this._animate();
  19335. // Physics
  19336. if (this._physicsEngine) {
  19337. BABYLON.Tools.StartPerformanceCounter("Physics");
  19338. this._physicsEngine._step(defaultTimeStep);
  19339. BABYLON.Tools.EndPerformanceCounter("Physics");
  19340. }
  19341. this._timeAccumulator -= defaultTimeStep;
  19342. this.onAfterStepObservable.notifyObservers(this);
  19343. this._currentStepId++;
  19344. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  19345. this._evaluateActiveMeshes();
  19346. }
  19347. }
  19348. }
  19349. else {
  19350. // Animations
  19351. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  19352. this._animationRatio = deltaTime * (60.0 / 1000.0);
  19353. this._animate();
  19354. // Physics
  19355. if (this._physicsEngine) {
  19356. BABYLON.Tools.StartPerformanceCounter("Physics");
  19357. this._physicsEngine._step(deltaTime / 1000.0);
  19358. BABYLON.Tools.EndPerformanceCounter("Physics");
  19359. }
  19360. }
  19361. // Before render
  19362. this.onBeforeRenderObservable.notifyObservers(this);
  19363. // Customs render targets
  19364. this._renderTargetsDuration.beginMonitoring();
  19365. var engine = this.getEngine();
  19366. var currentActiveCamera = this.activeCamera;
  19367. if (this.renderTargetsEnabled) {
  19368. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19369. this._intermediateRendering = true;
  19370. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  19371. var renderTarget = this.customRenderTargets[customIndex];
  19372. if (renderTarget._shouldRender()) {
  19373. this._renderId++;
  19374. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  19375. if (!this.activeCamera)
  19376. throw new Error("Active camera not set");
  19377. // Viewport
  19378. engine.setViewport(this.activeCamera.viewport);
  19379. // Camera
  19380. this.updateTransformMatrix();
  19381. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  19382. }
  19383. }
  19384. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19385. this._intermediateRendering = false;
  19386. this._renderId++;
  19387. }
  19388. // Restore back buffer
  19389. if (this.customRenderTargets.length > 0) {
  19390. engine.restoreDefaultFramebuffer();
  19391. }
  19392. this._renderTargetsDuration.endMonitoring();
  19393. this.activeCamera = currentActiveCamera;
  19394. // Procedural textures
  19395. if (this.proceduralTexturesEnabled) {
  19396. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19397. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  19398. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  19399. if (proceduralTexture._shouldRender()) {
  19400. proceduralTexture.render();
  19401. }
  19402. }
  19403. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19404. }
  19405. // Clear
  19406. if (this.autoClearDepthAndStencil || this.autoClear) {
  19407. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  19408. }
  19409. // Shadows
  19410. if (this.shadowsEnabled) {
  19411. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  19412. var light = this.lights[lightIndex];
  19413. var shadowGenerator = light.getShadowGenerator();
  19414. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  19415. var shadowMap = shadowGenerator.getShadowMap();
  19416. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  19417. this._renderTargets.push(shadowMap);
  19418. }
  19419. }
  19420. }
  19421. }
  19422. // Depth renderer
  19423. if (this._depthRenderer) {
  19424. this._renderTargets.push(this._depthRenderer.getDepthMap());
  19425. }
  19426. // Geometry renderer
  19427. if (this._geometryBufferRenderer) {
  19428. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  19429. }
  19430. // RenderPipeline
  19431. if (this._postProcessRenderPipelineManager) {
  19432. this._postProcessRenderPipelineManager.update();
  19433. }
  19434. // Multi-cameras?
  19435. if (this.activeCameras.length > 0) {
  19436. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  19437. if (cameraIndex > 0) {
  19438. this._engine.clear(null, false, true, true);
  19439. }
  19440. this._processSubCameras(this.activeCameras[cameraIndex]);
  19441. }
  19442. }
  19443. else {
  19444. if (!this.activeCamera) {
  19445. throw new Error("No camera defined");
  19446. }
  19447. this._processSubCameras(this.activeCamera);
  19448. }
  19449. // Intersection checks
  19450. this._checkIntersections();
  19451. // Update the audio listener attached to the camera
  19452. if (BABYLON.AudioEngine) {
  19453. this._updateAudioParameters();
  19454. }
  19455. // After render
  19456. if (this.afterRender) {
  19457. this.afterRender();
  19458. }
  19459. this.onAfterRenderObservable.notifyObservers(this);
  19460. // Cleaning
  19461. for (var index = 0; index < this._toBeDisposed.length; index++) {
  19462. this._toBeDisposed.data[index].dispose();
  19463. this._toBeDisposed[index] = null;
  19464. }
  19465. this._toBeDisposed.reset();
  19466. if (this.dumpNextRenderTargets) {
  19467. this.dumpNextRenderTargets = false;
  19468. }
  19469. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  19470. this._interFrameDuration.beginMonitoring();
  19471. this._lastFrameDuration.endMonitoring();
  19472. this._totalMeshesCounter.addCount(this.meshes.length, true);
  19473. this._totalLightsCounter.addCount(this.lights.length, true);
  19474. this._totalMaterialsCounter.addCount(this.materials.length, true);
  19475. this._totalTexturesCounter.addCount(this.textures.length, true);
  19476. this._activeBones.addCount(0, true);
  19477. this._activeIndices.addCount(0, true);
  19478. this._activeParticles.addCount(0, true);
  19479. };
  19480. Scene.prototype._updateAudioParameters = function () {
  19481. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  19482. return;
  19483. }
  19484. var listeningCamera;
  19485. var audioEngine = BABYLON.Engine.audioEngine;
  19486. if (this.activeCameras.length > 0) {
  19487. listeningCamera = this.activeCameras[0];
  19488. }
  19489. else {
  19490. listeningCamera = this.activeCamera;
  19491. }
  19492. if (listeningCamera && audioEngine.canUseWebAudio) {
  19493. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  19494. // for VR cameras
  19495. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  19496. listeningCamera = listeningCamera.rigCameras[0];
  19497. }
  19498. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  19499. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  19500. cameraDirection.normalize();
  19501. // To avoid some errors on GearVR
  19502. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  19503. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  19504. }
  19505. var i;
  19506. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19507. var sound = this.mainSoundTrack.soundCollection[i];
  19508. if (sound.useCustomAttenuation) {
  19509. sound.updateDistanceFromListener();
  19510. }
  19511. }
  19512. for (i = 0; i < this.soundTracks.length; i++) {
  19513. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19514. sound = this.soundTracks[i].soundCollection[j];
  19515. if (sound.useCustomAttenuation) {
  19516. sound.updateDistanceFromListener();
  19517. }
  19518. }
  19519. }
  19520. }
  19521. };
  19522. Object.defineProperty(Scene.prototype, "audioEnabled", {
  19523. // Audio
  19524. get: function () {
  19525. return this._audioEnabled;
  19526. },
  19527. set: function (value) {
  19528. this._audioEnabled = value;
  19529. if (BABYLON.AudioEngine) {
  19530. if (this._audioEnabled) {
  19531. this._enableAudio();
  19532. }
  19533. else {
  19534. this._disableAudio();
  19535. }
  19536. }
  19537. },
  19538. enumerable: true,
  19539. configurable: true
  19540. });
  19541. Scene.prototype._disableAudio = function () {
  19542. var i;
  19543. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19544. this.mainSoundTrack.soundCollection[i].pause();
  19545. }
  19546. for (i = 0; i < this.soundTracks.length; i++) {
  19547. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19548. this.soundTracks[i].soundCollection[j].pause();
  19549. }
  19550. }
  19551. };
  19552. Scene.prototype._enableAudio = function () {
  19553. var i;
  19554. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19555. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  19556. this.mainSoundTrack.soundCollection[i].play();
  19557. }
  19558. }
  19559. for (i = 0; i < this.soundTracks.length; i++) {
  19560. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19561. if (this.soundTracks[i].soundCollection[j].isPaused) {
  19562. this.soundTracks[i].soundCollection[j].play();
  19563. }
  19564. }
  19565. }
  19566. };
  19567. Object.defineProperty(Scene.prototype, "headphone", {
  19568. get: function () {
  19569. return this._headphone;
  19570. },
  19571. set: function (value) {
  19572. this._headphone = value;
  19573. if (BABYLON.AudioEngine) {
  19574. if (this._headphone) {
  19575. this._switchAudioModeForHeadphones();
  19576. }
  19577. else {
  19578. this._switchAudioModeForNormalSpeakers();
  19579. }
  19580. }
  19581. },
  19582. enumerable: true,
  19583. configurable: true
  19584. });
  19585. Scene.prototype._switchAudioModeForHeadphones = function () {
  19586. this.mainSoundTrack.switchPanningModelToHRTF();
  19587. for (var i = 0; i < this.soundTracks.length; i++) {
  19588. this.soundTracks[i].switchPanningModelToHRTF();
  19589. }
  19590. };
  19591. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  19592. this.mainSoundTrack.switchPanningModelToEqualPower();
  19593. for (var i = 0; i < this.soundTracks.length; i++) {
  19594. this.soundTracks[i].switchPanningModelToEqualPower();
  19595. }
  19596. };
  19597. Scene.prototype.enableDepthRenderer = function () {
  19598. if (this._depthRenderer) {
  19599. return this._depthRenderer;
  19600. }
  19601. this._depthRenderer = new BABYLON.DepthRenderer(this);
  19602. return this._depthRenderer;
  19603. };
  19604. Scene.prototype.disableDepthRenderer = function () {
  19605. if (!this._depthRenderer) {
  19606. return;
  19607. }
  19608. this._depthRenderer.dispose();
  19609. this._depthRenderer = null;
  19610. };
  19611. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  19612. if (ratio === void 0) { ratio = 1; }
  19613. if (this._geometryBufferRenderer) {
  19614. return this._geometryBufferRenderer;
  19615. }
  19616. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  19617. if (!this._geometryBufferRenderer.isSupported) {
  19618. this._geometryBufferRenderer = null;
  19619. }
  19620. return this._geometryBufferRenderer;
  19621. };
  19622. Scene.prototype.disableGeometryBufferRenderer = function () {
  19623. if (!this._geometryBufferRenderer) {
  19624. return;
  19625. }
  19626. this._geometryBufferRenderer.dispose();
  19627. this._geometryBufferRenderer = null;
  19628. };
  19629. Scene.prototype.freezeMaterials = function () {
  19630. for (var i = 0; i < this.materials.length; i++) {
  19631. this.materials[i].freeze();
  19632. }
  19633. };
  19634. Scene.prototype.unfreezeMaterials = function () {
  19635. for (var i = 0; i < this.materials.length; i++) {
  19636. this.materials[i].unfreeze();
  19637. }
  19638. };
  19639. Scene.prototype.dispose = function () {
  19640. this.beforeRender = null;
  19641. this.afterRender = null;
  19642. this.skeletons = [];
  19643. this.morphTargetManagers = [];
  19644. this.importedMeshesFiles = new Array();
  19645. this.resetCachedMaterial();
  19646. if (this._depthRenderer) {
  19647. this._depthRenderer.dispose();
  19648. }
  19649. if (this._gamepadManager) {
  19650. this._gamepadManager.dispose();
  19651. this._gamepadManager = null;
  19652. }
  19653. // Smart arrays
  19654. if (this.activeCamera) {
  19655. this.activeCamera._activeMeshes.dispose();
  19656. this.activeCamera = null;
  19657. }
  19658. this._activeMeshes.dispose();
  19659. this._renderingManager.dispose();
  19660. this._processedMaterials.dispose();
  19661. this._activeParticleSystems.dispose();
  19662. this._activeSkeletons.dispose();
  19663. this._softwareSkinnedMeshes.dispose();
  19664. this._renderTargets.dispose();
  19665. if (this._boundingBoxRenderer) {
  19666. this._boundingBoxRenderer.dispose();
  19667. }
  19668. this._meshesForIntersections.dispose();
  19669. this._toBeDisposed.dispose();
  19670. // Debug layer
  19671. if (this._debugLayer) {
  19672. this._debugLayer.hide();
  19673. }
  19674. // Events
  19675. this.onDisposeObservable.notifyObservers(this);
  19676. this.onDisposeObservable.clear();
  19677. this.onBeforeRenderObservable.clear();
  19678. this.onAfterRenderObservable.clear();
  19679. this.detachControl();
  19680. // Release sounds & sounds tracks
  19681. if (BABYLON.AudioEngine) {
  19682. this.disposeSounds();
  19683. }
  19684. // VR Helper
  19685. if (this.VRHelper) {
  19686. this.VRHelper.dispose();
  19687. }
  19688. // Detach cameras
  19689. var canvas = this._engine.getRenderingCanvas();
  19690. var index;
  19691. for (index = 0; index < this.cameras.length; index++) {
  19692. this.cameras[index].detachControl(canvas);
  19693. }
  19694. // Release lights
  19695. while (this.lights.length) {
  19696. this.lights[0].dispose();
  19697. }
  19698. // Release meshes
  19699. while (this.meshes.length) {
  19700. this.meshes[0].dispose(true);
  19701. }
  19702. // Release cameras
  19703. while (this.cameras.length) {
  19704. this.cameras[0].dispose();
  19705. }
  19706. // Release materials
  19707. if (this.defaultMaterial) {
  19708. this.defaultMaterial.dispose();
  19709. }
  19710. while (this.multiMaterials.length) {
  19711. this.multiMaterials[0].dispose();
  19712. }
  19713. while (this.materials.length) {
  19714. this.materials[0].dispose();
  19715. }
  19716. // Release particles
  19717. while (this.particleSystems.length) {
  19718. this.particleSystems[0].dispose();
  19719. }
  19720. // Release sprites
  19721. while (this.spriteManagers.length) {
  19722. this.spriteManagers[0].dispose();
  19723. }
  19724. // Release postProcesses
  19725. while (this.postProcesses.length) {
  19726. this.postProcesses[0].dispose();
  19727. }
  19728. // Release layers
  19729. while (this.layers.length) {
  19730. this.layers[0].dispose();
  19731. }
  19732. while (this.highlightLayers.length) {
  19733. this.highlightLayers[0].dispose();
  19734. }
  19735. // Release textures
  19736. while (this.textures.length) {
  19737. this.textures[0].dispose();
  19738. }
  19739. // Release UBO
  19740. this._sceneUbo.dispose();
  19741. if (this._alternateSceneUbo) {
  19742. this._alternateSceneUbo.dispose();
  19743. }
  19744. // Post-processes
  19745. this.postProcessManager.dispose();
  19746. if (this._postProcessRenderPipelineManager) {
  19747. this._postProcessRenderPipelineManager.dispose();
  19748. }
  19749. // Physics
  19750. if (this._physicsEngine) {
  19751. this.disablePhysicsEngine();
  19752. }
  19753. // Remove from engine
  19754. index = this._engine.scenes.indexOf(this);
  19755. if (index > -1) {
  19756. this._engine.scenes.splice(index, 1);
  19757. }
  19758. this._engine.wipeCaches();
  19759. this._engine = null;
  19760. this.defaultMaterial = null;
  19761. this.multiMaterials = null;
  19762. this.materials = null;
  19763. };
  19764. Object.defineProperty(Scene.prototype, "isDisposed", {
  19765. get: function () {
  19766. return !this._engine;
  19767. },
  19768. enumerable: true,
  19769. configurable: true
  19770. });
  19771. // Release sounds & sounds tracks
  19772. Scene.prototype.disposeSounds = function () {
  19773. if (!this._mainSoundTrack) {
  19774. return;
  19775. }
  19776. this.mainSoundTrack.dispose();
  19777. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19778. this.soundTracks[scIndex].dispose();
  19779. }
  19780. };
  19781. // Octrees
  19782. Scene.prototype.getWorldExtends = function () {
  19783. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19784. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19785. for (var index = 0; index < this.meshes.length; index++) {
  19786. var mesh = this.meshes[index];
  19787. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  19788. continue;
  19789. }
  19790. mesh.computeWorldMatrix(true);
  19791. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19792. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19793. BABYLON.Tools.CheckExtends(minBox, min, max);
  19794. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19795. }
  19796. return {
  19797. min: min,
  19798. max: max
  19799. };
  19800. };
  19801. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19802. if (maxCapacity === void 0) { maxCapacity = 64; }
  19803. if (maxDepth === void 0) { maxDepth = 2; }
  19804. if (!this._selectionOctree) {
  19805. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19806. }
  19807. var worldExtends = this.getWorldExtends();
  19808. // Update octree
  19809. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19810. return this._selectionOctree;
  19811. };
  19812. // Picking
  19813. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19814. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19815. var engine = this._engine;
  19816. if (!camera) {
  19817. if (!this.activeCamera)
  19818. throw new Error("Active camera not set");
  19819. camera = this.activeCamera;
  19820. }
  19821. var cameraViewport = camera.viewport;
  19822. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19823. // Moving coordinates to local viewport world
  19824. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19825. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19826. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19827. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19828. };
  19829. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19830. if (!BABYLON.PickingInfo) {
  19831. return null;
  19832. }
  19833. var engine = this._engine;
  19834. if (!camera) {
  19835. if (!this.activeCamera)
  19836. throw new Error("Active camera not set");
  19837. camera = this.activeCamera;
  19838. }
  19839. var cameraViewport = camera.viewport;
  19840. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19841. var identity = BABYLON.Matrix.Identity();
  19842. // Moving coordinates to local viewport world
  19843. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19844. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19845. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19846. };
  19847. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19848. if (!BABYLON.PickingInfo) {
  19849. return null;
  19850. }
  19851. var pickingInfo = null;
  19852. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19853. var mesh = this.meshes[meshIndex];
  19854. if (predicate) {
  19855. if (!predicate(mesh)) {
  19856. continue;
  19857. }
  19858. }
  19859. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19860. continue;
  19861. }
  19862. var world = mesh.getWorldMatrix();
  19863. var ray = rayFunction(world);
  19864. var result = mesh.intersects(ray, fastCheck);
  19865. if (!result || !result.hit)
  19866. continue;
  19867. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19868. continue;
  19869. pickingInfo = result;
  19870. if (fastCheck) {
  19871. break;
  19872. }
  19873. }
  19874. return pickingInfo || new BABYLON.PickingInfo();
  19875. };
  19876. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19877. if (!BABYLON.PickingInfo) {
  19878. return null;
  19879. }
  19880. var pickingInfos = new Array();
  19881. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19882. var mesh = this.meshes[meshIndex];
  19883. if (predicate) {
  19884. if (!predicate(mesh)) {
  19885. continue;
  19886. }
  19887. }
  19888. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19889. continue;
  19890. }
  19891. var world = mesh.getWorldMatrix();
  19892. var ray = rayFunction(world);
  19893. var result = mesh.intersects(ray, false);
  19894. if (!result || !result.hit)
  19895. continue;
  19896. pickingInfos.push(result);
  19897. }
  19898. return pickingInfos;
  19899. };
  19900. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19901. if (!BABYLON.PickingInfo) {
  19902. return null;
  19903. }
  19904. var pickingInfo = null;
  19905. camera = camera || this.activeCamera;
  19906. if (this.spriteManagers.length > 0) {
  19907. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19908. var spriteManager = this.spriteManagers[spriteIndex];
  19909. if (!spriteManager.isPickable) {
  19910. continue;
  19911. }
  19912. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19913. if (!result || !result.hit)
  19914. continue;
  19915. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19916. continue;
  19917. pickingInfo = result;
  19918. if (fastCheck) {
  19919. break;
  19920. }
  19921. }
  19922. }
  19923. return pickingInfo || new BABYLON.PickingInfo();
  19924. };
  19925. /** Launch a ray to try to pick a mesh in the scene
  19926. * @param x position on screen
  19927. * @param y position on screen
  19928. * @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
  19929. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19930. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19931. */
  19932. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19933. var _this = this;
  19934. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19935. };
  19936. /** Launch a ray to try to pick a sprite in the scene
  19937. * @param x position on screen
  19938. * @param y position on screen
  19939. * @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
  19940. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19941. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19942. */
  19943. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19944. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19945. };
  19946. /** Use the given ray to pick a mesh in the scene
  19947. * @param ray The ray to use to pick meshes
  19948. * @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
  19949. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19950. */
  19951. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19952. var _this = this;
  19953. return this._internalPick(function (world) {
  19954. if (!_this._pickWithRayInverseMatrix) {
  19955. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19956. }
  19957. world.invertToRef(_this._pickWithRayInverseMatrix);
  19958. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19959. }, predicate, fastCheck);
  19960. };
  19961. /**
  19962. * Launch a ray to try to pick a mesh in the scene
  19963. * @param x X position on screen
  19964. * @param y Y position on screen
  19965. * @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
  19966. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19967. */
  19968. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19969. var _this = this;
  19970. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19971. };
  19972. /**
  19973. * Launch a ray to try to pick a mesh in the scene
  19974. * @param ray Ray to use
  19975. * @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
  19976. */
  19977. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19978. var _this = this;
  19979. return this._internalMultiPick(function (world) {
  19980. if (!_this._pickWithRayInverseMatrix) {
  19981. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19982. }
  19983. world.invertToRef(_this._pickWithRayInverseMatrix);
  19984. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19985. }, predicate);
  19986. };
  19987. Scene.prototype.setPointerOverMesh = function (mesh) {
  19988. if (this._pointerOverMesh === mesh) {
  19989. return;
  19990. }
  19991. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19992. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19993. }
  19994. this._pointerOverMesh = mesh;
  19995. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19996. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19997. }
  19998. };
  19999. Scene.prototype.getPointerOverMesh = function () {
  20000. return this._pointerOverMesh;
  20001. };
  20002. Scene.prototype.setPointerOverSprite = function (sprite) {
  20003. if (this._pointerOverSprite === sprite) {
  20004. return;
  20005. }
  20006. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20007. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20008. }
  20009. this._pointerOverSprite = sprite;
  20010. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20011. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20012. }
  20013. };
  20014. Scene.prototype.getPointerOverSprite = function () {
  20015. return this._pointerOverSprite;
  20016. };
  20017. // Physics
  20018. Scene.prototype.getPhysicsEngine = function () {
  20019. return this._physicsEngine;
  20020. };
  20021. /**
  20022. * Enables physics to the current scene
  20023. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  20024. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  20025. * @return {boolean} was the physics engine initialized
  20026. */
  20027. Scene.prototype.enablePhysics = function (gravity, plugin) {
  20028. if (this._physicsEngine) {
  20029. return true;
  20030. }
  20031. try {
  20032. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  20033. return true;
  20034. }
  20035. catch (e) {
  20036. BABYLON.Tools.Error(e.message);
  20037. return false;
  20038. }
  20039. };
  20040. Scene.prototype.disablePhysicsEngine = function () {
  20041. if (!this._physicsEngine) {
  20042. return;
  20043. }
  20044. this._physicsEngine.dispose();
  20045. this._physicsEngine = undefined;
  20046. };
  20047. Scene.prototype.isPhysicsEnabled = function () {
  20048. return this._physicsEngine !== undefined;
  20049. };
  20050. Scene.prototype.deleteCompoundImpostor = function (compound) {
  20051. var mesh = compound.parts[0].mesh;
  20052. mesh.physicsImpostor.dispose();
  20053. mesh.physicsImpostor = null;
  20054. };
  20055. // Misc.
  20056. Scene.prototype._rebuildGeometries = function () {
  20057. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  20058. var geometry = _a[_i];
  20059. geometry._rebuild();
  20060. }
  20061. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  20062. var mesh = _c[_b];
  20063. mesh._rebuild();
  20064. }
  20065. if (this.postProcessManager) {
  20066. this.postProcessManager._rebuild();
  20067. }
  20068. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  20069. var layer = _e[_d];
  20070. layer._rebuild();
  20071. }
  20072. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  20073. var highlightLayer = _g[_f];
  20074. highlightLayer._rebuild();
  20075. }
  20076. if (this._boundingBoxRenderer) {
  20077. this._boundingBoxRenderer._rebuild();
  20078. }
  20079. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  20080. var system = _j[_h];
  20081. system.rebuild();
  20082. }
  20083. if (this._postProcessRenderPipelineManager) {
  20084. this._postProcessRenderPipelineManager._rebuild();
  20085. }
  20086. };
  20087. Scene.prototype._rebuildTextures = function () {
  20088. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  20089. var texture = _a[_i];
  20090. texture._rebuild();
  20091. }
  20092. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20093. };
  20094. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  20095. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  20096. if (replace === void 0) { replace = false; }
  20097. if (attachCameraControls === void 0) { attachCameraControls = false; }
  20098. // Dispose existing camera or light in replace mode.
  20099. if (replace) {
  20100. if (this.activeCamera) {
  20101. this.activeCamera.dispose();
  20102. this.activeCamera = null;
  20103. }
  20104. if (this.lights) {
  20105. for (var i = 0; i < this.lights.length; i++) {
  20106. this.lights[i].dispose();
  20107. }
  20108. }
  20109. }
  20110. // Light
  20111. if (this.lights.length === 0) {
  20112. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  20113. }
  20114. // Camera
  20115. if (!this.activeCamera) {
  20116. var worldExtends = this.getWorldExtends();
  20117. var worldSize = worldExtends.max.subtract(worldExtends.min);
  20118. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  20119. var camera;
  20120. var radius = worldSize.length() * 1.5;
  20121. if (createArcRotateCamera) {
  20122. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  20123. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  20124. arcRotateCamera.wheelPrecision = 100 / radius;
  20125. camera = arcRotateCamera;
  20126. }
  20127. else {
  20128. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  20129. freeCamera.setTarget(worldCenter);
  20130. camera = freeCamera;
  20131. }
  20132. camera.minZ = radius * 0.01;
  20133. camera.maxZ = radius * 100;
  20134. camera.speed = radius * 0.2;
  20135. this.activeCamera = camera;
  20136. if (attachCameraControls) {
  20137. camera.attachControl(this.getEngine().getRenderingCanvas());
  20138. }
  20139. }
  20140. };
  20141. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  20142. if (pbr === void 0) { pbr = false; }
  20143. if (scale === void 0) { scale = 1000; }
  20144. if (blur === void 0) { blur = 0; }
  20145. if (environmentTexture) {
  20146. this.environmentTexture = environmentTexture;
  20147. }
  20148. if (!this.environmentTexture) {
  20149. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  20150. return null;
  20151. }
  20152. // Skybox
  20153. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  20154. if (pbr) {
  20155. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  20156. hdrSkyboxMaterial.backFaceCulling = false;
  20157. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20158. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20159. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  20160. hdrSkyboxMaterial.disableLighting = true;
  20161. hdrSkyboxMaterial.twoSidedLighting = true;
  20162. hdrSkybox.infiniteDistance = true;
  20163. hdrSkybox.material = hdrSkyboxMaterial;
  20164. }
  20165. else {
  20166. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  20167. skyboxMaterial.backFaceCulling = false;
  20168. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20169. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20170. skyboxMaterial.disableLighting = true;
  20171. hdrSkybox.infiniteDistance = true;
  20172. hdrSkybox.material = skyboxMaterial;
  20173. }
  20174. return hdrSkybox;
  20175. };
  20176. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  20177. if (webVROptions === void 0) { webVROptions = {}; }
  20178. this.VRHelper = new BABYLON.VRExperienceHelper(this, webVROptions);
  20179. };
  20180. // Tags
  20181. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  20182. if (tagsQuery === undefined) {
  20183. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  20184. return list;
  20185. }
  20186. var listByTags = [];
  20187. forEach = forEach || (function (item) { return; });
  20188. for (var i in list) {
  20189. var item = list[i];
  20190. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  20191. listByTags.push(item);
  20192. forEach(item);
  20193. }
  20194. }
  20195. return listByTags;
  20196. };
  20197. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  20198. return this._getByTags(this.meshes, tagsQuery, forEach);
  20199. };
  20200. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  20201. return this._getByTags(this.cameras, tagsQuery, forEach);
  20202. };
  20203. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  20204. return this._getByTags(this.lights, tagsQuery, forEach);
  20205. };
  20206. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  20207. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  20208. };
  20209. /**
  20210. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20211. * This allowed control for front to back rendering or reversly depending of the special needs.
  20212. *
  20213. * @param renderingGroupId The rendering group id corresponding to its index
  20214. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20215. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20216. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20217. */
  20218. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20219. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20220. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20221. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20222. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  20223. };
  20224. /**
  20225. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20226. *
  20227. * @param renderingGroupId The rendering group id corresponding to its index
  20228. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20229. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20230. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20231. */
  20232. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20233. if (depth === void 0) { depth = true; }
  20234. if (stencil === void 0) { stencil = true; }
  20235. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  20236. };
  20237. /**
  20238. * Will flag all materials as dirty to trigger new shader compilation
  20239. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  20240. */
  20241. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  20242. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  20243. var material = _a[_i];
  20244. if (predicate && !predicate(material)) {
  20245. continue;
  20246. }
  20247. material.markAsDirty(flag);
  20248. }
  20249. };
  20250. // Statics
  20251. Scene._FOGMODE_NONE = 0;
  20252. Scene._FOGMODE_EXP = 1;
  20253. Scene._FOGMODE_EXP2 = 2;
  20254. Scene._FOGMODE_LINEAR = 3;
  20255. Scene._uniqueIdCounter = 0;
  20256. Scene.MinDeltaTime = 1.0;
  20257. Scene.MaxDeltaTime = 1000.0;
  20258. /** The distance in pixel that you have to move to prevent some events */
  20259. Scene.DragMovementThreshold = 10; // in pixels
  20260. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  20261. Scene.LongPressDelay = 500; // in milliseconds
  20262. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  20263. Scene.DoubleClickDelay = 300; // in milliseconds
  20264. /** If you need to check double click without raising a single click at first click, enable this flag */
  20265. Scene.ExclusiveDoubleClickMode = false;
  20266. return Scene;
  20267. }());
  20268. BABYLON.Scene = Scene;
  20269. })(BABYLON || (BABYLON = {}));
  20270. //# sourceMappingURL=babylon.scene.js.map
  20271. var BABYLON;
  20272. (function (BABYLON) {
  20273. var Buffer = (function () {
  20274. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  20275. if (engine instanceof BABYLON.Mesh) {
  20276. this._engine = engine.getScene().getEngine();
  20277. }
  20278. else {
  20279. this._engine = engine;
  20280. }
  20281. this._updatable = updatable;
  20282. this._data = data;
  20283. this._strideSize = stride;
  20284. if (!postponeInternalCreation) {
  20285. this.create();
  20286. }
  20287. this._instanced = instanced;
  20288. this._instanceDivisor = instanced ? 1 : 0;
  20289. }
  20290. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  20291. // a lot of these parameters are ignored as they are overriden by the buffer
  20292. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  20293. };
  20294. // Properties
  20295. Buffer.prototype.isUpdatable = function () {
  20296. return this._updatable;
  20297. };
  20298. Buffer.prototype.getData = function () {
  20299. return this._data;
  20300. };
  20301. Buffer.prototype.getBuffer = function () {
  20302. return this._buffer;
  20303. };
  20304. Buffer.prototype.getStrideSize = function () {
  20305. return this._strideSize;
  20306. };
  20307. Buffer.prototype.getIsInstanced = function () {
  20308. return this._instanced;
  20309. };
  20310. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  20311. get: function () {
  20312. return this._instanceDivisor;
  20313. },
  20314. set: function (value) {
  20315. this._instanceDivisor = value;
  20316. if (value == 0) {
  20317. this._instanced = false;
  20318. }
  20319. else {
  20320. this._instanced = true;
  20321. }
  20322. },
  20323. enumerable: true,
  20324. configurable: true
  20325. });
  20326. // Methods
  20327. Buffer.prototype.create = function (data) {
  20328. if (!data && this._buffer) {
  20329. return; // nothing to do
  20330. }
  20331. data = data || this._data;
  20332. if (!this._buffer) {
  20333. if (this._updatable) {
  20334. this._buffer = this._engine.createDynamicVertexBuffer(data);
  20335. this._data = data;
  20336. }
  20337. else {
  20338. this._buffer = this._engine.createVertexBuffer(data);
  20339. }
  20340. }
  20341. else if (this._updatable) {
  20342. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  20343. this._data = data;
  20344. }
  20345. };
  20346. Buffer.prototype._rebuild = function () {
  20347. this._buffer = null;
  20348. this.create(this._data);
  20349. };
  20350. Buffer.prototype.update = function (data) {
  20351. this.create(data);
  20352. };
  20353. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  20354. if (!this._buffer) {
  20355. return;
  20356. }
  20357. if (this._updatable) {
  20358. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  20359. this._data = null;
  20360. }
  20361. };
  20362. Buffer.prototype.dispose = function () {
  20363. if (!this._buffer) {
  20364. return;
  20365. }
  20366. if (this._engine._releaseBuffer(this._buffer)) {
  20367. this._buffer = null;
  20368. }
  20369. };
  20370. return Buffer;
  20371. }());
  20372. BABYLON.Buffer = Buffer;
  20373. })(BABYLON || (BABYLON = {}));
  20374. //# sourceMappingURL=babylon.buffer.js.map
  20375. var BABYLON;
  20376. (function (BABYLON) {
  20377. var VertexBuffer = (function () {
  20378. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  20379. if (!stride) {
  20380. // Deduce stride from kind
  20381. switch (kind) {
  20382. case VertexBuffer.PositionKind:
  20383. stride = 3;
  20384. break;
  20385. case VertexBuffer.NormalKind:
  20386. stride = 3;
  20387. break;
  20388. case VertexBuffer.UVKind:
  20389. case VertexBuffer.UV2Kind:
  20390. case VertexBuffer.UV3Kind:
  20391. case VertexBuffer.UV4Kind:
  20392. case VertexBuffer.UV5Kind:
  20393. case VertexBuffer.UV6Kind:
  20394. stride = 2;
  20395. break;
  20396. case VertexBuffer.TangentKind:
  20397. case VertexBuffer.ColorKind:
  20398. stride = 4;
  20399. break;
  20400. case VertexBuffer.MatricesIndicesKind:
  20401. case VertexBuffer.MatricesIndicesExtraKind:
  20402. stride = 4;
  20403. break;
  20404. case VertexBuffer.MatricesWeightsKind:
  20405. case VertexBuffer.MatricesWeightsExtraKind:
  20406. stride = 4;
  20407. break;
  20408. }
  20409. }
  20410. if (data instanceof BABYLON.Buffer) {
  20411. if (!stride) {
  20412. stride = data.getStrideSize();
  20413. }
  20414. this._buffer = data;
  20415. this._ownsBuffer = false;
  20416. }
  20417. else {
  20418. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  20419. this._ownsBuffer = true;
  20420. }
  20421. this._stride = stride;
  20422. this._offset = offset ? offset : 0;
  20423. this._size = size ? size : stride;
  20424. this._kind = kind;
  20425. }
  20426. VertexBuffer.prototype._rebuild = function () {
  20427. if (!this._buffer) {
  20428. return;
  20429. }
  20430. this._buffer._rebuild();
  20431. };
  20432. /**
  20433. * Returns the kind of the VertexBuffer (string).
  20434. */
  20435. VertexBuffer.prototype.getKind = function () {
  20436. return this._kind;
  20437. };
  20438. // Properties
  20439. /**
  20440. * Boolean : is the VertexBuffer updatable ?
  20441. */
  20442. VertexBuffer.prototype.isUpdatable = function () {
  20443. return this._buffer.isUpdatable();
  20444. };
  20445. /**
  20446. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  20447. */
  20448. VertexBuffer.prototype.getData = function () {
  20449. return this._buffer.getData();
  20450. };
  20451. /**
  20452. * Returns the WebGLBuffer associated to the VertexBuffer.
  20453. */
  20454. VertexBuffer.prototype.getBuffer = function () {
  20455. return this._buffer.getBuffer();
  20456. };
  20457. /**
  20458. * Returns the stride of the VertexBuffer (integer).
  20459. */
  20460. VertexBuffer.prototype.getStrideSize = function () {
  20461. return this._stride;
  20462. };
  20463. /**
  20464. * Returns the offset (integer).
  20465. */
  20466. VertexBuffer.prototype.getOffset = function () {
  20467. return this._offset;
  20468. };
  20469. /**
  20470. * Returns the VertexBuffer total size (integer).
  20471. */
  20472. VertexBuffer.prototype.getSize = function () {
  20473. return this._size;
  20474. };
  20475. /**
  20476. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  20477. */
  20478. VertexBuffer.prototype.getIsInstanced = function () {
  20479. return this._buffer.getIsInstanced();
  20480. };
  20481. /**
  20482. * Returns the instancing divisor, zero for non-instanced (integer).
  20483. */
  20484. VertexBuffer.prototype.getInstanceDivisor = function () {
  20485. return this._buffer.instanceDivisor;
  20486. };
  20487. // Methods
  20488. /**
  20489. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  20490. * Returns the created WebGLBuffer.
  20491. */
  20492. VertexBuffer.prototype.create = function (data) {
  20493. return this._buffer.create(data);
  20494. };
  20495. /**
  20496. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  20497. * Returns the updated WebGLBuffer.
  20498. */
  20499. VertexBuffer.prototype.update = function (data) {
  20500. return this._buffer.update(data);
  20501. };
  20502. /**
  20503. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  20504. * Returns the directly updated WebGLBuffer.
  20505. */
  20506. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  20507. return this._buffer.updateDirectly(data, offset);
  20508. };
  20509. /**
  20510. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  20511. */
  20512. VertexBuffer.prototype.dispose = function () {
  20513. if (this._ownsBuffer) {
  20514. this._buffer.dispose();
  20515. }
  20516. };
  20517. Object.defineProperty(VertexBuffer, "PositionKind", {
  20518. get: function () {
  20519. return VertexBuffer._PositionKind;
  20520. },
  20521. enumerable: true,
  20522. configurable: true
  20523. });
  20524. Object.defineProperty(VertexBuffer, "NormalKind", {
  20525. get: function () {
  20526. return VertexBuffer._NormalKind;
  20527. },
  20528. enumerable: true,
  20529. configurable: true
  20530. });
  20531. Object.defineProperty(VertexBuffer, "TangentKind", {
  20532. get: function () {
  20533. return VertexBuffer._TangentKind;
  20534. },
  20535. enumerable: true,
  20536. configurable: true
  20537. });
  20538. Object.defineProperty(VertexBuffer, "UVKind", {
  20539. get: function () {
  20540. return VertexBuffer._UVKind;
  20541. },
  20542. enumerable: true,
  20543. configurable: true
  20544. });
  20545. Object.defineProperty(VertexBuffer, "UV2Kind", {
  20546. get: function () {
  20547. return VertexBuffer._UV2Kind;
  20548. },
  20549. enumerable: true,
  20550. configurable: true
  20551. });
  20552. Object.defineProperty(VertexBuffer, "UV3Kind", {
  20553. get: function () {
  20554. return VertexBuffer._UV3Kind;
  20555. },
  20556. enumerable: true,
  20557. configurable: true
  20558. });
  20559. Object.defineProperty(VertexBuffer, "UV4Kind", {
  20560. get: function () {
  20561. return VertexBuffer._UV4Kind;
  20562. },
  20563. enumerable: true,
  20564. configurable: true
  20565. });
  20566. Object.defineProperty(VertexBuffer, "UV5Kind", {
  20567. get: function () {
  20568. return VertexBuffer._UV5Kind;
  20569. },
  20570. enumerable: true,
  20571. configurable: true
  20572. });
  20573. Object.defineProperty(VertexBuffer, "UV6Kind", {
  20574. get: function () {
  20575. return VertexBuffer._UV6Kind;
  20576. },
  20577. enumerable: true,
  20578. configurable: true
  20579. });
  20580. Object.defineProperty(VertexBuffer, "ColorKind", {
  20581. get: function () {
  20582. return VertexBuffer._ColorKind;
  20583. },
  20584. enumerable: true,
  20585. configurable: true
  20586. });
  20587. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  20588. get: function () {
  20589. return VertexBuffer._MatricesIndicesKind;
  20590. },
  20591. enumerable: true,
  20592. configurable: true
  20593. });
  20594. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  20595. get: function () {
  20596. return VertexBuffer._MatricesWeightsKind;
  20597. },
  20598. enumerable: true,
  20599. configurable: true
  20600. });
  20601. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  20602. get: function () {
  20603. return VertexBuffer._MatricesIndicesExtraKind;
  20604. },
  20605. enumerable: true,
  20606. configurable: true
  20607. });
  20608. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  20609. get: function () {
  20610. return VertexBuffer._MatricesWeightsExtraKind;
  20611. },
  20612. enumerable: true,
  20613. configurable: true
  20614. });
  20615. // Enums
  20616. VertexBuffer._PositionKind = "position";
  20617. VertexBuffer._NormalKind = "normal";
  20618. VertexBuffer._TangentKind = "tangent";
  20619. VertexBuffer._UVKind = "uv";
  20620. VertexBuffer._UV2Kind = "uv2";
  20621. VertexBuffer._UV3Kind = "uv3";
  20622. VertexBuffer._UV4Kind = "uv4";
  20623. VertexBuffer._UV5Kind = "uv5";
  20624. VertexBuffer._UV6Kind = "uv6";
  20625. VertexBuffer._ColorKind = "color";
  20626. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  20627. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  20628. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  20629. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  20630. return VertexBuffer;
  20631. }());
  20632. BABYLON.VertexBuffer = VertexBuffer;
  20633. })(BABYLON || (BABYLON = {}));
  20634. //# sourceMappingURL=babylon.vertexBuffer.js.map
  20635. var BABYLON;
  20636. (function (BABYLON) {
  20637. var InternalTexture = (function () {
  20638. function InternalTexture(engine, dataSource) {
  20639. this.onLoadedObservable = new BABYLON.Observable();
  20640. // Private
  20641. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  20642. this._references = 1;
  20643. this._engine = engine;
  20644. this._dataSource = dataSource;
  20645. this._webGLTexture = engine._createTexture();
  20646. }
  20647. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  20648. get: function () {
  20649. return this._dataSource;
  20650. },
  20651. enumerable: true,
  20652. configurable: true
  20653. });
  20654. InternalTexture.prototype.incrementReferences = function () {
  20655. this._references++;
  20656. };
  20657. InternalTexture.prototype.updateSize = function (width, height) {
  20658. this.width = width;
  20659. this.height = height;
  20660. this._size = width * height;
  20661. this.baseWidth = width;
  20662. this.baseHeight = height;
  20663. };
  20664. InternalTexture.prototype._rebuild = function () {
  20665. var _this = this;
  20666. var proxy;
  20667. this.isReady = false;
  20668. this._cachedCoordinatesMode = null;
  20669. this._cachedWrapU = null;
  20670. this._cachedWrapV = null;
  20671. this._cachedAnisotropicFilteringLevel = null;
  20672. switch (this._dataSource) {
  20673. case InternalTexture.DATASOURCE_TEMP:
  20674. return;
  20675. case InternalTexture.DATASOURCE_URL:
  20676. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  20677. _this.isReady = true;
  20678. }, null, this._buffer, null, this.format);
  20679. proxy._swapAndDie(this);
  20680. return;
  20681. case InternalTexture.DATASOURCE_RAW:
  20682. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20683. proxy._swapAndDie(this);
  20684. this.isReady = true;
  20685. return;
  20686. case InternalTexture.DATASOURCE_DYNAMIC:
  20687. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  20688. proxy._swapAndDie(this);
  20689. // The engine will make sure to update content so no need to flag it as isReady = true
  20690. return;
  20691. case InternalTexture.DATASOURCE_RENDERTARGET:
  20692. var options = new BABYLON.RenderTargetCreationOptions();
  20693. options.generateDepthBuffer = this._generateDepthBuffer;
  20694. options.generateMipMaps = this.generateMipMaps;
  20695. options.generateStencilBuffer = this._generateStencilBuffer;
  20696. options.samplingMode = this.samplingMode;
  20697. options.type = this.type;
  20698. if (this.isCube) {
  20699. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  20700. }
  20701. else {
  20702. var size = {
  20703. width: this.width,
  20704. height: this.height
  20705. };
  20706. proxy = this._engine.createRenderTargetTexture(size, options);
  20707. }
  20708. proxy._swapAndDie(this);
  20709. this.isReady = true;
  20710. return;
  20711. case InternalTexture.DATASOURCE_CUBE:
  20712. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  20713. _this.isReady = true;
  20714. }, null, this.format, this._extension);
  20715. proxy._swapAndDie(this);
  20716. return;
  20717. case InternalTexture.DATASOURCE_CUBERAW:
  20718. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20719. proxy._swapAndDie(this);
  20720. this.isReady = true;
  20721. return;
  20722. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  20723. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  20724. proxy._swapAndDie(_this);
  20725. _this.isReady = true;
  20726. }, null, this.format, this._extension);
  20727. return;
  20728. }
  20729. };
  20730. InternalTexture.prototype._swapAndDie = function (target) {
  20731. target._webGLTexture = this._webGLTexture;
  20732. if (this._framebuffer) {
  20733. target._framebuffer = this._framebuffer;
  20734. }
  20735. if (this._depthStencilBuffer) {
  20736. target._depthStencilBuffer = this._depthStencilBuffer;
  20737. }
  20738. if (this._lodTextureHigh) {
  20739. if (target._lodTextureHigh) {
  20740. target._lodTextureHigh.dispose();
  20741. }
  20742. target._lodTextureHigh = this._lodTextureHigh;
  20743. }
  20744. if (this._lodTextureMid) {
  20745. if (target._lodTextureMid) {
  20746. target._lodTextureMid.dispose();
  20747. }
  20748. target._lodTextureMid = this._lodTextureMid;
  20749. }
  20750. if (this._lodTextureLow) {
  20751. if (target._lodTextureLow) {
  20752. target._lodTextureLow.dispose();
  20753. }
  20754. target._lodTextureLow = this._lodTextureLow;
  20755. }
  20756. var cache = this._engine.getLoadedTexturesCache();
  20757. var index = cache.indexOf(this);
  20758. if (index !== -1) {
  20759. cache.splice(index, 1);
  20760. }
  20761. };
  20762. InternalTexture.prototype.dispose = function () {
  20763. if (!this._webGLTexture) {
  20764. return;
  20765. }
  20766. this._references--;
  20767. if (this._references === 0) {
  20768. this._engine._releaseTexture(this);
  20769. this._webGLTexture = null;
  20770. }
  20771. };
  20772. InternalTexture.DATASOURCE_UNKNOWN = 0;
  20773. InternalTexture.DATASOURCE_URL = 1;
  20774. InternalTexture.DATASOURCE_TEMP = 2;
  20775. InternalTexture.DATASOURCE_RAW = 3;
  20776. InternalTexture.DATASOURCE_DYNAMIC = 4;
  20777. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  20778. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  20779. InternalTexture.DATASOURCE_CUBE = 7;
  20780. InternalTexture.DATASOURCE_CUBERAW = 8;
  20781. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  20782. return InternalTexture;
  20783. }());
  20784. BABYLON.InternalTexture = InternalTexture;
  20785. })(BABYLON || (BABYLON = {}));
  20786. //# sourceMappingURL=babylon.internalTexture.js.map
  20787. var BABYLON;
  20788. (function (BABYLON) {
  20789. var BaseTexture = (function () {
  20790. function BaseTexture(scene) {
  20791. this._hasAlpha = false;
  20792. this.getAlphaFromRGB = false;
  20793. this.level = 1;
  20794. this.coordinatesIndex = 0;
  20795. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20796. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20797. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20798. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  20799. this.isCube = false;
  20800. this.gammaSpace = true;
  20801. this.invertZ = false;
  20802. this.lodLevelInAlpha = false;
  20803. this.lodGenerationOffset = 0.0;
  20804. this.lodGenerationScale = 0.8;
  20805. this.isRenderTarget = false;
  20806. this.animations = new Array();
  20807. /**
  20808. * An event triggered when the texture is disposed.
  20809. * @type {BABYLON.Observable}
  20810. */
  20811. this.onDisposeObservable = new BABYLON.Observable();
  20812. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20813. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  20814. this._scene.textures.push(this);
  20815. this._uid = null;
  20816. }
  20817. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  20818. get: function () {
  20819. return this._hasAlpha;
  20820. },
  20821. set: function (value) {
  20822. if (this._hasAlpha === value) {
  20823. return;
  20824. }
  20825. this._hasAlpha = value;
  20826. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20827. },
  20828. enumerable: true,
  20829. configurable: true
  20830. });
  20831. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  20832. get: function () {
  20833. return this._coordinatesMode;
  20834. },
  20835. set: function (value) {
  20836. if (this._coordinatesMode === value) {
  20837. return;
  20838. }
  20839. this._coordinatesMode = value;
  20840. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20841. },
  20842. enumerable: true,
  20843. configurable: true
  20844. });
  20845. Object.defineProperty(BaseTexture.prototype, "uid", {
  20846. get: function () {
  20847. if (!this._uid) {
  20848. this._uid = BABYLON.Tools.RandomId();
  20849. }
  20850. return this._uid;
  20851. },
  20852. enumerable: true,
  20853. configurable: true
  20854. });
  20855. BaseTexture.prototype.toString = function () {
  20856. return this.name;
  20857. };
  20858. BaseTexture.prototype.getClassName = function () {
  20859. return "BaseTexture";
  20860. };
  20861. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20862. set: function (callback) {
  20863. if (this._onDisposeObserver) {
  20864. this.onDisposeObservable.remove(this._onDisposeObserver);
  20865. }
  20866. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20867. },
  20868. enumerable: true,
  20869. configurable: true
  20870. });
  20871. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  20872. get: function () {
  20873. return true;
  20874. },
  20875. enumerable: true,
  20876. configurable: true
  20877. });
  20878. BaseTexture.prototype.getScene = function () {
  20879. return this._scene;
  20880. };
  20881. BaseTexture.prototype.getTextureMatrix = function () {
  20882. return null;
  20883. };
  20884. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20885. return null;
  20886. };
  20887. BaseTexture.prototype.getInternalTexture = function () {
  20888. return this._texture;
  20889. };
  20890. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  20891. return !this.isBlocking || this.isReady();
  20892. };
  20893. BaseTexture.prototype.isReady = function () {
  20894. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20895. this.delayLoad();
  20896. return false;
  20897. }
  20898. if (this._texture) {
  20899. return this._texture.isReady;
  20900. }
  20901. return false;
  20902. };
  20903. BaseTexture.prototype.getSize = function () {
  20904. if (this._texture.width) {
  20905. return new BABYLON.Size(this._texture.width, this._texture.height);
  20906. }
  20907. if (this._texture._size) {
  20908. return new BABYLON.Size(this._texture._size, this._texture._size);
  20909. }
  20910. return BABYLON.Size.Zero();
  20911. };
  20912. BaseTexture.prototype.getBaseSize = function () {
  20913. if (!this.isReady() || !this._texture)
  20914. return BABYLON.Size.Zero();
  20915. if (this._texture._size) {
  20916. return new BABYLON.Size(this._texture._size, this._texture._size);
  20917. }
  20918. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  20919. };
  20920. BaseTexture.prototype.scale = function (ratio) {
  20921. };
  20922. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20923. get: function () {
  20924. return false;
  20925. },
  20926. enumerable: true,
  20927. configurable: true
  20928. });
  20929. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20930. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20931. for (var index = 0; index < texturesCache.length; index++) {
  20932. var texturesCacheEntry = texturesCache[index];
  20933. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  20934. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20935. texturesCacheEntry.incrementReferences();
  20936. return texturesCacheEntry;
  20937. }
  20938. }
  20939. }
  20940. return null;
  20941. };
  20942. BaseTexture.prototype._rebuild = function () {
  20943. };
  20944. BaseTexture.prototype.delayLoad = function () {
  20945. };
  20946. BaseTexture.prototype.clone = function () {
  20947. return null;
  20948. };
  20949. Object.defineProperty(BaseTexture.prototype, "textureType", {
  20950. get: function () {
  20951. if (!this._texture) {
  20952. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20953. }
  20954. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20955. },
  20956. enumerable: true,
  20957. configurable: true
  20958. });
  20959. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  20960. get: function () {
  20961. if (!this._texture) {
  20962. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20963. }
  20964. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20965. },
  20966. enumerable: true,
  20967. configurable: true
  20968. });
  20969. BaseTexture.prototype.readPixels = function (faceIndex) {
  20970. if (faceIndex === void 0) { faceIndex = 0; }
  20971. if (!this._texture) {
  20972. return null;
  20973. }
  20974. var size = this.getSize();
  20975. var engine = this.getScene().getEngine();
  20976. if (this._texture.isCube) {
  20977. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  20978. }
  20979. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  20980. };
  20981. BaseTexture.prototype.releaseInternalTexture = function () {
  20982. if (this._texture) {
  20983. this._texture.dispose();
  20984. this._texture = null;
  20985. }
  20986. };
  20987. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  20988. get: function () {
  20989. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  20990. return null;
  20991. }
  20992. if (!this._texture._sphericalPolynomial) {
  20993. this._texture._sphericalPolynomial =
  20994. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  20995. }
  20996. return this._texture._sphericalPolynomial;
  20997. },
  20998. set: function (value) {
  20999. if (this._texture) {
  21000. this._texture._sphericalPolynomial = value;
  21001. }
  21002. },
  21003. enumerable: true,
  21004. configurable: true
  21005. });
  21006. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  21007. get: function () {
  21008. if (this._texture) {
  21009. return this._texture._lodTextureHigh;
  21010. }
  21011. return null;
  21012. },
  21013. enumerable: true,
  21014. configurable: true
  21015. });
  21016. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  21017. get: function () {
  21018. if (this._texture) {
  21019. return this._texture._lodTextureMid;
  21020. }
  21021. return null;
  21022. },
  21023. enumerable: true,
  21024. configurable: true
  21025. });
  21026. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  21027. get: function () {
  21028. if (this._texture) {
  21029. return this._texture._lodTextureLow;
  21030. }
  21031. return null;
  21032. },
  21033. enumerable: true,
  21034. configurable: true
  21035. });
  21036. BaseTexture.prototype.dispose = function () {
  21037. // Animations
  21038. this.getScene().stopAnimation(this);
  21039. // Remove from scene
  21040. this._scene._removePendingData(this);
  21041. var index = this._scene.textures.indexOf(this);
  21042. if (index >= 0) {
  21043. this._scene.textures.splice(index, 1);
  21044. }
  21045. if (this._texture === undefined) {
  21046. return;
  21047. }
  21048. // Release
  21049. this.releaseInternalTexture();
  21050. // Callback
  21051. this.onDisposeObservable.notifyObservers(this);
  21052. this.onDisposeObservable.clear();
  21053. };
  21054. BaseTexture.prototype.serialize = function () {
  21055. if (!this.name) {
  21056. return null;
  21057. }
  21058. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21059. // Animations
  21060. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21061. return serializationObject;
  21062. };
  21063. BaseTexture.WhenAllReady = function (textures, callback) {
  21064. var numRemaining = textures.length;
  21065. if (numRemaining === 0) {
  21066. callback();
  21067. return;
  21068. }
  21069. var _loop_1 = function () {
  21070. texture = textures[i];
  21071. if (texture.isReady()) {
  21072. if (--numRemaining === 0) {
  21073. callback();
  21074. }
  21075. }
  21076. else {
  21077. onLoadObservable = texture.onLoadObservable;
  21078. var onLoadCallback_1 = function () {
  21079. onLoadObservable.removeCallback(onLoadCallback_1);
  21080. if (--numRemaining === 0) {
  21081. callback();
  21082. }
  21083. };
  21084. onLoadObservable.add(onLoadCallback_1);
  21085. }
  21086. };
  21087. var texture, onLoadObservable;
  21088. for (var i = 0; i < textures.length; i++) {
  21089. _loop_1();
  21090. }
  21091. };
  21092. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  21093. __decorate([
  21094. BABYLON.serialize()
  21095. ], BaseTexture.prototype, "name", void 0);
  21096. __decorate([
  21097. BABYLON.serialize("hasAlpha")
  21098. ], BaseTexture.prototype, "_hasAlpha", void 0);
  21099. __decorate([
  21100. BABYLON.serialize()
  21101. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  21102. __decorate([
  21103. BABYLON.serialize()
  21104. ], BaseTexture.prototype, "level", void 0);
  21105. __decorate([
  21106. BABYLON.serialize()
  21107. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  21108. __decorate([
  21109. BABYLON.serialize("coordinatesMode")
  21110. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  21111. __decorate([
  21112. BABYLON.serialize()
  21113. ], BaseTexture.prototype, "wrapU", void 0);
  21114. __decorate([
  21115. BABYLON.serialize()
  21116. ], BaseTexture.prototype, "wrapV", void 0);
  21117. __decorate([
  21118. BABYLON.serialize()
  21119. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  21120. __decorate([
  21121. BABYLON.serialize()
  21122. ], BaseTexture.prototype, "isCube", void 0);
  21123. __decorate([
  21124. BABYLON.serialize()
  21125. ], BaseTexture.prototype, "gammaSpace", void 0);
  21126. __decorate([
  21127. BABYLON.serialize()
  21128. ], BaseTexture.prototype, "invertZ", void 0);
  21129. __decorate([
  21130. BABYLON.serialize()
  21131. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  21132. __decorate([
  21133. BABYLON.serialize()
  21134. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  21135. __decorate([
  21136. BABYLON.serialize()
  21137. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  21138. __decorate([
  21139. BABYLON.serialize()
  21140. ], BaseTexture.prototype, "isRenderTarget", void 0);
  21141. return BaseTexture;
  21142. }());
  21143. BABYLON.BaseTexture = BaseTexture;
  21144. })(BABYLON || (BABYLON = {}));
  21145. //# sourceMappingURL=babylon.baseTexture.js.map
  21146. var BABYLON;
  21147. (function (BABYLON) {
  21148. var Texture = (function (_super) {
  21149. __extends(Texture, _super);
  21150. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  21151. if (noMipmap === void 0) { noMipmap = false; }
  21152. if (invertY === void 0) { invertY = true; }
  21153. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21154. if (onLoad === void 0) { onLoad = null; }
  21155. if (onError === void 0) { onError = null; }
  21156. if (buffer === void 0) { buffer = null; }
  21157. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21158. var _this = _super.call(this, scene) || this;
  21159. _this.uOffset = 0;
  21160. _this.vOffset = 0;
  21161. _this.uScale = 1.0;
  21162. _this.vScale = 1.0;
  21163. _this.uAng = 0;
  21164. _this.vAng = 0;
  21165. _this.wAng = 0;
  21166. _this._isBlocking = true;
  21167. _this.name = url;
  21168. _this.url = url;
  21169. _this._noMipmap = noMipmap;
  21170. _this._invertY = invertY;
  21171. _this._samplingMode = samplingMode;
  21172. _this._buffer = buffer;
  21173. _this._deleteBuffer = deleteBuffer;
  21174. _this._format = format;
  21175. scene = _this.getScene();
  21176. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  21177. var load = function () {
  21178. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  21179. _this.onLoadObservable.notifyObservers(_this);
  21180. }
  21181. if (onLoad) {
  21182. onLoad();
  21183. }
  21184. if (!_this.isBlocking) {
  21185. scene.resetCachedMaterial();
  21186. }
  21187. };
  21188. if (!_this.url) {
  21189. _this._delayedOnLoad = load;
  21190. _this._delayedOnError = onError;
  21191. return _this;
  21192. }
  21193. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  21194. if (!_this._texture) {
  21195. if (!scene.useDelayedTextureLoading) {
  21196. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  21197. if (deleteBuffer) {
  21198. delete _this._buffer;
  21199. }
  21200. }
  21201. else {
  21202. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21203. _this._delayedOnLoad = load;
  21204. _this._delayedOnError = onError;
  21205. }
  21206. }
  21207. else {
  21208. if (_this._texture.isReady) {
  21209. BABYLON.Tools.SetImmediate(function () { return load(); });
  21210. }
  21211. else {
  21212. _this._texture.onLoadedObservable.add(load);
  21213. }
  21214. }
  21215. return _this;
  21216. }
  21217. Object.defineProperty(Texture.prototype, "noMipmap", {
  21218. get: function () {
  21219. return this._noMipmap;
  21220. },
  21221. enumerable: true,
  21222. configurable: true
  21223. });
  21224. Object.defineProperty(Texture.prototype, "isBlocking", {
  21225. get: function () {
  21226. return this._isBlocking;
  21227. },
  21228. set: function (value) {
  21229. this._isBlocking = value;
  21230. },
  21231. enumerable: true,
  21232. configurable: true
  21233. });
  21234. Object.defineProperty(Texture.prototype, "samplingMode", {
  21235. get: function () {
  21236. return this._samplingMode;
  21237. },
  21238. enumerable: true,
  21239. configurable: true
  21240. });
  21241. Texture.prototype.updateURL = function (url) {
  21242. this.url = url;
  21243. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21244. this.delayLoad();
  21245. };
  21246. Texture.prototype.delayLoad = function () {
  21247. var _this = this;
  21248. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21249. return;
  21250. }
  21251. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21252. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  21253. if (!this._texture) {
  21254. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  21255. if (this._deleteBuffer) {
  21256. delete this._buffer;
  21257. }
  21258. }
  21259. else {
  21260. if (this._texture.isReady) {
  21261. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  21262. }
  21263. else {
  21264. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  21265. }
  21266. }
  21267. };
  21268. Texture.prototype.updateSamplingMode = function (samplingMode) {
  21269. if (!this._texture) {
  21270. return;
  21271. }
  21272. this._samplingMode = samplingMode;
  21273. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  21274. };
  21275. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  21276. x *= this.uScale;
  21277. y *= this.vScale;
  21278. x -= 0.5 * this.uScale;
  21279. y -= 0.5 * this.vScale;
  21280. z -= 0.5;
  21281. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  21282. t.x += 0.5 * this.uScale + this.uOffset;
  21283. t.y += 0.5 * this.vScale + this.vOffset;
  21284. t.z += 0.5;
  21285. };
  21286. Texture.prototype.getTextureMatrix = function () {
  21287. var _this = this;
  21288. if (this.uOffset === this._cachedUOffset &&
  21289. this.vOffset === this._cachedVOffset &&
  21290. this.uScale === this._cachedUScale &&
  21291. this.vScale === this._cachedVScale &&
  21292. this.uAng === this._cachedUAng &&
  21293. this.vAng === this._cachedVAng &&
  21294. this.wAng === this._cachedWAng) {
  21295. return this._cachedTextureMatrix;
  21296. }
  21297. this._cachedUOffset = this.uOffset;
  21298. this._cachedVOffset = this.vOffset;
  21299. this._cachedUScale = this.uScale;
  21300. this._cachedVScale = this.vScale;
  21301. this._cachedUAng = this.uAng;
  21302. this._cachedVAng = this.vAng;
  21303. this._cachedWAng = this.wAng;
  21304. if (!this._cachedTextureMatrix) {
  21305. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21306. this._rowGenerationMatrix = new BABYLON.Matrix();
  21307. this._t0 = BABYLON.Vector3.Zero();
  21308. this._t1 = BABYLON.Vector3.Zero();
  21309. this._t2 = BABYLON.Vector3.Zero();
  21310. }
  21311. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  21312. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  21313. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  21314. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  21315. this._t1.subtractInPlace(this._t0);
  21316. this._t2.subtractInPlace(this._t0);
  21317. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21318. this._cachedTextureMatrix.m[0] = this._t1.x;
  21319. this._cachedTextureMatrix.m[1] = this._t1.y;
  21320. this._cachedTextureMatrix.m[2] = this._t1.z;
  21321. this._cachedTextureMatrix.m[4] = this._t2.x;
  21322. this._cachedTextureMatrix.m[5] = this._t2.y;
  21323. this._cachedTextureMatrix.m[6] = this._t2.z;
  21324. this._cachedTextureMatrix.m[8] = this._t0.x;
  21325. this._cachedTextureMatrix.m[9] = this._t0.y;
  21326. this._cachedTextureMatrix.m[10] = this._t0.z;
  21327. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  21328. return mat.hasTexture(_this);
  21329. });
  21330. return this._cachedTextureMatrix;
  21331. };
  21332. Texture.prototype.getReflectionTextureMatrix = function () {
  21333. var _this = this;
  21334. var scene = this.getScene();
  21335. if (this.uOffset === this._cachedUOffset &&
  21336. this.vOffset === this._cachedVOffset &&
  21337. this.uScale === this._cachedUScale &&
  21338. this.vScale === this._cachedVScale &&
  21339. this.coordinatesMode === this._cachedCoordinatesMode) {
  21340. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  21341. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  21342. return this._cachedTextureMatrix;
  21343. }
  21344. }
  21345. else {
  21346. return this._cachedTextureMatrix;
  21347. }
  21348. }
  21349. if (!this._cachedTextureMatrix) {
  21350. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21351. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  21352. }
  21353. this._cachedUOffset = this.uOffset;
  21354. this._cachedVOffset = this.vOffset;
  21355. this._cachedUScale = this.uScale;
  21356. this._cachedVScale = this.vScale;
  21357. this._cachedCoordinatesMode = this.coordinatesMode;
  21358. switch (this.coordinatesMode) {
  21359. case Texture.PLANAR_MODE:
  21360. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21361. this._cachedTextureMatrix[0] = this.uScale;
  21362. this._cachedTextureMatrix[5] = this.vScale;
  21363. this._cachedTextureMatrix[12] = this.uOffset;
  21364. this._cachedTextureMatrix[13] = this.vOffset;
  21365. break;
  21366. case Texture.PROJECTION_MODE:
  21367. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  21368. this._projectionModeMatrix.m[0] = 0.5;
  21369. this._projectionModeMatrix.m[5] = -0.5;
  21370. this._projectionModeMatrix.m[10] = 0.0;
  21371. this._projectionModeMatrix.m[12] = 0.5;
  21372. this._projectionModeMatrix.m[13] = 0.5;
  21373. this._projectionModeMatrix.m[14] = 1.0;
  21374. this._projectionModeMatrix.m[15] = 1.0;
  21375. var projectionMatrix = scene.getProjectionMatrix();
  21376. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  21377. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  21378. break;
  21379. default:
  21380. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21381. break;
  21382. }
  21383. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  21384. return (mat.getActiveTextures().indexOf(_this) !== -1);
  21385. });
  21386. return this._cachedTextureMatrix;
  21387. };
  21388. Texture.prototype.clone = function () {
  21389. var _this = this;
  21390. return BABYLON.SerializationHelper.Clone(function () {
  21391. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  21392. }, this);
  21393. };
  21394. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  21395. get: function () {
  21396. if (!this._onLoadObservable) {
  21397. this._onLoadObservable = new BABYLON.Observable();
  21398. }
  21399. return this._onLoadObservable;
  21400. },
  21401. enumerable: true,
  21402. configurable: true
  21403. });
  21404. Texture.prototype.serialize = function () {
  21405. var serializationObject = _super.prototype.serialize.call(this);
  21406. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  21407. serializationObject.base64String = this._buffer;
  21408. serializationObject.name = serializationObject.name.replace("data:", "");
  21409. }
  21410. return serializationObject;
  21411. };
  21412. Texture.prototype.getClassName = function () {
  21413. return "Texture";
  21414. };
  21415. Texture.prototype.dispose = function () {
  21416. _super.prototype.dispose.call(this);
  21417. if (this.onLoadObservable) {
  21418. this.onLoadObservable.clear();
  21419. this._onLoadObservable = null;
  21420. }
  21421. this._delayedOnLoad = null;
  21422. this._delayedOnError = null;
  21423. };
  21424. // Statics
  21425. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  21426. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21427. if (onLoad === void 0) { onLoad = null; }
  21428. if (onError === void 0) { onError = null; }
  21429. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  21430. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  21431. };
  21432. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  21433. if (parsedTexture.customType) {
  21434. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  21435. // Update Sampling Mode
  21436. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  21437. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  21438. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  21439. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  21440. }
  21441. }
  21442. return parsedCustomTexture;
  21443. }
  21444. if (parsedTexture.isCube) {
  21445. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  21446. }
  21447. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  21448. return null;
  21449. }
  21450. var texture = BABYLON.SerializationHelper.Parse(function () {
  21451. if (parsedTexture.mirrorPlane) {
  21452. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21453. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  21454. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  21455. return mirrorTexture;
  21456. }
  21457. else if (parsedTexture.isRenderTarget) {
  21458. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21459. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  21460. return renderTargetTexture;
  21461. }
  21462. else {
  21463. var texture;
  21464. if (parsedTexture.base64String) {
  21465. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  21466. }
  21467. else {
  21468. texture = new Texture(rootUrl + parsedTexture.name, scene);
  21469. }
  21470. return texture;
  21471. }
  21472. }, parsedTexture, scene);
  21473. // Update Sampling Mode
  21474. if (parsedTexture.samplingMode) {
  21475. var sampling = parsedTexture.samplingMode;
  21476. if (texture._samplingMode !== sampling) {
  21477. texture.updateSamplingMode(sampling);
  21478. }
  21479. }
  21480. // Animations
  21481. if (parsedTexture.animations) {
  21482. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21483. var parsedAnimation = parsedTexture.animations[animationIndex];
  21484. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21485. }
  21486. }
  21487. return texture;
  21488. };
  21489. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  21490. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21491. if (noMipmap === void 0) { noMipmap = false; }
  21492. if (invertY === void 0) { invertY = true; }
  21493. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21494. if (onLoad === void 0) { onLoad = null; }
  21495. if (onError === void 0) { onError = null; }
  21496. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  21497. if (name.substr(0, 5) !== "data:") {
  21498. name = "data:" + name;
  21499. }
  21500. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  21501. };
  21502. // Constants
  21503. Texture.NEAREST_SAMPLINGMODE = 1;
  21504. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  21505. Texture.BILINEAR_SAMPLINGMODE = 2;
  21506. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  21507. Texture.TRILINEAR_SAMPLINGMODE = 3;
  21508. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  21509. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  21510. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  21511. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  21512. Texture.NEAREST_LINEAR = 7;
  21513. Texture.NEAREST_NEAREST = 8;
  21514. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  21515. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  21516. Texture.LINEAR_LINEAR = 11;
  21517. Texture.LINEAR_NEAREST = 12;
  21518. Texture.EXPLICIT_MODE = 0;
  21519. Texture.SPHERICAL_MODE = 1;
  21520. Texture.PLANAR_MODE = 2;
  21521. Texture.CUBIC_MODE = 3;
  21522. Texture.PROJECTION_MODE = 4;
  21523. Texture.SKYBOX_MODE = 5;
  21524. Texture.INVCUBIC_MODE = 6;
  21525. Texture.EQUIRECTANGULAR_MODE = 7;
  21526. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  21527. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  21528. Texture.CLAMP_ADDRESSMODE = 0;
  21529. Texture.WRAP_ADDRESSMODE = 1;
  21530. Texture.MIRROR_ADDRESSMODE = 2;
  21531. __decorate([
  21532. BABYLON.serialize()
  21533. ], Texture.prototype, "url", void 0);
  21534. __decorate([
  21535. BABYLON.serialize()
  21536. ], Texture.prototype, "uOffset", void 0);
  21537. __decorate([
  21538. BABYLON.serialize()
  21539. ], Texture.prototype, "vOffset", void 0);
  21540. __decorate([
  21541. BABYLON.serialize()
  21542. ], Texture.prototype, "uScale", void 0);
  21543. __decorate([
  21544. BABYLON.serialize()
  21545. ], Texture.prototype, "vScale", void 0);
  21546. __decorate([
  21547. BABYLON.serialize()
  21548. ], Texture.prototype, "uAng", void 0);
  21549. __decorate([
  21550. BABYLON.serialize()
  21551. ], Texture.prototype, "vAng", void 0);
  21552. __decorate([
  21553. BABYLON.serialize()
  21554. ], Texture.prototype, "wAng", void 0);
  21555. __decorate([
  21556. BABYLON.serialize()
  21557. ], Texture.prototype, "isBlocking", null);
  21558. return Texture;
  21559. }(BABYLON.BaseTexture));
  21560. BABYLON.Texture = Texture;
  21561. })(BABYLON || (BABYLON = {}));
  21562. //# sourceMappingURL=babylon.texture.js.map
  21563. var BABYLON;
  21564. (function (BABYLON) {
  21565. var _InstancesBatch = (function () {
  21566. function _InstancesBatch() {
  21567. this.mustReturn = false;
  21568. this.visibleInstances = new Array();
  21569. this.renderSelf = new Array();
  21570. }
  21571. return _InstancesBatch;
  21572. }());
  21573. BABYLON._InstancesBatch = _InstancesBatch;
  21574. var Mesh = (function (_super) {
  21575. __extends(Mesh, _super);
  21576. /**
  21577. * @constructor
  21578. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  21579. * @param {Scene} scene The scene to add this mesh to.
  21580. * @param {Node} parent The parent of this mesh, if it has one
  21581. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  21582. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  21583. * When false, achieved by calling a clone(), also passing False.
  21584. * This will make creation of children, recursive.
  21585. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  21586. */
  21587. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  21588. if (parent === void 0) { parent = null; }
  21589. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  21590. var _this = _super.call(this, name, scene) || this;
  21591. // Events
  21592. /**
  21593. * An event triggered before rendering the mesh
  21594. * @type {BABYLON.Observable}
  21595. */
  21596. _this.onBeforeRenderObservable = new BABYLON.Observable();
  21597. /**
  21598. * An event triggered after rendering the mesh
  21599. * @type {BABYLON.Observable}
  21600. */
  21601. _this.onAfterRenderObservable = new BABYLON.Observable();
  21602. /**
  21603. * An event triggered before drawing the mesh
  21604. * @type {BABYLON.Observable}
  21605. */
  21606. _this.onBeforeDrawObservable = new BABYLON.Observable();
  21607. // Members
  21608. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21609. _this.instances = new Array();
  21610. _this._LODLevels = new Array();
  21611. _this._visibleInstances = {};
  21612. _this._renderIdForInstances = new Array();
  21613. _this._batchCache = new _InstancesBatch();
  21614. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  21615. // Use by builder only to know what orientation were the mesh build in.
  21616. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  21617. _this.overrideMaterialSideOrientation = null;
  21618. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  21619. // Will be used to save a source mesh reference, If any
  21620. _this._source = null;
  21621. if (source) {
  21622. // Source mesh
  21623. _this._source = source;
  21624. // Geometry
  21625. if (source._geometry) {
  21626. source._geometry.applyToMesh(_this);
  21627. }
  21628. // Deep copy
  21629. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  21630. // Parent
  21631. _this.parent = source.parent;
  21632. // Pivot
  21633. _this.setPivotMatrix(source.getPivotMatrix());
  21634. _this.id = name + "." + source.id;
  21635. // Material
  21636. _this.material = source.material;
  21637. var index;
  21638. if (!doNotCloneChildren) {
  21639. // Children
  21640. for (index = 0; index < scene.meshes.length; index++) {
  21641. var mesh = scene.meshes[index];
  21642. if (mesh.parent === source) {
  21643. // doNotCloneChildren is always going to be False
  21644. mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  21645. }
  21646. }
  21647. }
  21648. // Physics clone
  21649. var physicsEngine = _this.getScene().getPhysicsEngine();
  21650. if (clonePhysicsImpostor && physicsEngine) {
  21651. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  21652. if (impostor) {
  21653. _this.physicsImpostor = impostor.clone(_this);
  21654. }
  21655. }
  21656. // Particles
  21657. for (index = 0; index < scene.particleSystems.length; index++) {
  21658. var system = scene.particleSystems[index];
  21659. if (system.emitter === source) {
  21660. system.clone(system.name, _this);
  21661. }
  21662. }
  21663. _this.computeWorldMatrix(true);
  21664. }
  21665. // Parent
  21666. if (parent !== null) {
  21667. _this.parent = parent;
  21668. }
  21669. return _this;
  21670. }
  21671. Object.defineProperty(Mesh, "FRONTSIDE", {
  21672. /**
  21673. * Mesh side orientation : usually the external or front surface
  21674. */
  21675. get: function () {
  21676. return Mesh._FRONTSIDE;
  21677. },
  21678. enumerable: true,
  21679. configurable: true
  21680. });
  21681. Object.defineProperty(Mesh, "BACKSIDE", {
  21682. /**
  21683. * Mesh side orientation : usually the internal or back surface
  21684. */
  21685. get: function () {
  21686. return Mesh._BACKSIDE;
  21687. },
  21688. enumerable: true,
  21689. configurable: true
  21690. });
  21691. Object.defineProperty(Mesh, "DOUBLESIDE", {
  21692. /**
  21693. * Mesh side orientation : both internal and external or front and back surfaces
  21694. */
  21695. get: function () {
  21696. return Mesh._DOUBLESIDE;
  21697. },
  21698. enumerable: true,
  21699. configurable: true
  21700. });
  21701. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  21702. /**
  21703. * Mesh side orientation : by default, `FRONTSIDE`
  21704. */
  21705. get: function () {
  21706. return Mesh._DEFAULTSIDE;
  21707. },
  21708. enumerable: true,
  21709. configurable: true
  21710. });
  21711. Object.defineProperty(Mesh, "NO_CAP", {
  21712. /**
  21713. * Mesh cap setting : no cap
  21714. */
  21715. get: function () {
  21716. return Mesh._NO_CAP;
  21717. },
  21718. enumerable: true,
  21719. configurable: true
  21720. });
  21721. Object.defineProperty(Mesh, "CAP_START", {
  21722. /**
  21723. * Mesh cap setting : one cap at the beginning of the mesh
  21724. */
  21725. get: function () {
  21726. return Mesh._CAP_START;
  21727. },
  21728. enumerable: true,
  21729. configurable: true
  21730. });
  21731. Object.defineProperty(Mesh, "CAP_END", {
  21732. /**
  21733. * Mesh cap setting : one cap at the end of the mesh
  21734. */
  21735. get: function () {
  21736. return Mesh._CAP_END;
  21737. },
  21738. enumerable: true,
  21739. configurable: true
  21740. });
  21741. Object.defineProperty(Mesh, "CAP_ALL", {
  21742. /**
  21743. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  21744. */
  21745. get: function () {
  21746. return Mesh._CAP_ALL;
  21747. },
  21748. enumerable: true,
  21749. configurable: true
  21750. });
  21751. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  21752. set: function (callback) {
  21753. if (this._onBeforeDrawObserver) {
  21754. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  21755. }
  21756. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  21757. },
  21758. enumerable: true,
  21759. configurable: true
  21760. });
  21761. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  21762. get: function () {
  21763. return this._morphTargetManager;
  21764. },
  21765. set: function (value) {
  21766. if (this._morphTargetManager === value) {
  21767. return;
  21768. }
  21769. this._morphTargetManager = value;
  21770. this._syncGeometryWithMorphTargetManager();
  21771. },
  21772. enumerable: true,
  21773. configurable: true
  21774. });
  21775. Object.defineProperty(Mesh.prototype, "source", {
  21776. get: function () {
  21777. return this._source;
  21778. },
  21779. enumerable: true,
  21780. configurable: true
  21781. });
  21782. // Methods
  21783. /**
  21784. * Returns the string "Mesh".
  21785. */
  21786. Mesh.prototype.getClassName = function () {
  21787. return "Mesh";
  21788. };
  21789. /**
  21790. * Returns a string.
  21791. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21792. */
  21793. Mesh.prototype.toString = function (fullDetails) {
  21794. var ret = _super.prototype.toString.call(this, fullDetails);
  21795. ret += ", n vertices: " + this.getTotalVertices();
  21796. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  21797. if (this.animations) {
  21798. for (var i = 0; i < this.animations.length; i++) {
  21799. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21800. }
  21801. }
  21802. if (fullDetails) {
  21803. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  21804. }
  21805. return ret;
  21806. };
  21807. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  21808. /**
  21809. * True if the mesh has some Levels Of Details (LOD).
  21810. * Returns a boolean.
  21811. */
  21812. get: function () {
  21813. return this._LODLevels.length > 0;
  21814. },
  21815. enumerable: true,
  21816. configurable: true
  21817. });
  21818. Mesh.prototype._sortLODLevels = function () {
  21819. this._LODLevels.sort(function (a, b) {
  21820. if (a.distance < b.distance) {
  21821. return 1;
  21822. }
  21823. if (a.distance > b.distance) {
  21824. return -1;
  21825. }
  21826. return 0;
  21827. });
  21828. };
  21829. /**
  21830. * Add a mesh as LOD level triggered at the given distance.
  21831. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21832. * @param {number} distance The distance from the center of the object to show this level
  21833. * @param {Mesh} mesh The mesh to be added as LOD level
  21834. * @return {Mesh} This mesh (for chaining)
  21835. */
  21836. Mesh.prototype.addLODLevel = function (distance, mesh) {
  21837. if (mesh && mesh._masterMesh) {
  21838. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  21839. return this;
  21840. }
  21841. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  21842. this._LODLevels.push(level);
  21843. if (mesh) {
  21844. mesh._masterMesh = this;
  21845. }
  21846. this._sortLODLevels();
  21847. return this;
  21848. };
  21849. /**
  21850. * Returns the LOD level mesh at the passed distance or null if not found.
  21851. * It is related to the method `addLODLevel(distance, mesh)`.
  21852. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21853. * Returns an object Mesh or `null`.
  21854. */
  21855. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  21856. for (var index = 0; index < this._LODLevels.length; index++) {
  21857. var level = this._LODLevels[index];
  21858. if (level.distance === distance) {
  21859. return level.mesh;
  21860. }
  21861. }
  21862. return null;
  21863. };
  21864. /**
  21865. * Remove a mesh from the LOD array
  21866. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21867. * @param {Mesh} mesh The mesh to be removed.
  21868. * @return {Mesh} This mesh (for chaining)
  21869. */
  21870. Mesh.prototype.removeLODLevel = function (mesh) {
  21871. for (var index = 0; index < this._LODLevels.length; index++) {
  21872. if (this._LODLevels[index].mesh === mesh) {
  21873. this._LODLevels.splice(index, 1);
  21874. if (mesh) {
  21875. mesh._masterMesh = null;
  21876. }
  21877. }
  21878. }
  21879. this._sortLODLevels();
  21880. return this;
  21881. };
  21882. /**
  21883. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  21884. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21885. */
  21886. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  21887. if (!this._LODLevels || this._LODLevels.length === 0) {
  21888. return this;
  21889. }
  21890. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  21891. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  21892. if (this.onLODLevelSelection) {
  21893. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  21894. }
  21895. return this;
  21896. }
  21897. for (var index = 0; index < this._LODLevels.length; index++) {
  21898. var level = this._LODLevels[index];
  21899. if (level.distance < distanceToCamera) {
  21900. if (level.mesh) {
  21901. level.mesh._preActivate();
  21902. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21903. }
  21904. if (this.onLODLevelSelection) {
  21905. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  21906. }
  21907. return level.mesh;
  21908. }
  21909. }
  21910. if (this.onLODLevelSelection) {
  21911. this.onLODLevelSelection(distanceToCamera, this, this);
  21912. }
  21913. return this;
  21914. };
  21915. Object.defineProperty(Mesh.prototype, "geometry", {
  21916. /**
  21917. * Returns the mesh internal Geometry object.
  21918. */
  21919. get: function () {
  21920. return this._geometry;
  21921. },
  21922. enumerable: true,
  21923. configurable: true
  21924. });
  21925. /**
  21926. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  21927. */
  21928. Mesh.prototype.getTotalVertices = function () {
  21929. if (!this._geometry) {
  21930. return 0;
  21931. }
  21932. return this._geometry.getTotalVertices();
  21933. };
  21934. /**
  21935. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  21936. * 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.
  21937. * You can force the copy with forceCopy === true
  21938. * Returns null if the mesh has no geometry or no vertex buffer.
  21939. * Possible `kind` values :
  21940. * - BABYLON.VertexBuffer.PositionKind
  21941. * - BABYLON.VertexBuffer.UVKind
  21942. * - BABYLON.VertexBuffer.UV2Kind
  21943. * - BABYLON.VertexBuffer.UV3Kind
  21944. * - BABYLON.VertexBuffer.UV4Kind
  21945. * - BABYLON.VertexBuffer.UV5Kind
  21946. * - BABYLON.VertexBuffer.UV6Kind
  21947. * - BABYLON.VertexBuffer.ColorKind
  21948. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21949. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21950. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21951. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21952. */
  21953. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  21954. if (!this._geometry) {
  21955. return null;
  21956. }
  21957. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  21958. };
  21959. /**
  21960. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  21961. * Returns `undefined` if the mesh has no geometry.
  21962. * Possible `kind` values :
  21963. * - BABYLON.VertexBuffer.PositionKind
  21964. * - BABYLON.VertexBuffer.UVKind
  21965. * - BABYLON.VertexBuffer.UV2Kind
  21966. * - BABYLON.VertexBuffer.UV3Kind
  21967. * - BABYLON.VertexBuffer.UV4Kind
  21968. * - BABYLON.VertexBuffer.UV5Kind
  21969. * - BABYLON.VertexBuffer.UV6Kind
  21970. * - BABYLON.VertexBuffer.ColorKind
  21971. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21972. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21973. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21974. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21975. */
  21976. Mesh.prototype.getVertexBuffer = function (kind) {
  21977. if (!this._geometry) {
  21978. return undefined;
  21979. }
  21980. return this._geometry.getVertexBuffer(kind);
  21981. };
  21982. /**
  21983. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  21984. * Possible `kind` values :
  21985. * - BABYLON.VertexBuffer.PositionKind
  21986. * - BABYLON.VertexBuffer.UVKind
  21987. * - BABYLON.VertexBuffer.UV2Kind
  21988. * - BABYLON.VertexBuffer.UV3Kind
  21989. * - BABYLON.VertexBuffer.UV4Kind
  21990. * - BABYLON.VertexBuffer.UV5Kind
  21991. * - BABYLON.VertexBuffer.UV6Kind
  21992. * - BABYLON.VertexBuffer.ColorKind
  21993. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21994. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21995. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21996. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21997. */
  21998. Mesh.prototype.isVerticesDataPresent = function (kind) {
  21999. if (!this._geometry) {
  22000. if (this._delayInfo) {
  22001. return this._delayInfo.indexOf(kind) !== -1;
  22002. }
  22003. return false;
  22004. }
  22005. return this._geometry.isVerticesDataPresent(kind);
  22006. };
  22007. /**
  22008. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  22009. * Possible `kind` values :
  22010. * - BABYLON.VertexBuffer.PositionKind
  22011. * - BABYLON.VertexBuffer.UVKind
  22012. * - BABYLON.VertexBuffer.UV2Kind
  22013. * - BABYLON.VertexBuffer.UV3Kind
  22014. * - BABYLON.VertexBuffer.UV4Kind
  22015. * - BABYLON.VertexBuffer.UV5Kind
  22016. * - BABYLON.VertexBuffer.UV6Kind
  22017. * - BABYLON.VertexBuffer.ColorKind
  22018. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22019. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22020. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22021. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22022. */
  22023. Mesh.prototype.getVerticesDataKinds = function () {
  22024. if (!this._geometry) {
  22025. var result = new Array();
  22026. if (this._delayInfo) {
  22027. this._delayInfo.forEach(function (kind, index, array) {
  22028. result.push(kind);
  22029. });
  22030. }
  22031. return result;
  22032. }
  22033. return this._geometry.getVerticesDataKinds();
  22034. };
  22035. /**
  22036. * Returns a positive integer : the total number of indices in this mesh geometry.
  22037. * Returns zero if the mesh has no geometry.
  22038. */
  22039. Mesh.prototype.getTotalIndices = function () {
  22040. if (!this._geometry) {
  22041. return 0;
  22042. }
  22043. return this._geometry.getTotalIndices();
  22044. };
  22045. /**
  22046. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  22047. * 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.
  22048. * Returns an empty array if the mesh has no geometry.
  22049. */
  22050. Mesh.prototype.getIndices = function (copyWhenShared) {
  22051. if (!this._geometry) {
  22052. return [];
  22053. }
  22054. return this._geometry.getIndices(copyWhenShared);
  22055. };
  22056. Object.defineProperty(Mesh.prototype, "isBlocked", {
  22057. get: function () {
  22058. return this._masterMesh !== null && this._masterMesh !== undefined;
  22059. },
  22060. enumerable: true,
  22061. configurable: true
  22062. });
  22063. /**
  22064. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  22065. */
  22066. Mesh.prototype.isReady = function () {
  22067. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22068. return false;
  22069. }
  22070. return _super.prototype.isReady.call(this);
  22071. };
  22072. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  22073. /**
  22074. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  22075. * This property is pertinent only for updatable parametric shapes.
  22076. */
  22077. get: function () {
  22078. return this._areNormalsFrozen;
  22079. },
  22080. enumerable: true,
  22081. configurable: true
  22082. });
  22083. /**
  22084. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22085. * It has no effect at all on other shapes.
  22086. * It prevents the mesh normals from being recomputed on next `positions` array update.
  22087. * Returns the Mesh.
  22088. */
  22089. Mesh.prototype.freezeNormals = function () {
  22090. this._areNormalsFrozen = true;
  22091. return this;
  22092. };
  22093. /**
  22094. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22095. * It has no effect at all on other shapes.
  22096. * It reactivates the mesh normals computation if it was previously frozen.
  22097. * Returns the Mesh.
  22098. */
  22099. Mesh.prototype.unfreezeNormals = function () {
  22100. this._areNormalsFrozen = false;
  22101. return this;
  22102. };
  22103. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  22104. /**
  22105. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  22106. */
  22107. set: function (count) {
  22108. this._overridenInstanceCount = count;
  22109. },
  22110. enumerable: true,
  22111. configurable: true
  22112. });
  22113. // Methods
  22114. Mesh.prototype._preActivate = function () {
  22115. var sceneRenderId = this.getScene().getRenderId();
  22116. if (this._preActivateId === sceneRenderId) {
  22117. return this;
  22118. }
  22119. this._preActivateId = sceneRenderId;
  22120. this._visibleInstances = null;
  22121. return this;
  22122. };
  22123. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  22124. if (this._visibleInstances) {
  22125. this._visibleInstances.intermediateDefaultRenderId = renderId;
  22126. }
  22127. return this;
  22128. };
  22129. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  22130. if (!this._visibleInstances) {
  22131. this._visibleInstances = {};
  22132. this._visibleInstances.defaultRenderId = renderId;
  22133. this._visibleInstances.selfDefaultRenderId = this._renderId;
  22134. }
  22135. if (!this._visibleInstances[renderId]) {
  22136. this._visibleInstances[renderId] = new Array();
  22137. }
  22138. this._visibleInstances[renderId].push(instance);
  22139. return this;
  22140. };
  22141. /**
  22142. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  22143. * This means the mesh underlying bounding box and sphere are recomputed.
  22144. * Returns the Mesh.
  22145. */
  22146. Mesh.prototype.refreshBoundingInfo = function () {
  22147. if (this._boundingInfo.isLocked) {
  22148. return this;
  22149. }
  22150. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22151. if (data) {
  22152. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  22153. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22154. }
  22155. if (this.subMeshes) {
  22156. for (var index = 0; index < this.subMeshes.length; index++) {
  22157. this.subMeshes[index].refreshBoundingInfo();
  22158. }
  22159. }
  22160. this._updateBoundingInfo();
  22161. return this;
  22162. };
  22163. Mesh.prototype._createGlobalSubMesh = function (force) {
  22164. var totalVertices = this.getTotalVertices();
  22165. if (!totalVertices || !this.getIndices()) {
  22166. return null;
  22167. }
  22168. // Check if we need to recreate the submeshes
  22169. if (this.subMeshes && this.subMeshes.length > 0) {
  22170. var totalIndices = this.getIndices().length;
  22171. var needToRecreate = false;
  22172. if (force) {
  22173. needToRecreate = true;
  22174. }
  22175. else {
  22176. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  22177. var submesh = _a[_i];
  22178. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  22179. needToRecreate = true;
  22180. break;
  22181. }
  22182. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  22183. needToRecreate = true;
  22184. break;
  22185. }
  22186. }
  22187. }
  22188. if (!needToRecreate) {
  22189. return this.subMeshes[0];
  22190. }
  22191. }
  22192. this.releaseSubMeshes();
  22193. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  22194. };
  22195. Mesh.prototype.subdivide = function (count) {
  22196. if (count < 1) {
  22197. return;
  22198. }
  22199. var totalIndices = this.getTotalIndices();
  22200. var subdivisionSize = (totalIndices / count) | 0;
  22201. var offset = 0;
  22202. // Ensure that subdivisionSize is a multiple of 3
  22203. while (subdivisionSize % 3 !== 0) {
  22204. subdivisionSize++;
  22205. }
  22206. this.releaseSubMeshes();
  22207. for (var index = 0; index < count; index++) {
  22208. if (offset >= totalIndices) {
  22209. break;
  22210. }
  22211. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  22212. offset += subdivisionSize;
  22213. }
  22214. this.synchronizeInstances();
  22215. };
  22216. /**
  22217. * Sets the vertex data of the mesh geometry for the requested `kind`.
  22218. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  22219. * The `data` are either a numeric array either a Float32Array.
  22220. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  22221. * 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).
  22222. * Note that a new underlying VertexBuffer object is created each call.
  22223. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  22224. *
  22225. * Possible `kind` values :
  22226. * - BABYLON.VertexBuffer.PositionKind
  22227. * - BABYLON.VertexBuffer.UVKind
  22228. * - BABYLON.VertexBuffer.UV2Kind
  22229. * - BABYLON.VertexBuffer.UV3Kind
  22230. * - BABYLON.VertexBuffer.UV4Kind
  22231. * - BABYLON.VertexBuffer.UV5Kind
  22232. * - BABYLON.VertexBuffer.UV6Kind
  22233. * - BABYLON.VertexBuffer.ColorKind
  22234. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22235. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22236. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22237. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22238. *
  22239. * Returns the Mesh.
  22240. */
  22241. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22242. if (!this._geometry) {
  22243. var vertexData = new BABYLON.VertexData();
  22244. vertexData.set(data, kind);
  22245. var scene = this.getScene();
  22246. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  22247. }
  22248. else {
  22249. this._geometry.setVerticesData(kind, data, updatable, stride);
  22250. }
  22251. return this;
  22252. };
  22253. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  22254. if (updatable === void 0) { updatable = true; }
  22255. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  22256. return;
  22257. }
  22258. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  22259. };
  22260. /**
  22261. * Sets the mesh VertexBuffer.
  22262. * Returns the Mesh.
  22263. */
  22264. Mesh.prototype.setVerticesBuffer = function (buffer) {
  22265. if (!this._geometry) {
  22266. var scene = this.getScene();
  22267. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  22268. }
  22269. this._geometry.setVerticesBuffer(buffer);
  22270. return this;
  22271. };
  22272. /**
  22273. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  22274. * If the mesh has no geometry, it is simply returned as it is.
  22275. * The `data` are either a numeric array either a Float32Array.
  22276. * No new underlying VertexBuffer object is created.
  22277. * 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.
  22278. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  22279. *
  22280. * Possible `kind` values :
  22281. * - BABYLON.VertexBuffer.PositionKind
  22282. * - BABYLON.VertexBuffer.UVKind
  22283. * - BABYLON.VertexBuffer.UV2Kind
  22284. * - BABYLON.VertexBuffer.UV3Kind
  22285. * - BABYLON.VertexBuffer.UV4Kind
  22286. * - BABYLON.VertexBuffer.UV5Kind
  22287. * - BABYLON.VertexBuffer.UV6Kind
  22288. * - BABYLON.VertexBuffer.ColorKind
  22289. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22290. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22291. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22292. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22293. *
  22294. * Returns the Mesh.
  22295. */
  22296. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  22297. if (!this._geometry) {
  22298. return this;
  22299. }
  22300. if (!makeItUnique) {
  22301. this._geometry.updateVerticesData(kind, data, updateExtends);
  22302. }
  22303. else {
  22304. this.makeGeometryUnique();
  22305. this.updateVerticesData(kind, data, updateExtends, false);
  22306. }
  22307. return this;
  22308. };
  22309. /**
  22310. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  22311. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  22312. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  22313. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  22314. * Returns the Mesh.
  22315. */
  22316. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  22317. if (computeNormals === void 0) { computeNormals = true; }
  22318. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22319. positionFunction(positions);
  22320. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  22321. if (computeNormals) {
  22322. var indices = this.getIndices();
  22323. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22324. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  22325. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  22326. }
  22327. return this;
  22328. };
  22329. /**
  22330. * Creates a un-shared specific occurence of the geometry for the mesh.
  22331. * Returns the Mesh.
  22332. */
  22333. Mesh.prototype.makeGeometryUnique = function () {
  22334. if (!this._geometry) {
  22335. return this;
  22336. }
  22337. var oldGeometry = this._geometry;
  22338. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  22339. oldGeometry.releaseForMesh(this, true);
  22340. geometry.applyToMesh(this);
  22341. return this;
  22342. };
  22343. /**
  22344. * Sets the mesh indices.
  22345. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  22346. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  22347. * This method creates a new index buffer each call.
  22348. * Returns the Mesh.
  22349. */
  22350. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  22351. if (!this._geometry) {
  22352. var vertexData = new BABYLON.VertexData();
  22353. vertexData.indices = indices;
  22354. var scene = this.getScene();
  22355. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  22356. }
  22357. else {
  22358. this._geometry.setIndices(indices, totalVertices, updatable);
  22359. }
  22360. return this;
  22361. };
  22362. /**
  22363. * Update the current index buffer
  22364. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  22365. * Returns the Mesh.
  22366. */
  22367. Mesh.prototype.updateIndices = function (indices, offset) {
  22368. if (!this._geometry) {
  22369. return this;
  22370. }
  22371. this._geometry.updateIndices(indices, offset);
  22372. return this;
  22373. };
  22374. /**
  22375. * Invert the geometry to move from a right handed system to a left handed one.
  22376. * Returns the Mesh.
  22377. */
  22378. Mesh.prototype.toLeftHanded = function () {
  22379. if (!this._geometry) {
  22380. return this;
  22381. }
  22382. this._geometry.toLeftHanded();
  22383. return this;
  22384. };
  22385. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  22386. var engine = this.getScene().getEngine();
  22387. // Wireframe
  22388. var indexToBind;
  22389. if (this._unIndexed) {
  22390. indexToBind = null;
  22391. }
  22392. else {
  22393. switch (fillMode) {
  22394. case BABYLON.Material.PointFillMode:
  22395. indexToBind = null;
  22396. break;
  22397. case BABYLON.Material.WireFrameFillMode:
  22398. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  22399. break;
  22400. default:
  22401. case BABYLON.Material.TriangleFillMode:
  22402. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  22403. break;
  22404. }
  22405. }
  22406. // VBOs
  22407. this._geometry._bind(effect, indexToBind);
  22408. return this;
  22409. };
  22410. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  22411. if (alternate === void 0) { alternate = false; }
  22412. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22413. return this;
  22414. }
  22415. this.onBeforeDrawObservable.notifyObservers(this);
  22416. var scene = this.getScene();
  22417. var engine = scene.getEngine();
  22418. // Draw order
  22419. switch (fillMode) {
  22420. case BABYLON.Material.PointFillMode:
  22421. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22422. break;
  22423. case BABYLON.Material.WireFrameFillMode:
  22424. if (this._unIndexed) {
  22425. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22426. }
  22427. else {
  22428. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  22429. }
  22430. break;
  22431. default:
  22432. if (this._unIndexed) {
  22433. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22434. }
  22435. else {
  22436. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  22437. }
  22438. }
  22439. if (scene._isAlternateRenderingEnabled && !alternate) {
  22440. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  22441. scene._switchToAlternateCameraConfiguration(true);
  22442. this._effectiveMaterial.bindView(effect);
  22443. this._effectiveMaterial.bindViewProjection(effect);
  22444. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  22445. this._draw(subMesh, fillMode, instancesCount, true);
  22446. engine.setViewport(scene.activeCamera.viewport);
  22447. scene._switchToAlternateCameraConfiguration(false);
  22448. this._effectiveMaterial.bindView(effect);
  22449. this._effectiveMaterial.bindViewProjection(effect);
  22450. }
  22451. return this;
  22452. };
  22453. /**
  22454. * Registers for this mesh a javascript function called just before the rendering process.
  22455. * This function is passed the current mesh.
  22456. * Return the Mesh.
  22457. */
  22458. Mesh.prototype.registerBeforeRender = function (func) {
  22459. this.onBeforeRenderObservable.add(func);
  22460. return this;
  22461. };
  22462. /**
  22463. * Disposes a previously registered javascript function called before the rendering.
  22464. * This function is passed the current mesh.
  22465. * Returns the Mesh.
  22466. */
  22467. Mesh.prototype.unregisterBeforeRender = function (func) {
  22468. this.onBeforeRenderObservable.removeCallback(func);
  22469. return this;
  22470. };
  22471. /**
  22472. * Registers for this mesh a javascript function called just after the rendering is complete.
  22473. * This function is passed the current mesh.
  22474. * Returns the Mesh.
  22475. */
  22476. Mesh.prototype.registerAfterRender = function (func) {
  22477. this.onAfterRenderObservable.add(func);
  22478. return this;
  22479. };
  22480. /**
  22481. * Disposes a previously registered javascript function called after the rendering.
  22482. * This function is passed the current mesh.
  22483. * Return the Mesh.
  22484. */
  22485. Mesh.prototype.unregisterAfterRender = function (func) {
  22486. this.onAfterRenderObservable.removeCallback(func);
  22487. return this;
  22488. };
  22489. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  22490. var scene = this.getScene();
  22491. this._batchCache.mustReturn = false;
  22492. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  22493. this._batchCache.visibleInstances[subMeshId] = null;
  22494. if (this._visibleInstances) {
  22495. var currentRenderId = scene.getRenderId();
  22496. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  22497. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  22498. var selfRenderId = this._renderId;
  22499. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  22500. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  22501. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  22502. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  22503. }
  22504. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  22505. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  22506. this._batchCache.mustReturn = true;
  22507. return this._batchCache;
  22508. }
  22509. if (currentRenderId !== selfRenderId) {
  22510. this._batchCache.renderSelf[subMeshId] = false;
  22511. }
  22512. }
  22513. this._renderIdForInstances[subMeshId] = currentRenderId;
  22514. }
  22515. return this._batchCache;
  22516. };
  22517. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  22518. var visibleInstances = batch.visibleInstances[subMesh._id];
  22519. var matricesCount = visibleInstances.length + 1;
  22520. var bufferSize = matricesCount * 16 * 4;
  22521. var currentInstancesBufferSize = this._instancesBufferSize;
  22522. var instancesBuffer = this._instancesBuffer;
  22523. while (this._instancesBufferSize < bufferSize) {
  22524. this._instancesBufferSize *= 2;
  22525. }
  22526. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  22527. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  22528. }
  22529. var offset = 0;
  22530. var instancesCount = 0;
  22531. var world = this.getWorldMatrix();
  22532. if (batch.renderSelf[subMesh._id]) {
  22533. world.copyToArray(this._instancesData, offset);
  22534. offset += 16;
  22535. instancesCount++;
  22536. }
  22537. if (visibleInstances) {
  22538. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  22539. var instance = visibleInstances[instanceIndex];
  22540. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  22541. offset += 16;
  22542. instancesCount++;
  22543. }
  22544. }
  22545. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  22546. if (instancesBuffer) {
  22547. instancesBuffer.dispose();
  22548. }
  22549. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  22550. this._instancesBuffer = instancesBuffer;
  22551. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  22552. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  22553. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  22554. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  22555. }
  22556. else {
  22557. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  22558. }
  22559. this._bind(subMesh, effect, fillMode);
  22560. this._draw(subMesh, fillMode, instancesCount);
  22561. engine.unbindInstanceAttributes();
  22562. return this;
  22563. };
  22564. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  22565. var scene = this.getScene();
  22566. var engine = scene.getEngine();
  22567. if (hardwareInstancedRendering) {
  22568. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  22569. }
  22570. else {
  22571. if (batch.renderSelf[subMesh._id]) {
  22572. // Draw
  22573. if (onBeforeDraw) {
  22574. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  22575. }
  22576. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  22577. }
  22578. if (batch.visibleInstances[subMesh._id]) {
  22579. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  22580. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  22581. // World
  22582. var world = instance.getWorldMatrix();
  22583. if (onBeforeDraw) {
  22584. onBeforeDraw(true, world, effectiveMaterial);
  22585. }
  22586. // Draw
  22587. this._draw(subMesh, fillMode);
  22588. }
  22589. }
  22590. }
  22591. return this;
  22592. };
  22593. /**
  22594. * Triggers the draw call for the mesh.
  22595. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  22596. * Returns the Mesh.
  22597. */
  22598. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  22599. this.checkOcclusionQuery();
  22600. if (this._isOccluded) {
  22601. return this;
  22602. }
  22603. var scene = this.getScene();
  22604. // Managing instances
  22605. var batch = this._getInstancesRenderList(subMesh._id);
  22606. if (batch.mustReturn) {
  22607. return this;
  22608. }
  22609. // Checking geometry state
  22610. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22611. return this;
  22612. }
  22613. this.onBeforeRenderObservable.notifyObservers(this);
  22614. var engine = scene.getEngine();
  22615. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  22616. // Material
  22617. this._effectiveMaterial = subMesh.getMaterial();
  22618. if (!this._effectiveMaterial) {
  22619. return this;
  22620. }
  22621. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22622. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  22623. return this;
  22624. }
  22625. }
  22626. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  22627. return this;
  22628. }
  22629. // Alpha mode
  22630. if (enableAlphaMode) {
  22631. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  22632. }
  22633. // Outline - step 1
  22634. var savedDepthWrite = engine.getDepthWrite();
  22635. if (this.renderOutline) {
  22636. engine.setDepthWrite(false);
  22637. scene.getOutlineRenderer().render(subMesh, batch);
  22638. engine.setDepthWrite(savedDepthWrite);
  22639. }
  22640. var effect;
  22641. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22642. effect = subMesh.effect;
  22643. }
  22644. else {
  22645. effect = this._effectiveMaterial.getEffect();
  22646. }
  22647. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  22648. if (this._effectiveMaterial.forceDepthWrite) {
  22649. engine.setDepthWrite(true);
  22650. }
  22651. // Bind
  22652. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  22653. if (!hardwareInstancedRendering) {
  22654. this._bind(subMesh, effect, fillMode);
  22655. }
  22656. var world = this.getWorldMatrix();
  22657. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22658. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  22659. }
  22660. else {
  22661. this._effectiveMaterial.bind(world, this);
  22662. }
  22663. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  22664. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  22665. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  22666. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  22667. }
  22668. // Draw
  22669. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  22670. // Unbind
  22671. this._effectiveMaterial.unbind();
  22672. // Outline - step 2
  22673. if (this.renderOutline && savedDepthWrite) {
  22674. engine.setDepthWrite(true);
  22675. engine.setColorWrite(false);
  22676. scene.getOutlineRenderer().render(subMesh, batch);
  22677. engine.setColorWrite(true);
  22678. }
  22679. // Overlay
  22680. if (this.renderOverlay) {
  22681. var currentMode = engine.getAlphaMode();
  22682. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22683. scene.getOutlineRenderer().render(subMesh, batch, true);
  22684. engine.setAlphaMode(currentMode);
  22685. }
  22686. this.onAfterRenderObservable.notifyObservers(this);
  22687. return this;
  22688. };
  22689. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  22690. if (isInstance) {
  22691. effectiveMaterial.bindOnlyWorldMatrix(world);
  22692. }
  22693. return this;
  22694. };
  22695. /**
  22696. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  22697. */
  22698. Mesh.prototype.getEmittedParticleSystems = function () {
  22699. var results = new Array();
  22700. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22701. var particleSystem = this.getScene().particleSystems[index];
  22702. if (particleSystem.emitter === this) {
  22703. results.push(particleSystem);
  22704. }
  22705. }
  22706. return results;
  22707. };
  22708. /**
  22709. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  22710. */
  22711. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  22712. var results = new Array();
  22713. var descendants = this.getDescendants();
  22714. descendants.push(this);
  22715. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22716. var particleSystem = this.getScene().particleSystems[index];
  22717. var emitter = particleSystem.emitter;
  22718. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  22719. results.push(particleSystem);
  22720. }
  22721. }
  22722. return results;
  22723. };
  22724. Mesh.prototype._checkDelayState = function () {
  22725. var scene = this.getScene();
  22726. if (this._geometry) {
  22727. this._geometry.load(scene);
  22728. }
  22729. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22730. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22731. this._queueLoad(this, scene);
  22732. }
  22733. return this;
  22734. };
  22735. Mesh.prototype._queueLoad = function (mesh, scene) {
  22736. var _this = this;
  22737. scene._addPendingData(mesh);
  22738. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  22739. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22740. if (data instanceof ArrayBuffer) {
  22741. _this._delayLoadingFunction(data, _this);
  22742. }
  22743. else {
  22744. _this._delayLoadingFunction(JSON.parse(data), _this);
  22745. }
  22746. _this.instances.forEach(function (instance) {
  22747. instance._syncSubMeshes();
  22748. });
  22749. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22750. scene._removePendingData(_this);
  22751. }, function () { }, scene.database, getBinaryData);
  22752. return this;
  22753. };
  22754. /**
  22755. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  22756. */
  22757. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  22758. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22759. return false;
  22760. }
  22761. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  22762. return false;
  22763. }
  22764. this._checkDelayState();
  22765. return true;
  22766. };
  22767. /**
  22768. * Sets the mesh material by the material or multiMaterial `id` property.
  22769. * The material `id` is a string identifying the material or the multiMaterial.
  22770. * This method returns the Mesh.
  22771. */
  22772. Mesh.prototype.setMaterialByID = function (id) {
  22773. var materials = this.getScene().materials;
  22774. var index;
  22775. for (index = materials.length - 1; index > -1; index--) {
  22776. if (materials[index].id === id) {
  22777. this.material = materials[index];
  22778. return this;
  22779. }
  22780. }
  22781. // Multi
  22782. var multiMaterials = this.getScene().multiMaterials;
  22783. for (index = multiMaterials.length - 1; index > -1; index--) {
  22784. if (multiMaterials[index].id === id) {
  22785. this.material = multiMaterials[index];
  22786. return this;
  22787. }
  22788. }
  22789. return this;
  22790. };
  22791. /**
  22792. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  22793. */
  22794. Mesh.prototype.getAnimatables = function () {
  22795. var results = new Array();
  22796. if (this.material) {
  22797. results.push(this.material);
  22798. }
  22799. if (this.skeleton) {
  22800. results.push(this.skeleton);
  22801. }
  22802. return results;
  22803. };
  22804. /**
  22805. * Modifies the mesh geometry according to the passed transformation matrix.
  22806. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  22807. * The mesh normals are modified accordingly the same transformation.
  22808. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22809. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22810. * Returns the Mesh.
  22811. */
  22812. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  22813. // Position
  22814. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22815. return this;
  22816. }
  22817. var submeshes = this.subMeshes.splice(0);
  22818. this._resetPointsArrayCache();
  22819. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22820. var temp = new Array();
  22821. var index;
  22822. for (index = 0; index < data.length; index += 3) {
  22823. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  22824. }
  22825. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  22826. // Normals
  22827. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22828. return this;
  22829. }
  22830. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22831. temp = [];
  22832. for (index = 0; index < data.length; index += 3) {
  22833. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  22834. }
  22835. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  22836. // flip faces?
  22837. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  22838. this.flipFaces();
  22839. }
  22840. // Restore submeshes
  22841. this.releaseSubMeshes();
  22842. this.subMeshes = submeshes;
  22843. return this;
  22844. };
  22845. /**
  22846. * Modifies the mesh geometry according to its own current World Matrix.
  22847. * The mesh World Matrix is then reset.
  22848. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  22849. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22850. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22851. * Returns the Mesh.
  22852. */
  22853. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  22854. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  22855. this.scaling.copyFromFloats(1, 1, 1);
  22856. this.position.copyFromFloats(0, 0, 0);
  22857. this.rotation.copyFromFloats(0, 0, 0);
  22858. //only if quaternion is already set
  22859. if (this.rotationQuaternion) {
  22860. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  22861. }
  22862. this._worldMatrix = BABYLON.Matrix.Identity();
  22863. return this;
  22864. };
  22865. Object.defineProperty(Mesh.prototype, "_positions", {
  22866. // Cache
  22867. get: function () {
  22868. if (this._geometry) {
  22869. return this._geometry._positions;
  22870. }
  22871. return null;
  22872. },
  22873. enumerable: true,
  22874. configurable: true
  22875. });
  22876. Mesh.prototype._resetPointsArrayCache = function () {
  22877. if (this._geometry) {
  22878. this._geometry._resetPointsArrayCache();
  22879. }
  22880. return this;
  22881. };
  22882. Mesh.prototype._generatePointsArray = function () {
  22883. if (this._geometry) {
  22884. return this._geometry._generatePointsArray();
  22885. }
  22886. return false;
  22887. };
  22888. /**
  22889. * Returns a new Mesh object generated from the current mesh properties.
  22890. * This method must not get confused with createInstance().
  22891. * The parameter `name` is a string, the name given to the new mesh.
  22892. * The optional parameter `newParent` can be any Node object (default `null`).
  22893. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  22894. * 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.
  22895. */
  22896. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  22897. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22898. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  22899. };
  22900. /**
  22901. * Disposes the mesh.
  22902. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  22903. */
  22904. Mesh.prototype.dispose = function (doNotRecurse) {
  22905. var _this = this;
  22906. this.morphTargetManager = undefined;
  22907. if (this._geometry) {
  22908. this._geometry.releaseForMesh(this, true);
  22909. }
  22910. // Sources
  22911. var meshes = this.getScene().meshes;
  22912. meshes.forEach(function (mesh) {
  22913. if (mesh._source && mesh._source === _this) {
  22914. mesh._source = null;
  22915. }
  22916. });
  22917. this._source = null;
  22918. // Instances
  22919. if (this._instancesBuffer) {
  22920. this._instancesBuffer.dispose();
  22921. this._instancesBuffer = null;
  22922. }
  22923. while (this.instances.length) {
  22924. this.instances[0].dispose();
  22925. }
  22926. // Highlight layers.
  22927. var highlightLayers = this.getScene().highlightLayers;
  22928. for (var i = 0; i < highlightLayers.length; i++) {
  22929. var highlightLayer = highlightLayers[i];
  22930. if (highlightLayer) {
  22931. highlightLayer.removeMesh(this);
  22932. highlightLayer.removeExcludedMesh(this);
  22933. }
  22934. }
  22935. _super.prototype.dispose.call(this, doNotRecurse);
  22936. };
  22937. /**
  22938. * Modifies the mesh geometry according to a displacement map.
  22939. * 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.
  22940. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22941. * This method returns nothing.
  22942. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  22943. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22944. * 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.
  22945. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22946. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22947. *
  22948. * Returns the Mesh.
  22949. */
  22950. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  22951. var _this = this;
  22952. var scene = this.getScene();
  22953. var onload = function (img) {
  22954. // Getting height map data
  22955. var canvas = document.createElement("canvas");
  22956. var context = canvas.getContext("2d");
  22957. var heightMapWidth = img.width;
  22958. var heightMapHeight = img.height;
  22959. canvas.width = heightMapWidth;
  22960. canvas.height = heightMapHeight;
  22961. context.drawImage(img, 0, 0);
  22962. // Create VertexData from map data
  22963. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22964. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  22965. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  22966. //execute success callback, if set
  22967. if (onSuccess) {
  22968. onSuccess(_this);
  22969. }
  22970. };
  22971. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22972. return this;
  22973. };
  22974. /**
  22975. * Modifies the mesh geometry according to a displacementMap buffer.
  22976. * 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.
  22977. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22978. * This method returns nothing.
  22979. * 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.
  22980. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  22981. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22982. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22983. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22984. *
  22985. * Returns the Mesh.
  22986. */
  22987. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  22988. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  22989. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  22990. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22991. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  22992. return this;
  22993. }
  22994. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22995. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22996. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22997. var position = BABYLON.Vector3.Zero();
  22998. var normal = BABYLON.Vector3.Zero();
  22999. var uv = BABYLON.Vector2.Zero();
  23000. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  23001. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  23002. for (var index = 0; index < positions.length; index += 3) {
  23003. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  23004. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  23005. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  23006. // Compute height
  23007. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  23008. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  23009. var pos = (u + v * heightMapWidth) * 4;
  23010. var r = buffer[pos] / 255.0;
  23011. var g = buffer[pos + 1] / 255.0;
  23012. var b = buffer[pos + 2] / 255.0;
  23013. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23014. normal.normalize();
  23015. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  23016. position = position.add(normal);
  23017. position.toArray(positions, index);
  23018. }
  23019. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  23020. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  23021. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  23022. return this;
  23023. };
  23024. /**
  23025. * Modify the mesh to get a flat shading rendering.
  23026. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  23027. * This method returns the Mesh.
  23028. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  23029. */
  23030. Mesh.prototype.convertToFlatShadedMesh = function () {
  23031. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  23032. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23033. var kinds = this.getVerticesDataKinds();
  23034. var vbs = {};
  23035. var data = {};
  23036. var newdata = {};
  23037. var updatableNormals = false;
  23038. var kindIndex;
  23039. var kind;
  23040. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23041. kind = kinds[kindIndex];
  23042. var vertexBuffer = this.getVertexBuffer(kind);
  23043. if (kind === BABYLON.VertexBuffer.NormalKind) {
  23044. updatableNormals = vertexBuffer.isUpdatable();
  23045. kinds.splice(kindIndex, 1);
  23046. kindIndex--;
  23047. continue;
  23048. }
  23049. vbs[kind] = vertexBuffer;
  23050. data[kind] = vbs[kind].getData();
  23051. newdata[kind] = [];
  23052. }
  23053. // Save previous submeshes
  23054. var previousSubmeshes = this.subMeshes.slice(0);
  23055. var indices = this.getIndices();
  23056. var totalIndices = this.getTotalIndices();
  23057. // Generating unique vertices per face
  23058. var index;
  23059. for (index = 0; index < totalIndices; index++) {
  23060. var vertexIndex = indices[index];
  23061. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23062. kind = kinds[kindIndex];
  23063. var stride = vbs[kind].getStrideSize();
  23064. for (var offset = 0; offset < stride; offset++) {
  23065. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23066. }
  23067. }
  23068. }
  23069. // Updating faces & normal
  23070. var normals = [];
  23071. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  23072. for (index = 0; index < totalIndices; index += 3) {
  23073. indices[index] = index;
  23074. indices[index + 1] = index + 1;
  23075. indices[index + 2] = index + 2;
  23076. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  23077. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  23078. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  23079. var p1p2 = p1.subtract(p2);
  23080. var p3p2 = p3.subtract(p2);
  23081. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  23082. // Store same normals for every vertex
  23083. for (var localIndex = 0; localIndex < 3; localIndex++) {
  23084. normals.push(normal.x);
  23085. normals.push(normal.y);
  23086. normals.push(normal.z);
  23087. }
  23088. }
  23089. this.setIndices(indices);
  23090. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  23091. // Updating vertex buffers
  23092. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23093. kind = kinds[kindIndex];
  23094. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23095. }
  23096. // Updating submeshes
  23097. this.releaseSubMeshes();
  23098. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23099. var previousOne = previousSubmeshes[submeshIndex];
  23100. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23101. }
  23102. this.synchronizeInstances();
  23103. return this;
  23104. };
  23105. /**
  23106. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  23107. * In other words, more vertices, no more indices and a single bigger VBO.
  23108. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  23109. * Returns the Mesh.
  23110. */
  23111. Mesh.prototype.convertToUnIndexedMesh = function () {
  23112. /// <summary>Remove indices by unfolding faces into buffers</summary>
  23113. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23114. var kinds = this.getVerticesDataKinds();
  23115. var vbs = {};
  23116. var data = {};
  23117. var newdata = {};
  23118. var kindIndex;
  23119. var kind;
  23120. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23121. kind = kinds[kindIndex];
  23122. var vertexBuffer = this.getVertexBuffer(kind);
  23123. vbs[kind] = vertexBuffer;
  23124. data[kind] = vbs[kind].getData();
  23125. newdata[kind] = [];
  23126. }
  23127. // Save previous submeshes
  23128. var previousSubmeshes = this.subMeshes.slice(0);
  23129. var indices = this.getIndices();
  23130. var totalIndices = this.getTotalIndices();
  23131. // Generating unique vertices per face
  23132. var index;
  23133. for (index = 0; index < totalIndices; index++) {
  23134. var vertexIndex = indices[index];
  23135. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23136. kind = kinds[kindIndex];
  23137. var stride = vbs[kind].getStrideSize();
  23138. for (var offset = 0; offset < stride; offset++) {
  23139. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23140. }
  23141. }
  23142. }
  23143. // Updating indices
  23144. for (index = 0; index < totalIndices; index += 3) {
  23145. indices[index] = index;
  23146. indices[index + 1] = index + 1;
  23147. indices[index + 2] = index + 2;
  23148. }
  23149. this.setIndices(indices);
  23150. // Updating vertex buffers
  23151. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23152. kind = kinds[kindIndex];
  23153. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23154. }
  23155. // Updating submeshes
  23156. this.releaseSubMeshes();
  23157. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23158. var previousOne = previousSubmeshes[submeshIndex];
  23159. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23160. }
  23161. this._unIndexed = true;
  23162. this.synchronizeInstances();
  23163. return this;
  23164. };
  23165. /**
  23166. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  23167. * This method returns the Mesh.
  23168. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  23169. */
  23170. Mesh.prototype.flipFaces = function (flipNormals) {
  23171. if (flipNormals === void 0) { flipNormals = false; }
  23172. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  23173. var i;
  23174. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23175. for (i = 0; i < vertex_data.normals.length; i++) {
  23176. vertex_data.normals[i] *= -1;
  23177. }
  23178. }
  23179. var temp;
  23180. for (i = 0; i < vertex_data.indices.length; i += 3) {
  23181. // reassign indices
  23182. temp = vertex_data.indices[i + 1];
  23183. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  23184. vertex_data.indices[i + 2] = temp;
  23185. }
  23186. vertex_data.applyToMesh(this);
  23187. return this;
  23188. };
  23189. // Instances
  23190. /**
  23191. * Creates a new InstancedMesh object from the mesh model.
  23192. * An instance shares the same properties and the same material than its model.
  23193. * Only these properties of each instance can then be set individually :
  23194. * - position
  23195. * - rotation
  23196. * - rotationQuaternion
  23197. * - setPivotMatrix
  23198. * - scaling
  23199. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  23200. * Warning : this method is not supported for Line mesh and LineSystem
  23201. */
  23202. Mesh.prototype.createInstance = function (name) {
  23203. return new BABYLON.InstancedMesh(name, this);
  23204. };
  23205. /**
  23206. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  23207. * After this call, all the mesh instances have the same submeshes than the current mesh.
  23208. * This method returns the Mesh.
  23209. */
  23210. Mesh.prototype.synchronizeInstances = function () {
  23211. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  23212. var instance = this.instances[instanceIndex];
  23213. instance._syncSubMeshes();
  23214. }
  23215. return this;
  23216. };
  23217. /**
  23218. * Simplify the mesh according to the given array of settings.
  23219. * Function will return immediately and will simplify async. It returns the Mesh.
  23220. * @param settings a collection of simplification settings.
  23221. * @param parallelProcessing should all levels calculate parallel or one after the other.
  23222. * @param type the type of simplification to run.
  23223. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  23224. */
  23225. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  23226. if (parallelProcessing === void 0) { parallelProcessing = true; }
  23227. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  23228. this.getScene().simplificationQueue.addTask({
  23229. settings: settings,
  23230. parallelProcessing: parallelProcessing,
  23231. mesh: this,
  23232. simplificationType: simplificationType,
  23233. successCallback: successCallback
  23234. });
  23235. return this;
  23236. };
  23237. /**
  23238. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  23239. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  23240. * This should be used together with the simplification to avoid disappearing triangles.
  23241. * Returns the Mesh.
  23242. * @param successCallback an optional success callback to be called after the optimization finished.
  23243. */
  23244. Mesh.prototype.optimizeIndices = function (successCallback) {
  23245. var _this = this;
  23246. var indices = this.getIndices();
  23247. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23248. var vectorPositions = new Array();
  23249. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  23250. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  23251. }
  23252. var dupes = new Array();
  23253. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  23254. var realPos = vectorPositions.length - 1 - iteration;
  23255. var testedPosition = vectorPositions[realPos];
  23256. for (var j = 0; j < realPos; ++j) {
  23257. var againstPosition = vectorPositions[j];
  23258. if (testedPosition.equals(againstPosition)) {
  23259. dupes[realPos] = j;
  23260. break;
  23261. }
  23262. }
  23263. }, function () {
  23264. for (var i = 0; i < indices.length; ++i) {
  23265. indices[i] = dupes[indices[i]] || indices[i];
  23266. }
  23267. //indices are now reordered
  23268. var originalSubMeshes = _this.subMeshes.slice(0);
  23269. _this.setIndices(indices);
  23270. _this.subMeshes = originalSubMeshes;
  23271. if (successCallback) {
  23272. successCallback(_this);
  23273. }
  23274. });
  23275. return this;
  23276. };
  23277. Mesh.prototype.serialize = function (serializationObject) {
  23278. serializationObject.name = this.name;
  23279. serializationObject.id = this.id;
  23280. serializationObject.type = this.getClassName();
  23281. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  23282. serializationObject.tags = BABYLON.Tags.GetTags(this);
  23283. }
  23284. serializationObject.position = this.position.asArray();
  23285. if (this.rotationQuaternion) {
  23286. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  23287. }
  23288. else if (this.rotation) {
  23289. serializationObject.rotation = this.rotation.asArray();
  23290. }
  23291. serializationObject.scaling = this.scaling.asArray();
  23292. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  23293. serializationObject.isEnabled = this.isEnabled();
  23294. serializationObject.isVisible = this.isVisible;
  23295. serializationObject.infiniteDistance = this.infiniteDistance;
  23296. serializationObject.pickable = this.isPickable;
  23297. serializationObject.receiveShadows = this.receiveShadows;
  23298. serializationObject.billboardMode = this.billboardMode;
  23299. serializationObject.visibility = this.visibility;
  23300. serializationObject.checkCollisions = this.checkCollisions;
  23301. serializationObject.isBlocker = this.isBlocker;
  23302. // Parent
  23303. if (this.parent) {
  23304. serializationObject.parentId = this.parent.id;
  23305. }
  23306. // Geometry
  23307. var geometry = this._geometry;
  23308. if (geometry) {
  23309. var geometryId = geometry.id;
  23310. serializationObject.geometryId = geometryId;
  23311. // SubMeshes
  23312. serializationObject.subMeshes = [];
  23313. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  23314. var subMesh = this.subMeshes[subIndex];
  23315. serializationObject.subMeshes.push({
  23316. materialIndex: subMesh.materialIndex,
  23317. verticesStart: subMesh.verticesStart,
  23318. verticesCount: subMesh.verticesCount,
  23319. indexStart: subMesh.indexStart,
  23320. indexCount: subMesh.indexCount
  23321. });
  23322. }
  23323. }
  23324. // Material
  23325. if (this.material) {
  23326. serializationObject.materialId = this.material.id;
  23327. }
  23328. else {
  23329. this.material = null;
  23330. }
  23331. // Morph targets
  23332. if (this.morphTargetManager) {
  23333. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  23334. }
  23335. // Skeleton
  23336. if (this.skeleton) {
  23337. serializationObject.skeletonId = this.skeleton.id;
  23338. }
  23339. // Physics
  23340. //TODO implement correct serialization for physics impostors.
  23341. if (this.getPhysicsImpostor()) {
  23342. var impostor = this.getPhysicsImpostor();
  23343. serializationObject.physicsMass = impostor.getParam("mass");
  23344. serializationObject.physicsFriction = impostor.getParam("friction");
  23345. serializationObject.physicsRestitution = impostor.getParam("mass");
  23346. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  23347. }
  23348. // Metadata
  23349. if (this.metadata) {
  23350. serializationObject.metadata = this.metadata;
  23351. }
  23352. // Instances
  23353. serializationObject.instances = [];
  23354. for (var index = 0; index < this.instances.length; index++) {
  23355. var instance = this.instances[index];
  23356. var serializationInstance = {
  23357. name: instance.name,
  23358. position: instance.position.asArray(),
  23359. scaling: instance.scaling.asArray()
  23360. };
  23361. if (instance.rotationQuaternion) {
  23362. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  23363. }
  23364. else if (instance.rotation) {
  23365. serializationInstance.rotation = instance.rotation.asArray();
  23366. }
  23367. serializationObject.instances.push(serializationInstance);
  23368. // Animations
  23369. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  23370. serializationInstance.ranges = instance.serializeAnimationRanges();
  23371. }
  23372. //
  23373. // Animations
  23374. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23375. serializationObject.ranges = this.serializeAnimationRanges();
  23376. // Layer mask
  23377. serializationObject.layerMask = this.layerMask;
  23378. // Alpha
  23379. serializationObject.alphaIndex = this.alphaIndex;
  23380. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  23381. // Overlay
  23382. serializationObject.overlayAlpha = this.overlayAlpha;
  23383. serializationObject.overlayColor = this.overlayColor.asArray();
  23384. serializationObject.renderOverlay = this.renderOverlay;
  23385. // Fog
  23386. serializationObject.applyFog = this.applyFog;
  23387. // Action Manager
  23388. if (this.actionManager) {
  23389. serializationObject.actions = this.actionManager.serialize(this.name);
  23390. }
  23391. };
  23392. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  23393. if (!this.geometry) {
  23394. return;
  23395. }
  23396. this._markSubMeshesAsAttributesDirty();
  23397. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  23398. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  23399. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  23400. this.morphTargetManager = undefined;
  23401. return;
  23402. }
  23403. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  23404. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  23405. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  23406. if (morphTarget.hasNormals) {
  23407. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  23408. }
  23409. if (morphTarget.hasTangents) {
  23410. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  23411. }
  23412. }
  23413. }
  23414. else {
  23415. var index = 0;
  23416. // Positions
  23417. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  23418. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  23419. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  23420. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  23421. }
  23422. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  23423. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  23424. }
  23425. index++;
  23426. }
  23427. }
  23428. };
  23429. // Statics
  23430. /**
  23431. * Returns a new Mesh object what is a deep copy of the passed mesh.
  23432. * The parameter `parsedMesh` is the mesh to be copied.
  23433. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  23434. */
  23435. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  23436. var mesh;
  23437. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  23438. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  23439. }
  23440. else {
  23441. mesh = new Mesh(parsedMesh.name, scene);
  23442. }
  23443. mesh.id = parsedMesh.id;
  23444. if (BABYLON.Tags) {
  23445. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  23446. }
  23447. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  23448. if (parsedMesh.metadata !== undefined) {
  23449. mesh.metadata = parsedMesh.metadata;
  23450. }
  23451. if (parsedMesh.rotationQuaternion) {
  23452. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  23453. }
  23454. else if (parsedMesh.rotation) {
  23455. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  23456. }
  23457. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  23458. if (parsedMesh.localMatrix) {
  23459. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  23460. }
  23461. else if (parsedMesh.pivotMatrix) {
  23462. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  23463. }
  23464. mesh.setEnabled(parsedMesh.isEnabled);
  23465. mesh.isVisible = parsedMesh.isVisible;
  23466. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  23467. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  23468. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  23469. if (parsedMesh.applyFog !== undefined) {
  23470. mesh.applyFog = parsedMesh.applyFog;
  23471. }
  23472. if (parsedMesh.pickable !== undefined) {
  23473. mesh.isPickable = parsedMesh.pickable;
  23474. }
  23475. if (parsedMesh.alphaIndex !== undefined) {
  23476. mesh.alphaIndex = parsedMesh.alphaIndex;
  23477. }
  23478. mesh.receiveShadows = parsedMesh.receiveShadows;
  23479. mesh.billboardMode = parsedMesh.billboardMode;
  23480. if (parsedMesh.visibility !== undefined) {
  23481. mesh.visibility = parsedMesh.visibility;
  23482. }
  23483. mesh.checkCollisions = parsedMesh.checkCollisions;
  23484. if (parsedMesh.isBlocker !== undefined) {
  23485. mesh.isBlocker = parsedMesh.isBlocker;
  23486. }
  23487. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  23488. // freezeWorldMatrix
  23489. if (parsedMesh.freezeWorldMatrix) {
  23490. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  23491. }
  23492. // Parent
  23493. if (parsedMesh.parentId) {
  23494. mesh._waitingParentId = parsedMesh.parentId;
  23495. }
  23496. // Actions
  23497. if (parsedMesh.actions !== undefined) {
  23498. mesh._waitingActions = parsedMesh.actions;
  23499. }
  23500. // Overlay
  23501. if (parsedMesh.overlayAlpha !== undefined) {
  23502. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  23503. }
  23504. if (parsedMesh.overlayColor !== undefined) {
  23505. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  23506. }
  23507. if (parsedMesh.renderOverlay !== undefined) {
  23508. mesh.renderOverlay = parsedMesh.renderOverlay;
  23509. }
  23510. // Geometry
  23511. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  23512. if (parsedMesh.delayLoadingFile) {
  23513. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23514. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  23515. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  23516. if (parsedMesh._binaryInfo) {
  23517. mesh._binaryInfo = parsedMesh._binaryInfo;
  23518. }
  23519. mesh._delayInfo = [];
  23520. if (parsedMesh.hasUVs) {
  23521. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  23522. }
  23523. if (parsedMesh.hasUVs2) {
  23524. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  23525. }
  23526. if (parsedMesh.hasUVs3) {
  23527. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  23528. }
  23529. if (parsedMesh.hasUVs4) {
  23530. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  23531. }
  23532. if (parsedMesh.hasUVs5) {
  23533. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  23534. }
  23535. if (parsedMesh.hasUVs6) {
  23536. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  23537. }
  23538. if (parsedMesh.hasColors) {
  23539. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  23540. }
  23541. if (parsedMesh.hasMatricesIndices) {
  23542. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23543. }
  23544. if (parsedMesh.hasMatricesWeights) {
  23545. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23546. }
  23547. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  23548. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  23549. mesh._checkDelayState();
  23550. }
  23551. }
  23552. else {
  23553. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  23554. }
  23555. // Material
  23556. if (parsedMesh.materialId) {
  23557. mesh.setMaterialByID(parsedMesh.materialId);
  23558. }
  23559. else {
  23560. mesh.material = null;
  23561. }
  23562. // Morph targets
  23563. if (parsedMesh.morphTargetManagerId > -1) {
  23564. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  23565. }
  23566. // Skeleton
  23567. if (parsedMesh.skeletonId > -1) {
  23568. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  23569. if (parsedMesh.numBoneInfluencers) {
  23570. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  23571. }
  23572. }
  23573. // Animations
  23574. if (parsedMesh.animations) {
  23575. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23576. var parsedAnimation = parsedMesh.animations[animationIndex];
  23577. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23578. }
  23579. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  23580. }
  23581. if (parsedMesh.autoAnimate) {
  23582. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  23583. }
  23584. // Layer Mask
  23585. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  23586. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  23587. }
  23588. else {
  23589. mesh.layerMask = 0x0FFFFFFF;
  23590. }
  23591. // Physics
  23592. if (parsedMesh.physicsImpostor) {
  23593. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  23594. mass: parsedMesh.physicsMass,
  23595. friction: parsedMesh.physicsFriction,
  23596. restitution: parsedMesh.physicsRestitution
  23597. }, scene);
  23598. }
  23599. // Instances
  23600. if (parsedMesh.instances) {
  23601. for (var index = 0; index < parsedMesh.instances.length; index++) {
  23602. var parsedInstance = parsedMesh.instances[index];
  23603. var instance = mesh.createInstance(parsedInstance.name);
  23604. if (BABYLON.Tags) {
  23605. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  23606. }
  23607. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  23608. if (parsedInstance.parentId) {
  23609. instance._waitingParentId = parsedInstance.parentId;
  23610. }
  23611. if (parsedInstance.rotationQuaternion) {
  23612. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  23613. }
  23614. else if (parsedInstance.rotation) {
  23615. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  23616. }
  23617. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  23618. instance.checkCollisions = mesh.checkCollisions;
  23619. if (parsedMesh.animations) {
  23620. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23621. parsedAnimation = parsedMesh.animations[animationIndex];
  23622. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23623. }
  23624. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  23625. }
  23626. }
  23627. }
  23628. return mesh;
  23629. };
  23630. /**
  23631. * Creates a ribbon mesh.
  23632. * Please consider using the same method from the MeshBuilder class instead.
  23633. * 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.
  23634. *
  23635. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  23636. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  23637. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  23638. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  23639. * 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.
  23640. * 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.
  23641. * 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
  23642. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23643. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23644. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23645. */
  23646. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  23647. return BABYLON.MeshBuilder.CreateRibbon(name, {
  23648. pathArray: pathArray,
  23649. closeArray: closeArray,
  23650. closePath: closePath,
  23651. offset: offset,
  23652. updatable: updatable,
  23653. sideOrientation: sideOrientation,
  23654. instance: instance
  23655. }, scene);
  23656. };
  23657. /**
  23658. * Creates a plane polygonal mesh. By default, this is a disc.
  23659. * Please consider using the same method from the MeshBuilder class instead.
  23660. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  23661. * 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.
  23662. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23663. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23664. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23665. */
  23666. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  23667. var options = {
  23668. radius: radius,
  23669. tessellation: tessellation,
  23670. sideOrientation: sideOrientation,
  23671. updatable: updatable
  23672. };
  23673. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  23674. };
  23675. /**
  23676. * Creates a box mesh.
  23677. * Please consider using the same method from the MeshBuilder class instead.
  23678. * The parameter `size` sets the size (float) of each box side (default 1).
  23679. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23680. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23681. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23682. */
  23683. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  23684. var options = {
  23685. size: size,
  23686. sideOrientation: sideOrientation,
  23687. updatable: updatable
  23688. };
  23689. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  23690. };
  23691. /**
  23692. * Creates a sphere mesh.
  23693. * Please consider using the same method from the MeshBuilder class instead.
  23694. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  23695. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  23696. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23697. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23698. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23699. */
  23700. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  23701. var options = {
  23702. segments: segments,
  23703. diameterX: diameter,
  23704. diameterY: diameter,
  23705. diameterZ: diameter,
  23706. sideOrientation: sideOrientation,
  23707. updatable: updatable
  23708. };
  23709. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  23710. };
  23711. /**
  23712. * Creates a cylinder or a cone mesh.
  23713. * Please consider using the same method from the MeshBuilder class instead.
  23714. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  23715. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  23716. * 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.
  23717. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  23718. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  23719. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23720. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23721. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23722. */
  23723. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  23724. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  23725. if (scene !== undefined) {
  23726. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  23727. updatable = scene;
  23728. }
  23729. scene = subdivisions;
  23730. subdivisions = 1;
  23731. }
  23732. var options = {
  23733. height: height,
  23734. diameterTop: diameterTop,
  23735. diameterBottom: diameterBottom,
  23736. tessellation: tessellation,
  23737. subdivisions: subdivisions,
  23738. sideOrientation: sideOrientation,
  23739. updatable: updatable
  23740. };
  23741. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  23742. };
  23743. // Torus (Code from SharpDX.org)
  23744. /**
  23745. * Creates a torus mesh.
  23746. * Please consider using the same method from the MeshBuilder class instead.
  23747. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  23748. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  23749. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  23750. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23751. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23752. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23753. */
  23754. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  23755. var options = {
  23756. diameter: diameter,
  23757. thickness: thickness,
  23758. tessellation: tessellation,
  23759. sideOrientation: sideOrientation,
  23760. updatable: updatable
  23761. };
  23762. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  23763. };
  23764. /**
  23765. * Creates a torus knot mesh.
  23766. * Please consider using the same method from the MeshBuilder class instead.
  23767. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  23768. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  23769. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  23770. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  23771. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23772. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23773. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23774. */
  23775. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  23776. var options = {
  23777. radius: radius,
  23778. tube: tube,
  23779. radialSegments: radialSegments,
  23780. tubularSegments: tubularSegments,
  23781. p: p,
  23782. q: q,
  23783. sideOrientation: sideOrientation,
  23784. updatable: updatable
  23785. };
  23786. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  23787. };
  23788. /**
  23789. * Creates a line mesh.
  23790. * Please consider using the same method from the MeshBuilder class instead.
  23791. * 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.
  23792. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23793. * The parameter `points` is an array successive Vector3.
  23794. * 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
  23795. * When updating an instance, remember that only point positions can change, not the number of points.
  23796. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23797. */
  23798. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  23799. var options = {
  23800. points: points,
  23801. updatable: updatable,
  23802. instance: instance
  23803. };
  23804. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  23805. };
  23806. /**
  23807. * Creates a dashed line mesh.
  23808. * Please consider using the same method from the MeshBuilder class instead.
  23809. * 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.
  23810. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23811. * The parameter `points` is an array successive Vector3.
  23812. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  23813. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  23814. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  23815. * 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
  23816. * When updating an instance, remember that only point positions can change, not the number of points.
  23817. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23818. */
  23819. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  23820. var options = {
  23821. points: points,
  23822. dashSize: dashSize,
  23823. gapSize: gapSize,
  23824. dashNb: dashNb,
  23825. updatable: updatable,
  23826. instance: instance
  23827. };
  23828. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  23829. };
  23830. /**
  23831. * Creates a polygon mesh.
  23832. * Please consider using the same method from the MeshBuilder class instead.
  23833. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  23834. * 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.
  23835. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23836. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23837. * Remember you can only change the shape positions, not their number when updating a polygon.
  23838. */
  23839. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  23840. var options = {
  23841. shape: shape,
  23842. holes: holes,
  23843. updatable: updatable,
  23844. sideOrientation: sideOrientation
  23845. };
  23846. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  23847. };
  23848. /**
  23849. * Creates an extruded polygon mesh, with depth in the Y direction.
  23850. * Please consider using the same method from the MeshBuilder class instead.
  23851. */
  23852. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  23853. var options = {
  23854. shape: shape,
  23855. holes: holes,
  23856. depth: depth,
  23857. updatable: updatable,
  23858. sideOrientation: sideOrientation
  23859. };
  23860. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  23861. };
  23862. /**
  23863. * Creates an extruded shape mesh.
  23864. * 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.
  23865. * Please consider using the same method from the MeshBuilder class instead.
  23866. *
  23867. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23868. * 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
  23869. * extruded along the Z axis.
  23870. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23871. * 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.
  23872. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23873. * 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
  23874. * 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
  23875. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23876. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23877. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23878. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23879. */
  23880. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  23881. var options = {
  23882. shape: shape,
  23883. path: path,
  23884. scale: scale,
  23885. rotation: rotation,
  23886. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23887. sideOrientation: sideOrientation,
  23888. instance: instance,
  23889. updatable: updatable
  23890. };
  23891. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  23892. };
  23893. /**
  23894. * Creates an custom extruded shape mesh.
  23895. * 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.
  23896. * Please consider using the same method from the MeshBuilder class instead.
  23897. *
  23898. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23899. * 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
  23900. * extruded along the Z axis.
  23901. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23902. * 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
  23903. * and the distance of this point from the begining of the path :
  23904. * ```javascript
  23905. * var rotationFunction = function(i, distance) {
  23906. * // do things
  23907. * return rotationValue; }
  23908. * ```
  23909. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23910. * 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
  23911. * and the distance of this point from the begining of the path :
  23912. * ```javascript
  23913. * var scaleFunction = function(i, distance) {
  23914. * // do things
  23915. * return scaleValue;}
  23916. * ```
  23917. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23918. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23919. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23920. * 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
  23921. * 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
  23922. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23923. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23924. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23925. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23926. */
  23927. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  23928. var options = {
  23929. shape: shape,
  23930. path: path,
  23931. scaleFunction: scaleFunction,
  23932. rotationFunction: rotationFunction,
  23933. ribbonCloseArray: ribbonCloseArray,
  23934. ribbonClosePath: ribbonClosePath,
  23935. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23936. sideOrientation: sideOrientation,
  23937. instance: instance,
  23938. updatable: updatable
  23939. };
  23940. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  23941. };
  23942. /**
  23943. * Creates lathe mesh.
  23944. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23945. * Please consider using the same method from the MeshBuilder class instead.
  23946. * 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
  23947. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23948. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23949. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23950. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23951. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23952. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23953. */
  23954. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  23955. var options = {
  23956. shape: shape,
  23957. radius: radius,
  23958. tessellation: tessellation,
  23959. sideOrientation: sideOrientation,
  23960. updatable: updatable
  23961. };
  23962. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  23963. };
  23964. /**
  23965. * Creates a plane mesh.
  23966. * Please consider using the same method from the MeshBuilder class instead.
  23967. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23968. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23969. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23970. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23971. */
  23972. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  23973. var options = {
  23974. size: size,
  23975. width: size,
  23976. height: size,
  23977. sideOrientation: sideOrientation,
  23978. updatable: updatable
  23979. };
  23980. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  23981. };
  23982. /**
  23983. * Creates a ground mesh.
  23984. * Please consider using the same method from the MeshBuilder class instead.
  23985. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23986. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  23987. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23988. */
  23989. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  23990. var options = {
  23991. width: width,
  23992. height: height,
  23993. subdivisions: subdivisions,
  23994. updatable: updatable
  23995. };
  23996. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  23997. };
  23998. /**
  23999. * Creates a tiled ground mesh.
  24000. * Please consider using the same method from the MeshBuilder class instead.
  24001. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  24002. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  24003. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  24004. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  24005. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  24006. * numbers of subdivisions on the ground width and height of each tile.
  24007. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24008. */
  24009. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  24010. var options = {
  24011. xmin: xmin,
  24012. zmin: zmin,
  24013. xmax: xmax,
  24014. zmax: zmax,
  24015. subdivisions: subdivisions,
  24016. precision: precision,
  24017. updatable: updatable
  24018. };
  24019. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  24020. };
  24021. /**
  24022. * Creates a ground mesh from a height map.
  24023. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  24024. * Please consider using the same method from the MeshBuilder class instead.
  24025. * The parameter `url` sets the URL of the height map image resource.
  24026. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  24027. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  24028. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  24029. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  24030. * 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).
  24031. * This function is passed the newly built mesh :
  24032. * ```javascript
  24033. * function(mesh) { // do things
  24034. * return; }
  24035. * ```
  24036. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24037. */
  24038. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  24039. var options = {
  24040. width: width,
  24041. height: height,
  24042. subdivisions: subdivisions,
  24043. minHeight: minHeight,
  24044. maxHeight: maxHeight,
  24045. updatable: updatable,
  24046. onReady: onReady
  24047. };
  24048. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  24049. };
  24050. /**
  24051. * Creates a tube mesh.
  24052. * 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.
  24053. * Please consider using the same method from the MeshBuilder class instead.
  24054. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  24055. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  24056. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  24057. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  24058. * 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.
  24059. * It must return a radius value (positive float) :
  24060. * ```javascript
  24061. * var radiusFunction = function(i, distance) {
  24062. * // do things
  24063. * return radius; }
  24064. * ```
  24065. * 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
  24066. * 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
  24067. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24068. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24069. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24070. */
  24071. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  24072. var options = {
  24073. path: path,
  24074. radius: radius,
  24075. tessellation: tessellation,
  24076. radiusFunction: radiusFunction,
  24077. arc: 1,
  24078. cap: cap,
  24079. updatable: updatable,
  24080. sideOrientation: sideOrientation,
  24081. instance: instance
  24082. };
  24083. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  24084. };
  24085. /**
  24086. * Creates a polyhedron mesh.
  24087. * Please consider using the same method from the MeshBuilder class instead.
  24088. * 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
  24089. * to choose the wanted type.
  24090. * The parameter `size` (positive float, default 1) sets the polygon size.
  24091. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  24092. * 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`.
  24093. * 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
  24094. * 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)`).
  24095. * 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
  24096. * 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.
  24097. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24098. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24099. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24100. */
  24101. Mesh.CreatePolyhedron = function (name, options, scene) {
  24102. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  24103. };
  24104. /**
  24105. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  24106. * Please consider using the same method from the MeshBuilder class instead.
  24107. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  24108. * 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`).
  24109. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  24110. * 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.
  24111. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24112. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24113. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24114. */
  24115. Mesh.CreateIcoSphere = function (name, options, scene) {
  24116. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  24117. };
  24118. /**
  24119. * Creates a decal mesh.
  24120. * Please consider using the same method from the MeshBuilder class instead.
  24121. * 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.
  24122. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  24123. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  24124. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  24125. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  24126. */
  24127. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  24128. var options = {
  24129. position: position,
  24130. normal: normal,
  24131. size: size,
  24132. angle: angle
  24133. };
  24134. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  24135. };
  24136. // Skeletons
  24137. /**
  24138. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24139. */
  24140. Mesh.prototype.setPositionsForCPUSkinning = function () {
  24141. var source;
  24142. if (!this._sourcePositions) {
  24143. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24144. this._sourcePositions = new Float32Array(source);
  24145. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  24146. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  24147. }
  24148. }
  24149. return this._sourcePositions;
  24150. };
  24151. /**
  24152. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24153. */
  24154. Mesh.prototype.setNormalsForCPUSkinning = function () {
  24155. var source;
  24156. if (!this._sourceNormals) {
  24157. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24158. this._sourceNormals = new Float32Array(source);
  24159. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  24160. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  24161. }
  24162. }
  24163. return this._sourceNormals;
  24164. };
  24165. /**
  24166. * Updates the vertex buffer by applying transformation from the bones.
  24167. * Returns the Mesh.
  24168. *
  24169. * @param {skeleton} skeleton to apply
  24170. */
  24171. Mesh.prototype.applySkeleton = function (skeleton) {
  24172. if (!this.geometry) {
  24173. return this;
  24174. }
  24175. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  24176. return this;
  24177. }
  24178. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  24179. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24180. return this;
  24181. }
  24182. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24183. return this;
  24184. }
  24185. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24186. return this;
  24187. }
  24188. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24189. return this;
  24190. }
  24191. if (!this._sourcePositions) {
  24192. var submeshes = this.subMeshes.slice();
  24193. this.setPositionsForCPUSkinning();
  24194. this.subMeshes = submeshes;
  24195. }
  24196. if (!this._sourceNormals) {
  24197. this.setNormalsForCPUSkinning();
  24198. }
  24199. // positionsData checks for not being Float32Array will only pass at most once
  24200. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24201. if (!(positionsData instanceof Float32Array)) {
  24202. positionsData = new Float32Array(positionsData);
  24203. }
  24204. // normalsData checks for not being Float32Array will only pass at most once
  24205. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24206. if (!(normalsData instanceof Float32Array)) {
  24207. normalsData = new Float32Array(normalsData);
  24208. }
  24209. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24210. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24211. var needExtras = this.numBoneInfluencers > 4;
  24212. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  24213. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  24214. var skeletonMatrices = skeleton.getTransformMatrices(this);
  24215. var tempVector3 = BABYLON.Vector3.Zero();
  24216. var finalMatrix = new BABYLON.Matrix();
  24217. var tempMatrix = new BABYLON.Matrix();
  24218. var matWeightIdx = 0;
  24219. var inf;
  24220. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  24221. var weight;
  24222. for (inf = 0; inf < 4; inf++) {
  24223. weight = matricesWeightsData[matWeightIdx + inf];
  24224. if (weight > 0) {
  24225. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24226. finalMatrix.addToSelf(tempMatrix);
  24227. }
  24228. else
  24229. break;
  24230. }
  24231. if (needExtras) {
  24232. for (inf = 0; inf < 4; inf++) {
  24233. weight = matricesWeightsExtraData[matWeightIdx + inf];
  24234. if (weight > 0) {
  24235. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24236. finalMatrix.addToSelf(tempMatrix);
  24237. }
  24238. else
  24239. break;
  24240. }
  24241. }
  24242. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  24243. tempVector3.toArray(positionsData, index);
  24244. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  24245. tempVector3.toArray(normalsData, index);
  24246. finalMatrix.reset();
  24247. }
  24248. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  24249. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  24250. return this;
  24251. };
  24252. // Tools
  24253. /**
  24254. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  24255. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  24256. */
  24257. Mesh.MinMax = function (meshes) {
  24258. var minVector = null;
  24259. var maxVector = null;
  24260. meshes.forEach(function (mesh, index, array) {
  24261. var boundingBox = mesh.getBoundingInfo().boundingBox;
  24262. if (!minVector) {
  24263. minVector = boundingBox.minimumWorld;
  24264. maxVector = boundingBox.maximumWorld;
  24265. }
  24266. else {
  24267. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  24268. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  24269. }
  24270. });
  24271. return {
  24272. min: minVector,
  24273. max: maxVector
  24274. };
  24275. };
  24276. /**
  24277. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  24278. */
  24279. Mesh.Center = function (meshesOrMinMaxVector) {
  24280. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  24281. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  24282. };
  24283. /**
  24284. * Merge the array of meshes into a single mesh for performance reasons.
  24285. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  24286. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  24287. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  24288. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  24289. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  24290. */
  24291. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  24292. if (disposeSource === void 0) { disposeSource = true; }
  24293. var index;
  24294. if (!allow32BitsIndices) {
  24295. var totalVertices = 0;
  24296. // Counting vertices
  24297. for (index = 0; index < meshes.length; index++) {
  24298. if (meshes[index]) {
  24299. totalVertices += meshes[index].getTotalVertices();
  24300. if (totalVertices > 65536) {
  24301. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  24302. return null;
  24303. }
  24304. }
  24305. }
  24306. }
  24307. // Merge
  24308. var vertexData;
  24309. var otherVertexData;
  24310. var indiceArray = new Array();
  24311. var source;
  24312. for (index = 0; index < meshes.length; index++) {
  24313. if (meshes[index]) {
  24314. meshes[index].computeWorldMatrix(true);
  24315. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  24316. otherVertexData.transform(meshes[index].getWorldMatrix());
  24317. if (vertexData) {
  24318. vertexData.merge(otherVertexData);
  24319. }
  24320. else {
  24321. vertexData = otherVertexData;
  24322. source = meshes[index];
  24323. }
  24324. if (subdivideWithSubMeshes) {
  24325. indiceArray.push(meshes[index].getTotalIndices());
  24326. }
  24327. }
  24328. }
  24329. if (!meshSubclass) {
  24330. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  24331. }
  24332. vertexData.applyToMesh(meshSubclass);
  24333. // Setting properties
  24334. meshSubclass.material = source.material;
  24335. meshSubclass.checkCollisions = source.checkCollisions;
  24336. // Cleaning
  24337. if (disposeSource) {
  24338. for (index = 0; index < meshes.length; index++) {
  24339. if (meshes[index]) {
  24340. meshes[index].dispose();
  24341. }
  24342. }
  24343. }
  24344. // Subdivide
  24345. if (subdivideWithSubMeshes) {
  24346. //-- Suppresions du submesh global
  24347. meshSubclass.releaseSubMeshes();
  24348. index = 0;
  24349. var offset = 0;
  24350. //-- aplique la subdivision en fonction du tableau d'indices
  24351. while (index < indiceArray.length) {
  24352. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  24353. offset += indiceArray[index];
  24354. index++;
  24355. }
  24356. }
  24357. return meshSubclass;
  24358. };
  24359. // Consts
  24360. Mesh._FRONTSIDE = 0;
  24361. Mesh._BACKSIDE = 1;
  24362. Mesh._DOUBLESIDE = 2;
  24363. Mesh._DEFAULTSIDE = 0;
  24364. Mesh._NO_CAP = 0;
  24365. Mesh._CAP_START = 1;
  24366. Mesh._CAP_END = 2;
  24367. Mesh._CAP_ALL = 3;
  24368. return Mesh;
  24369. }(BABYLON.AbstractMesh));
  24370. BABYLON.Mesh = Mesh;
  24371. })(BABYLON || (BABYLON = {}));
  24372. //# sourceMappingURL=babylon.mesh.js.map
  24373. var BABYLON;
  24374. (function (BABYLON) {
  24375. var BaseSubMesh = (function () {
  24376. function BaseSubMesh() {
  24377. }
  24378. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  24379. get: function () {
  24380. return this._materialEffect;
  24381. },
  24382. enumerable: true,
  24383. configurable: true
  24384. });
  24385. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  24386. if (this._materialEffect === effect) {
  24387. if (!effect) {
  24388. this._materialDefines = undefined;
  24389. }
  24390. return;
  24391. }
  24392. this._materialDefines = defines;
  24393. this._materialEffect = effect;
  24394. };
  24395. return BaseSubMesh;
  24396. }());
  24397. BABYLON.BaseSubMesh = BaseSubMesh;
  24398. var SubMesh = (function (_super) {
  24399. __extends(SubMesh, _super);
  24400. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  24401. if (createBoundingBox === void 0) { createBoundingBox = true; }
  24402. var _this = _super.call(this) || this;
  24403. _this.materialIndex = materialIndex;
  24404. _this.verticesStart = verticesStart;
  24405. _this.verticesCount = verticesCount;
  24406. _this.indexStart = indexStart;
  24407. _this.indexCount = indexCount;
  24408. _this._renderId = 0;
  24409. _this._mesh = mesh;
  24410. _this._renderingMesh = renderingMesh || mesh;
  24411. mesh.subMeshes.push(_this);
  24412. _this._trianglePlanes = [];
  24413. _this._id = mesh.subMeshes.length - 1;
  24414. if (createBoundingBox) {
  24415. _this.refreshBoundingInfo();
  24416. mesh.computeWorldMatrix(true);
  24417. }
  24418. return _this;
  24419. }
  24420. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  24421. if (createBoundingBox === void 0) { createBoundingBox = true; }
  24422. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  24423. };
  24424. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  24425. get: function () {
  24426. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  24427. },
  24428. enumerable: true,
  24429. configurable: true
  24430. });
  24431. /**
  24432. * Returns the submesh BoudingInfo object.
  24433. */
  24434. SubMesh.prototype.getBoundingInfo = function () {
  24435. if (this.IsGlobal) {
  24436. return this._mesh.getBoundingInfo();
  24437. }
  24438. return this._boundingInfo;
  24439. };
  24440. /**
  24441. * Sets the submesh BoundingInfo.
  24442. * Return the SubMesh.
  24443. */
  24444. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  24445. this._boundingInfo = boundingInfo;
  24446. return this;
  24447. };
  24448. /**
  24449. * Returns the mesh of the current submesh.
  24450. */
  24451. SubMesh.prototype.getMesh = function () {
  24452. return this._mesh;
  24453. };
  24454. /**
  24455. * Returns the rendering mesh of the submesh.
  24456. */
  24457. SubMesh.prototype.getRenderingMesh = function () {
  24458. return this._renderingMesh;
  24459. };
  24460. /**
  24461. * Returns the submesh material.
  24462. */
  24463. SubMesh.prototype.getMaterial = function () {
  24464. var rootMaterial = this._renderingMesh.material;
  24465. if (rootMaterial && rootMaterial.getSubMaterial) {
  24466. var multiMaterial = rootMaterial;
  24467. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  24468. if (this._currentMaterial !== effectiveMaterial) {
  24469. this._currentMaterial = effectiveMaterial;
  24470. this._materialDefines = undefined;
  24471. }
  24472. return effectiveMaterial;
  24473. }
  24474. if (!rootMaterial) {
  24475. return this._mesh.getScene().defaultMaterial;
  24476. }
  24477. return rootMaterial;
  24478. };
  24479. // Methods
  24480. /**
  24481. * Sets a new updated BoundingInfo object to the submesh.
  24482. * Returns the SubMesh.
  24483. */
  24484. SubMesh.prototype.refreshBoundingInfo = function () {
  24485. this._lastColliderWorldVertices = null;
  24486. if (this.IsGlobal) {
  24487. return this;
  24488. }
  24489. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24490. if (!data) {
  24491. this._boundingInfo = this._mesh._boundingInfo;
  24492. return this;
  24493. }
  24494. var indices = this._renderingMesh.getIndices();
  24495. var extend;
  24496. //is this the only submesh?
  24497. if (this.indexStart === 0 && this.indexCount === indices.length) {
  24498. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  24499. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  24500. }
  24501. else {
  24502. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  24503. }
  24504. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24505. return this;
  24506. };
  24507. SubMesh.prototype._checkCollision = function (collider) {
  24508. return this.getBoundingInfo()._checkCollision(collider);
  24509. };
  24510. /**
  24511. * Updates the submesh BoundingInfo.
  24512. * Returns the Submesh.
  24513. */
  24514. SubMesh.prototype.updateBoundingInfo = function (world) {
  24515. if (!this.getBoundingInfo()) {
  24516. this.refreshBoundingInfo();
  24517. }
  24518. this.getBoundingInfo().update(world);
  24519. return this;
  24520. };
  24521. /**
  24522. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  24523. * Boolean returned.
  24524. */
  24525. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  24526. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  24527. };
  24528. /**
  24529. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  24530. * Boolean returned.
  24531. */
  24532. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  24533. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  24534. };
  24535. /**
  24536. * Renders the submesh.
  24537. * Returns it.
  24538. */
  24539. SubMesh.prototype.render = function (enableAlphaMode) {
  24540. this._renderingMesh.render(this, enableAlphaMode);
  24541. return this;
  24542. };
  24543. /**
  24544. * Returns a new Index Buffer.
  24545. * Type returned : WebGLBuffer.
  24546. */
  24547. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  24548. if (!this._linesIndexBuffer) {
  24549. var linesIndices = [];
  24550. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24551. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  24552. }
  24553. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  24554. this.linesIndexCount = linesIndices.length;
  24555. }
  24556. return this._linesIndexBuffer;
  24557. };
  24558. /**
  24559. * True is the passed Ray intersects the submesh bounding box.
  24560. * Boolean returned.
  24561. */
  24562. SubMesh.prototype.canIntersects = function (ray) {
  24563. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  24564. };
  24565. /**
  24566. * Returns an object IntersectionInfo.
  24567. */
  24568. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  24569. var intersectInfo = null;
  24570. // LineMesh first as it's also a Mesh...
  24571. if (this._mesh instanceof BABYLON.LinesMesh) {
  24572. var lineMesh = this._mesh;
  24573. // Line test
  24574. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  24575. var p0 = positions[indices[index]];
  24576. var p1 = positions[indices[index + 1]];
  24577. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  24578. if (length < 0) {
  24579. continue;
  24580. }
  24581. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  24582. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  24583. if (fastCheck) {
  24584. break;
  24585. }
  24586. }
  24587. }
  24588. }
  24589. else {
  24590. // Triangles test
  24591. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24592. var p0 = positions[indices[index]];
  24593. var p1 = positions[indices[index + 1]];
  24594. var p2 = positions[indices[index + 2]];
  24595. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  24596. if (currentIntersectInfo) {
  24597. if (currentIntersectInfo.distance < 0) {
  24598. continue;
  24599. }
  24600. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  24601. intersectInfo = currentIntersectInfo;
  24602. intersectInfo.faceId = index / 3;
  24603. if (fastCheck) {
  24604. break;
  24605. }
  24606. }
  24607. }
  24608. }
  24609. }
  24610. return intersectInfo;
  24611. };
  24612. SubMesh.prototype._rebuild = function () {
  24613. if (this._linesIndexBuffer) {
  24614. this._linesIndexBuffer = null;
  24615. }
  24616. };
  24617. // Clone
  24618. /**
  24619. * Creates a new Submesh from the passed Mesh.
  24620. */
  24621. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  24622. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  24623. if (!this.IsGlobal) {
  24624. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  24625. }
  24626. return result;
  24627. };
  24628. // Dispose
  24629. /**
  24630. * Disposes the Submesh.
  24631. * Returns nothing.
  24632. */
  24633. SubMesh.prototype.dispose = function () {
  24634. if (this._linesIndexBuffer) {
  24635. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  24636. this._linesIndexBuffer = null;
  24637. }
  24638. // Remove from mesh
  24639. var index = this._mesh.subMeshes.indexOf(this);
  24640. this._mesh.subMeshes.splice(index, 1);
  24641. };
  24642. // Statics
  24643. /**
  24644. * Creates a new Submesh from the passed parameters :
  24645. * - materialIndex (integer) : the index of the main mesh material.
  24646. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  24647. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  24648. * - mesh (Mesh) : the main mesh to create the submesh from.
  24649. * - renderingMesh (optional Mesh) : rendering mesh.
  24650. */
  24651. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  24652. var minVertexIndex = Number.MAX_VALUE;
  24653. var maxVertexIndex = -Number.MAX_VALUE;
  24654. renderingMesh = renderingMesh || mesh;
  24655. var indices = renderingMesh.getIndices();
  24656. for (var index = startIndex; index < startIndex + indexCount; index++) {
  24657. var vertexIndex = indices[index];
  24658. if (vertexIndex < minVertexIndex)
  24659. minVertexIndex = vertexIndex;
  24660. if (vertexIndex > maxVertexIndex)
  24661. maxVertexIndex = vertexIndex;
  24662. }
  24663. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  24664. };
  24665. return SubMesh;
  24666. }(BaseSubMesh));
  24667. BABYLON.SubMesh = SubMesh;
  24668. })(BABYLON || (BABYLON = {}));
  24669. //# sourceMappingURL=babylon.subMesh.js.map
  24670. var BABYLON;
  24671. (function (BABYLON) {
  24672. var EffectFallbacks = (function () {
  24673. function EffectFallbacks() {
  24674. this._defines = {};
  24675. this._currentRank = 32;
  24676. this._maxRank = -1;
  24677. }
  24678. EffectFallbacks.prototype.unBindMesh = function () {
  24679. this._mesh = null;
  24680. };
  24681. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24682. if (!this._defines[rank]) {
  24683. if (rank < this._currentRank) {
  24684. this._currentRank = rank;
  24685. }
  24686. if (rank > this._maxRank) {
  24687. this._maxRank = rank;
  24688. }
  24689. this._defines[rank] = new Array();
  24690. }
  24691. this._defines[rank].push(define);
  24692. };
  24693. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24694. this._meshRank = rank;
  24695. this._mesh = mesh;
  24696. if (rank < this._currentRank) {
  24697. this._currentRank = rank;
  24698. }
  24699. if (rank > this._maxRank) {
  24700. this._maxRank = rank;
  24701. }
  24702. };
  24703. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24704. get: function () {
  24705. return this._currentRank <= this._maxRank;
  24706. },
  24707. enumerable: true,
  24708. configurable: true
  24709. });
  24710. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24711. // First we try to switch to CPU skinning
  24712. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  24713. this._mesh.computeBonesUsingShaders = false;
  24714. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24715. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24716. var scene = this._mesh.getScene();
  24717. for (var index = 0; index < scene.meshes.length; index++) {
  24718. var otherMesh = scene.meshes[index];
  24719. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  24720. otherMesh.computeBonesUsingShaders = false;
  24721. }
  24722. }
  24723. }
  24724. else {
  24725. var currentFallbacks = this._defines[this._currentRank];
  24726. if (currentFallbacks) {
  24727. for (var index = 0; index < currentFallbacks.length; index++) {
  24728. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24729. }
  24730. }
  24731. this._currentRank++;
  24732. }
  24733. return currentDefines;
  24734. };
  24735. return EffectFallbacks;
  24736. }());
  24737. BABYLON.EffectFallbacks = EffectFallbacks;
  24738. var EffectCreationOptions = (function () {
  24739. function EffectCreationOptions() {
  24740. }
  24741. return EffectCreationOptions;
  24742. }());
  24743. BABYLON.EffectCreationOptions = EffectCreationOptions;
  24744. var Effect = (function () {
  24745. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24746. var _this = this;
  24747. this.uniqueId = 0;
  24748. this.onCompileObservable = new BABYLON.Observable();
  24749. this.onErrorObservable = new BABYLON.Observable();
  24750. this.onBindObservable = new BABYLON.Observable();
  24751. this._uniformBuffersNames = {};
  24752. this._isReady = false;
  24753. this._compilationError = "";
  24754. this.name = baseName;
  24755. if (attributesNamesOrOptions.attributes) {
  24756. var options = attributesNamesOrOptions;
  24757. this._engine = uniformsNamesOrEngine;
  24758. this._attributesNames = options.attributes;
  24759. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  24760. this._samplers = options.samplers;
  24761. this.defines = options.defines;
  24762. this.onError = options.onError;
  24763. this.onCompiled = options.onCompiled;
  24764. this._fallbacks = options.fallbacks;
  24765. this._indexParameters = options.indexParameters;
  24766. if (options.uniformBuffersNames) {
  24767. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  24768. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  24769. }
  24770. }
  24771. }
  24772. else {
  24773. this._engine = engine;
  24774. this.defines = defines;
  24775. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  24776. this._samplers = samplers;
  24777. this._attributesNames = attributesNamesOrOptions;
  24778. this.onError = onError;
  24779. this.onCompiled = onCompiled;
  24780. this._indexParameters = indexParameters;
  24781. this._fallbacks = fallbacks;
  24782. }
  24783. this.uniqueId = Effect._uniqueIdSeed++;
  24784. var vertexSource;
  24785. var fragmentSource;
  24786. if (baseName.vertexElement) {
  24787. vertexSource = document.getElementById(baseName.vertexElement);
  24788. if (!vertexSource) {
  24789. vertexSource = baseName.vertexElement;
  24790. }
  24791. }
  24792. else {
  24793. vertexSource = baseName.vertex || baseName;
  24794. }
  24795. if (baseName.fragmentElement) {
  24796. fragmentSource = document.getElementById(baseName.fragmentElement);
  24797. if (!fragmentSource) {
  24798. fragmentSource = baseName.fragmentElement;
  24799. }
  24800. }
  24801. else {
  24802. fragmentSource = baseName.fragment || baseName;
  24803. }
  24804. this._loadVertexShader(vertexSource, function (vertexCode) {
  24805. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24806. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  24807. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24808. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24809. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  24810. if (baseName) {
  24811. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  24812. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  24813. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  24814. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  24815. }
  24816. else {
  24817. _this._vertexSourceCode = migratedVertexCode;
  24818. _this._fragmentSourceCode = migratedFragmentCode;
  24819. }
  24820. _this._prepareEffect();
  24821. });
  24822. });
  24823. });
  24824. });
  24825. });
  24826. });
  24827. }
  24828. Object.defineProperty(Effect.prototype, "key", {
  24829. get: function () {
  24830. return this._key;
  24831. },
  24832. enumerable: true,
  24833. configurable: true
  24834. });
  24835. // Properties
  24836. Effect.prototype.isReady = function () {
  24837. return this._isReady;
  24838. };
  24839. Effect.prototype.getEngine = function () {
  24840. return this._engine;
  24841. };
  24842. Effect.prototype.getProgram = function () {
  24843. return this._program;
  24844. };
  24845. Effect.prototype.getAttributesNames = function () {
  24846. return this._attributesNames;
  24847. };
  24848. Effect.prototype.getAttributeLocation = function (index) {
  24849. return this._attributes[index];
  24850. };
  24851. Effect.prototype.getAttributeLocationByName = function (name) {
  24852. var index = this._attributesNames.indexOf(name);
  24853. return this._attributes[index];
  24854. };
  24855. Effect.prototype.getAttributesCount = function () {
  24856. return this._attributes.length;
  24857. };
  24858. Effect.prototype.getUniformIndex = function (uniformName) {
  24859. return this._uniformsNames.indexOf(uniformName);
  24860. };
  24861. Effect.prototype.getUniform = function (uniformName) {
  24862. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24863. };
  24864. Effect.prototype.getSamplers = function () {
  24865. return this._samplers;
  24866. };
  24867. Effect.prototype.getCompilationError = function () {
  24868. return this._compilationError;
  24869. };
  24870. // Methods
  24871. Effect.prototype.executeWhenCompiled = function (func) {
  24872. if (this.isReady()) {
  24873. func(this);
  24874. return;
  24875. }
  24876. this.onCompileObservable.add(function (effect) {
  24877. func(effect);
  24878. });
  24879. };
  24880. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24881. if (BABYLON.Tools.IsWindowObjectExist()) {
  24882. // DOM element ?
  24883. if (vertex instanceof HTMLElement) {
  24884. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24885. callback(vertexCode);
  24886. return;
  24887. }
  24888. }
  24889. // Base64 encoded ?
  24890. if (vertex.substr(0, 7) === "base64:") {
  24891. var vertexBinary = window.atob(vertex.substr(7));
  24892. callback(vertexBinary);
  24893. return;
  24894. }
  24895. // Is in local store ?
  24896. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24897. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24898. return;
  24899. }
  24900. var vertexShaderUrl;
  24901. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24902. vertexShaderUrl = vertex;
  24903. }
  24904. else {
  24905. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24906. }
  24907. // Vertex shader
  24908. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24909. };
  24910. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24911. if (BABYLON.Tools.IsWindowObjectExist()) {
  24912. // DOM element ?
  24913. if (fragment instanceof HTMLElement) {
  24914. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24915. callback(fragmentCode);
  24916. return;
  24917. }
  24918. }
  24919. // Base64 encoded ?
  24920. if (fragment.substr(0, 7) === "base64:") {
  24921. var fragmentBinary = window.atob(fragment.substr(7));
  24922. callback(fragmentBinary);
  24923. return;
  24924. }
  24925. // Is in local store ?
  24926. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24927. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24928. return;
  24929. }
  24930. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24931. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24932. return;
  24933. }
  24934. var fragmentShaderUrl;
  24935. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24936. fragmentShaderUrl = fragment;
  24937. }
  24938. else {
  24939. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24940. }
  24941. // Fragment shader
  24942. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24943. };
  24944. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  24945. // Rebuild shaders source code
  24946. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  24947. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  24948. vertexCode = prefix + vertexCode;
  24949. fragmentCode = prefix + fragmentCode;
  24950. // Number lines of shaders source code
  24951. var i = 2;
  24952. var regex = /\n/gm;
  24953. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24954. i = 2;
  24955. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24956. // Dump shaders name and formatted source code
  24957. if (this.name.vertexElement) {
  24958. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  24959. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  24960. }
  24961. else if (this.name.vertex) {
  24962. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  24963. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  24964. }
  24965. else {
  24966. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  24967. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  24968. }
  24969. };
  24970. ;
  24971. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  24972. var preparedSourceCode = this._processPrecision(sourceCode);
  24973. if (this._engine.webGLVersion == 1) {
  24974. callback(preparedSourceCode);
  24975. return;
  24976. }
  24977. // Already converted
  24978. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  24979. callback(preparedSourceCode.replace("#version 300 es", ""));
  24980. return;
  24981. }
  24982. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  24983. // Remove extensions
  24984. // #extension GL_OES_standard_derivatives : enable
  24985. // #extension GL_EXT_shader_texture_lod : enable
  24986. // #extension GL_EXT_frag_depth : enable
  24987. // #extension GL_EXT_draw_buffers : require
  24988. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  24989. var result = preparedSourceCode.replace(regex, "");
  24990. // Migrate to GLSL v300
  24991. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  24992. result = result.replace(/attribute[ \t]/g, "in ");
  24993. result = result.replace(/[ \t]attribute/g, " in");
  24994. if (isFragment) {
  24995. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  24996. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  24997. result = result.replace(/texture2D\s*\(/g, "texture(");
  24998. result = result.replace(/textureCube\s*\(/g, "texture(");
  24999. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  25000. result = result.replace(/gl_FragColor/g, "glFragColor");
  25001. result = result.replace(/gl_FragData/g, "glFragData");
  25002. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  25003. }
  25004. callback(result);
  25005. };
  25006. Effect.prototype._processIncludes = function (sourceCode, callback) {
  25007. var _this = this;
  25008. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  25009. var match = regex.exec(sourceCode);
  25010. var returnValue = new String(sourceCode);
  25011. while (match != null) {
  25012. var includeFile = match[1];
  25013. // Uniform declaration
  25014. if (includeFile.indexOf("__decl__") !== -1) {
  25015. includeFile = includeFile.replace(/__decl__/, "");
  25016. if (this._engine.supportsUniformBuffers) {
  25017. includeFile = includeFile.replace(/Vertex/, "Ubo");
  25018. includeFile = includeFile.replace(/Fragment/, "Ubo");
  25019. }
  25020. includeFile = includeFile + "Declaration";
  25021. }
  25022. if (Effect.IncludesShadersStore[includeFile]) {
  25023. // Substitution
  25024. var includeContent = Effect.IncludesShadersStore[includeFile];
  25025. if (match[2]) {
  25026. var splits = match[3].split(",");
  25027. for (var index = 0; index < splits.length; index += 2) {
  25028. var source = new RegExp(splits[index], "g");
  25029. var dest = splits[index + 1];
  25030. includeContent = includeContent.replace(source, dest);
  25031. }
  25032. }
  25033. if (match[4]) {
  25034. var indexString = match[5];
  25035. if (indexString.indexOf("..") !== -1) {
  25036. var indexSplits = indexString.split("..");
  25037. var minIndex = parseInt(indexSplits[0]);
  25038. var maxIndex = parseInt(indexSplits[1]);
  25039. var sourceIncludeContent = includeContent.slice(0);
  25040. includeContent = "";
  25041. if (isNaN(maxIndex)) {
  25042. maxIndex = this._indexParameters[indexSplits[1]];
  25043. }
  25044. for (var i = minIndex; i < maxIndex; i++) {
  25045. if (!this._engine.supportsUniformBuffers) {
  25046. // Ubo replacement
  25047. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  25048. return p1 + "{X}";
  25049. });
  25050. }
  25051. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  25052. }
  25053. }
  25054. else {
  25055. if (!this._engine.supportsUniformBuffers) {
  25056. // Ubo replacement
  25057. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  25058. return p1 + "{X}";
  25059. });
  25060. }
  25061. includeContent = includeContent.replace(/\{X\}/g, indexString);
  25062. }
  25063. }
  25064. // Replace
  25065. returnValue = returnValue.replace(match[0], includeContent);
  25066. }
  25067. else {
  25068. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  25069. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  25070. Effect.IncludesShadersStore[includeFile] = fileContent;
  25071. _this._processIncludes(returnValue, callback);
  25072. });
  25073. return;
  25074. }
  25075. match = regex.exec(sourceCode);
  25076. }
  25077. callback(returnValue);
  25078. };
  25079. Effect.prototype._processPrecision = function (source) {
  25080. if (source.indexOf("precision highp float") === -1) {
  25081. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25082. source = "precision mediump float;\n" + source;
  25083. }
  25084. else {
  25085. source = "precision highp float;\n" + source;
  25086. }
  25087. }
  25088. else {
  25089. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25090. source = source.replace("precision highp float", "precision mediump float");
  25091. }
  25092. }
  25093. return source;
  25094. };
  25095. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  25096. var _this = this;
  25097. this._isReady = false;
  25098. this._vertexSourceCodeOverride = vertexSourceCode;
  25099. this._fragmentSourceCodeOverride = fragmentSourceCode;
  25100. this.onError = function (effect, error) {
  25101. if (onError) {
  25102. onError(error);
  25103. }
  25104. };
  25105. this.onCompiled = function () {
  25106. var scenes = _this.getEngine().scenes;
  25107. for (var i = 0; i < scenes.length; i++) {
  25108. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25109. }
  25110. if (onCompiled) {
  25111. onCompiled(_this._program);
  25112. }
  25113. };
  25114. this._fallbacks = null;
  25115. this._prepareEffect();
  25116. };
  25117. Effect.prototype._prepareEffect = function () {
  25118. var attributesNames = this._attributesNames;
  25119. var defines = this.defines;
  25120. var fallbacks = this._fallbacks;
  25121. this._valueCache = {};
  25122. var previousProgram = this._program;
  25123. try {
  25124. var engine = this._engine;
  25125. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  25126. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride);
  25127. }
  25128. else {
  25129. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  25130. }
  25131. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  25132. if (engine.webGLVersion > 1) {
  25133. for (var name in this._uniformBuffersNames) {
  25134. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  25135. }
  25136. }
  25137. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  25138. this._attributes = engine.getAttributes(this._program, attributesNames);
  25139. var index;
  25140. for (index = 0; index < this._samplers.length; index++) {
  25141. var sampler = this.getUniform(this._samplers[index]);
  25142. if (sampler == null) {
  25143. this._samplers.splice(index, 1);
  25144. index--;
  25145. }
  25146. }
  25147. engine.bindSamplers(this);
  25148. this._compilationError = "";
  25149. this._isReady = true;
  25150. if (this.onCompiled) {
  25151. this.onCompiled(this);
  25152. }
  25153. this.onCompileObservable.notifyObservers(this);
  25154. this.onCompileObservable.clear();
  25155. // Unbind mesh reference in fallbacks
  25156. if (this._fallbacks) {
  25157. this._fallbacks.unBindMesh();
  25158. }
  25159. if (previousProgram) {
  25160. this.getEngine()._deleteProgram(previousProgram);
  25161. }
  25162. }
  25163. catch (e) {
  25164. this._compilationError = e.message;
  25165. // Let's go through fallbacks then
  25166. BABYLON.Tools.Error("Unable to compile effect:");
  25167. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  25168. return " " + uniform;
  25169. }));
  25170. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  25171. return " " + attribute;
  25172. }));
  25173. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  25174. BABYLON.Tools.Error("Error: " + this._compilationError);
  25175. if (previousProgram) {
  25176. this._program = previousProgram;
  25177. this._isReady = true;
  25178. if (this.onError) {
  25179. this.onError(this, this._compilationError);
  25180. }
  25181. this.onErrorObservable.notifyObservers(this);
  25182. }
  25183. if (fallbacks && fallbacks.isMoreFallbacks) {
  25184. BABYLON.Tools.Error("Trying next fallback.");
  25185. this.defines = fallbacks.reduce(this.defines);
  25186. this._prepareEffect();
  25187. }
  25188. else {
  25189. if (this.onError) {
  25190. this.onError(this, this._compilationError);
  25191. }
  25192. this.onErrorObservable.notifyObservers(this);
  25193. this.onErrorObservable.clear();
  25194. // Unbind mesh reference in fallbacks
  25195. if (this._fallbacks) {
  25196. this._fallbacks.unBindMesh();
  25197. }
  25198. }
  25199. }
  25200. };
  25201. Object.defineProperty(Effect.prototype, "isSupported", {
  25202. get: function () {
  25203. return this._compilationError === "";
  25204. },
  25205. enumerable: true,
  25206. configurable: true
  25207. });
  25208. Effect.prototype._bindTexture = function (channel, texture) {
  25209. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  25210. };
  25211. Effect.prototype.setTexture = function (channel, texture) {
  25212. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  25213. };
  25214. Effect.prototype.setTextureArray = function (channel, textures) {
  25215. if (this._samplers.indexOf(channel + "Ex") === -1) {
  25216. var initialPos = this._samplers.indexOf(channel);
  25217. for (var index = 1; index < textures.length; index++) {
  25218. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  25219. }
  25220. }
  25221. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  25222. };
  25223. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  25224. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  25225. };
  25226. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  25227. var cache = this._valueCache[uniformName];
  25228. var flag = matrix.updateFlag;
  25229. if (cache !== undefined && cache === flag) {
  25230. return false;
  25231. }
  25232. this._valueCache[uniformName] = flag;
  25233. return true;
  25234. };
  25235. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  25236. var cache = this._valueCache[uniformName];
  25237. if (!cache) {
  25238. cache = [x, y];
  25239. this._valueCache[uniformName] = cache;
  25240. return true;
  25241. }
  25242. var changed = false;
  25243. if (cache[0] !== x) {
  25244. cache[0] = x;
  25245. changed = true;
  25246. }
  25247. if (cache[1] !== y) {
  25248. cache[1] = y;
  25249. changed = true;
  25250. }
  25251. return changed;
  25252. };
  25253. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  25254. var cache = this._valueCache[uniformName];
  25255. if (!cache) {
  25256. cache = [x, y, z];
  25257. this._valueCache[uniformName] = cache;
  25258. return true;
  25259. }
  25260. var changed = false;
  25261. if (cache[0] !== x) {
  25262. cache[0] = x;
  25263. changed = true;
  25264. }
  25265. if (cache[1] !== y) {
  25266. cache[1] = y;
  25267. changed = true;
  25268. }
  25269. if (cache[2] !== z) {
  25270. cache[2] = z;
  25271. changed = true;
  25272. }
  25273. return changed;
  25274. };
  25275. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  25276. var cache = this._valueCache[uniformName];
  25277. if (!cache) {
  25278. cache = [x, y, z, w];
  25279. this._valueCache[uniformName] = cache;
  25280. return true;
  25281. }
  25282. var changed = false;
  25283. if (cache[0] !== x) {
  25284. cache[0] = x;
  25285. changed = true;
  25286. }
  25287. if (cache[1] !== y) {
  25288. cache[1] = y;
  25289. changed = true;
  25290. }
  25291. if (cache[2] !== z) {
  25292. cache[2] = z;
  25293. changed = true;
  25294. }
  25295. if (cache[3] !== w) {
  25296. cache[3] = w;
  25297. changed = true;
  25298. }
  25299. return changed;
  25300. };
  25301. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  25302. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  25303. return;
  25304. }
  25305. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  25306. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  25307. };
  25308. Effect.prototype.bindUniformBlock = function (blockName, index) {
  25309. this._engine.bindUniformBlock(this._program, blockName, index);
  25310. };
  25311. Effect.prototype.setIntArray = function (uniformName, array) {
  25312. this._valueCache[uniformName] = null;
  25313. this._engine.setIntArray(this.getUniform(uniformName), array);
  25314. return this;
  25315. };
  25316. Effect.prototype.setIntArray2 = function (uniformName, array) {
  25317. this._valueCache[uniformName] = null;
  25318. this._engine.setIntArray2(this.getUniform(uniformName), array);
  25319. return this;
  25320. };
  25321. Effect.prototype.setIntArray3 = function (uniformName, array) {
  25322. this._valueCache[uniformName] = null;
  25323. this._engine.setIntArray3(this.getUniform(uniformName), array);
  25324. return this;
  25325. };
  25326. Effect.prototype.setIntArray4 = function (uniformName, array) {
  25327. this._valueCache[uniformName] = null;
  25328. this._engine.setIntArray4(this.getUniform(uniformName), array);
  25329. return this;
  25330. };
  25331. Effect.prototype.setFloatArray = function (uniformName, array) {
  25332. this._valueCache[uniformName] = null;
  25333. this._engine.setFloatArray(this.getUniform(uniformName), array);
  25334. return this;
  25335. };
  25336. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  25337. this._valueCache[uniformName] = null;
  25338. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  25339. return this;
  25340. };
  25341. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  25342. this._valueCache[uniformName] = null;
  25343. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  25344. return this;
  25345. };
  25346. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  25347. this._valueCache[uniformName] = null;
  25348. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  25349. return this;
  25350. };
  25351. Effect.prototype.setArray = function (uniformName, array) {
  25352. this._valueCache[uniformName] = null;
  25353. this._engine.setArray(this.getUniform(uniformName), array);
  25354. return this;
  25355. };
  25356. Effect.prototype.setArray2 = function (uniformName, array) {
  25357. this._valueCache[uniformName] = null;
  25358. this._engine.setArray2(this.getUniform(uniformName), array);
  25359. return this;
  25360. };
  25361. Effect.prototype.setArray3 = function (uniformName, array) {
  25362. this._valueCache[uniformName] = null;
  25363. this._engine.setArray3(this.getUniform(uniformName), array);
  25364. return this;
  25365. };
  25366. Effect.prototype.setArray4 = function (uniformName, array) {
  25367. this._valueCache[uniformName] = null;
  25368. this._engine.setArray4(this.getUniform(uniformName), array);
  25369. return this;
  25370. };
  25371. Effect.prototype.setMatrices = function (uniformName, matrices) {
  25372. if (!matrices) {
  25373. return this;
  25374. }
  25375. this._valueCache[uniformName] = null;
  25376. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  25377. return this;
  25378. };
  25379. Effect.prototype.setMatrix = function (uniformName, matrix) {
  25380. if (this._cacheMatrix(uniformName, matrix)) {
  25381. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  25382. }
  25383. return this;
  25384. };
  25385. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  25386. this._valueCache[uniformName] = null;
  25387. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  25388. return this;
  25389. };
  25390. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  25391. this._valueCache[uniformName] = null;
  25392. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  25393. return this;
  25394. };
  25395. Effect.prototype.setFloat = function (uniformName, value) {
  25396. var cache = this._valueCache[uniformName];
  25397. if (cache !== undefined && cache === value)
  25398. return this;
  25399. this._valueCache[uniformName] = value;
  25400. this._engine.setFloat(this.getUniform(uniformName), value);
  25401. return this;
  25402. };
  25403. Effect.prototype.setBool = function (uniformName, bool) {
  25404. var cache = this._valueCache[uniformName];
  25405. if (cache !== undefined && cache === bool)
  25406. return this;
  25407. this._valueCache[uniformName] = bool;
  25408. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  25409. return this;
  25410. };
  25411. Effect.prototype.setVector2 = function (uniformName, vector2) {
  25412. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  25413. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  25414. }
  25415. return this;
  25416. };
  25417. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  25418. if (this._cacheFloat2(uniformName, x, y)) {
  25419. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  25420. }
  25421. return this;
  25422. };
  25423. Effect.prototype.setVector3 = function (uniformName, vector3) {
  25424. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  25425. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  25426. }
  25427. return this;
  25428. };
  25429. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  25430. if (this._cacheFloat3(uniformName, x, y, z)) {
  25431. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  25432. }
  25433. return this;
  25434. };
  25435. Effect.prototype.setVector4 = function (uniformName, vector4) {
  25436. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  25437. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  25438. }
  25439. return this;
  25440. };
  25441. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  25442. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  25443. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  25444. }
  25445. return this;
  25446. };
  25447. Effect.prototype.setColor3 = function (uniformName, color3) {
  25448. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  25449. this._engine.setColor3(this.getUniform(uniformName), color3);
  25450. }
  25451. return this;
  25452. };
  25453. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  25454. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  25455. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  25456. }
  25457. return this;
  25458. };
  25459. Effect.ResetCache = function () {
  25460. Effect._baseCache = {};
  25461. };
  25462. Effect._uniqueIdSeed = 0;
  25463. Effect._baseCache = {};
  25464. // Statics
  25465. Effect.ShadersStore = {};
  25466. Effect.IncludesShadersStore = {};
  25467. return Effect;
  25468. }());
  25469. BABYLON.Effect = Effect;
  25470. })(BABYLON || (BABYLON = {}));
  25471. //# sourceMappingURL=babylon.effect.js.map
  25472. var BABYLON;
  25473. (function (BABYLON) {
  25474. var MaterialHelper = (function () {
  25475. function MaterialHelper() {
  25476. }
  25477. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  25478. defines._needUVs = true;
  25479. defines[key] = true;
  25480. if (texture.getTextureMatrix().isIdentity(true)) {
  25481. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  25482. if (texture.coordinatesIndex === 0) {
  25483. defines["MAINUV1"] = true;
  25484. }
  25485. else {
  25486. defines["MAINUV2"] = true;
  25487. }
  25488. }
  25489. else {
  25490. defines[key + "DIRECTUV"] = 0;
  25491. }
  25492. };
  25493. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  25494. var matrix = texture.getTextureMatrix();
  25495. if (!matrix.isIdentity(true)) {
  25496. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  25497. }
  25498. };
  25499. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  25500. if (defines._areMiscDirty) {
  25501. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  25502. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  25503. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  25504. }
  25505. };
  25506. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  25507. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  25508. var changed = false;
  25509. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  25510. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  25511. changed = true;
  25512. }
  25513. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  25514. defines["ALPHATEST"] = !defines["ALPHATEST"];
  25515. changed = true;
  25516. }
  25517. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  25518. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  25519. changed = true;
  25520. }
  25521. if (defines["INSTANCES"] !== useInstances) {
  25522. defines["INSTANCES"] = useInstances;
  25523. changed = true;
  25524. }
  25525. if (changed) {
  25526. defines.markAsUnprocessed();
  25527. }
  25528. };
  25529. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  25530. if (useMorphTargets === void 0) { useMorphTargets = false; }
  25531. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  25532. return false;
  25533. }
  25534. defines._normals = defines._needNormals;
  25535. defines._uvs = defines._needUVs;
  25536. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  25537. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25538. defines["TANGENT"] = true;
  25539. }
  25540. if (defines._needUVs) {
  25541. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  25542. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  25543. }
  25544. else {
  25545. defines["UV1"] = false;
  25546. defines["UV2"] = false;
  25547. }
  25548. if (useVertexColor) {
  25549. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  25550. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  25551. }
  25552. if (useBones) {
  25553. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  25554. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  25555. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  25556. }
  25557. else {
  25558. defines["NUM_BONE_INFLUENCERS"] = 0;
  25559. defines["BonesPerMesh"] = 0;
  25560. }
  25561. }
  25562. if (useMorphTargets) {
  25563. if (mesh.morphTargetManager) {
  25564. var manager = mesh.morphTargetManager;
  25565. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  25566. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  25567. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  25568. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  25569. }
  25570. else {
  25571. defines["MORPHTARGETS_TANGENT"] = false;
  25572. defines["MORPHTARGETS_NORMAL"] = false;
  25573. defines["MORPHTARGETS"] = false;
  25574. defines["NUM_MORPH_INFLUENCERS"] = 0;
  25575. }
  25576. }
  25577. return true;
  25578. };
  25579. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  25580. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25581. if (disableLighting === void 0) { disableLighting = false; }
  25582. if (!defines._areLightsDirty) {
  25583. return defines._needNormals;
  25584. }
  25585. var lightIndex = 0;
  25586. var needNormals = false;
  25587. var needRebuild = false;
  25588. var lightmapMode = false;
  25589. var shadowEnabled = false;
  25590. var specularEnabled = false;
  25591. if (scene.lightsEnabled && !disableLighting) {
  25592. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25593. var light = _a[_i];
  25594. needNormals = true;
  25595. if (defines["LIGHT" + lightIndex] === undefined) {
  25596. needRebuild = true;
  25597. }
  25598. defines["LIGHT" + lightIndex] = true;
  25599. defines["SPOTLIGHT" + lightIndex] = false;
  25600. defines["HEMILIGHT" + lightIndex] = false;
  25601. defines["POINTLIGHT" + lightIndex] = false;
  25602. defines["DIRLIGHT" + lightIndex] = false;
  25603. var type;
  25604. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  25605. type = "SPOTLIGHT" + lightIndex;
  25606. }
  25607. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  25608. type = "HEMILIGHT" + lightIndex;
  25609. }
  25610. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  25611. type = "POINTLIGHT" + lightIndex;
  25612. }
  25613. else {
  25614. type = "DIRLIGHT" + lightIndex;
  25615. }
  25616. defines[type] = true;
  25617. // Specular
  25618. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  25619. specularEnabled = true;
  25620. }
  25621. // Shadows
  25622. defines["SHADOW" + lightIndex] = false;
  25623. defines["SHADOWPCF" + lightIndex] = false;
  25624. defines["SHADOWESM" + lightIndex] = false;
  25625. defines["SHADOWCUBE" + lightIndex] = false;
  25626. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  25627. var shadowGenerator = light.getShadowGenerator();
  25628. if (shadowGenerator) {
  25629. shadowEnabled = true;
  25630. shadowGenerator.prepareDefines(defines, lightIndex);
  25631. }
  25632. }
  25633. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25634. lightmapMode = true;
  25635. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25636. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  25637. }
  25638. else {
  25639. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  25640. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  25641. }
  25642. lightIndex++;
  25643. if (lightIndex === maxSimultaneousLights)
  25644. break;
  25645. }
  25646. }
  25647. defines["SPECULARTERM"] = specularEnabled;
  25648. defines["SHADOWS"] = shadowEnabled;
  25649. // Resetting all other lights if any
  25650. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  25651. if (defines["LIGHT" + index] !== undefined) {
  25652. defines["LIGHT" + index] = false;
  25653. defines["HEMILIGHT" + lightIndex] = false;
  25654. defines["POINTLIGHT" + lightIndex] = false;
  25655. defines["DIRLIGHT" + lightIndex] = false;
  25656. defines["SPOTLIGHT" + lightIndex] = false;
  25657. defines["SHADOW" + lightIndex] = false;
  25658. }
  25659. }
  25660. var caps = scene.getEngine().getCaps();
  25661. if (defines["SHADOWFLOAT"] === undefined) {
  25662. needRebuild = true;
  25663. }
  25664. defines["SHADOWFLOAT"] = shadowEnabled &&
  25665. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  25666. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  25667. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  25668. if (needRebuild) {
  25669. defines.rebuild();
  25670. }
  25671. return needNormals;
  25672. };
  25673. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  25674. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25675. var uniformsList, uniformBuffersList, samplersList, defines;
  25676. if (uniformsListOrOptions.uniformsNames) {
  25677. var options = uniformsListOrOptions;
  25678. uniformsList = options.uniformsNames;
  25679. uniformBuffersList = options.uniformBuffersNames;
  25680. samplersList = options.samplers;
  25681. defines = options.defines;
  25682. maxSimultaneousLights = options.maxSimultaneousLights;
  25683. }
  25684. else {
  25685. uniformsList = uniformsListOrOptions;
  25686. }
  25687. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25688. if (!defines["LIGHT" + lightIndex]) {
  25689. break;
  25690. }
  25691. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  25692. if (uniformBuffersList) {
  25693. uniformBuffersList.push("Light" + lightIndex);
  25694. }
  25695. samplersList.push("shadowSampler" + lightIndex);
  25696. }
  25697. if (defines["NUM_MORPH_INFLUENCERS"]) {
  25698. uniformsList.push("morphTargetInfluences");
  25699. }
  25700. };
  25701. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25702. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25703. if (!defines["SHADOWS"]) {
  25704. return;
  25705. }
  25706. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25707. if (!defines["LIGHT" + lightIndex]) {
  25708. break;
  25709. }
  25710. if (lightIndex > 0) {
  25711. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25712. }
  25713. if (defines["SHADOW" + lightIndex]) {
  25714. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25715. }
  25716. if (defines["SHADOWPCF" + lightIndex]) {
  25717. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25718. }
  25719. if (defines["SHADOWESM" + lightIndex]) {
  25720. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  25721. }
  25722. }
  25723. };
  25724. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  25725. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  25726. if (influencers > 0) {
  25727. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  25728. var manager = mesh.morphTargetManager;
  25729. var normal = manager.supportsNormals && defines["NORMAL"];
  25730. var tangent = manager.supportsTangents && defines["TANGENT"];
  25731. for (var index = 0; index < influencers; index++) {
  25732. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  25733. if (normal) {
  25734. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  25735. }
  25736. if (tangent) {
  25737. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  25738. }
  25739. if (attribs.length > maxAttributesCount) {
  25740. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  25741. }
  25742. }
  25743. }
  25744. };
  25745. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25746. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25747. fallbacks.addCPUSkinningFallback(0, mesh);
  25748. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25749. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25750. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25751. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25752. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25753. }
  25754. }
  25755. };
  25756. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25757. if (defines["INSTANCES"]) {
  25758. attribs.push("world0");
  25759. attribs.push("world1");
  25760. attribs.push("world2");
  25761. attribs.push("world3");
  25762. }
  25763. };
  25764. // Bindings
  25765. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  25766. if (light.shadowEnabled && mesh.receiveShadows) {
  25767. var shadowGenerator = light.getShadowGenerator();
  25768. if (shadowGenerator) {
  25769. shadowGenerator.bindShadowLight(lightIndex, effect);
  25770. }
  25771. }
  25772. };
  25773. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25774. light.transferToEffect(effect, lightIndex + "");
  25775. };
  25776. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  25777. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25778. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  25779. var lightIndex = 0;
  25780. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25781. var light = _a[_i];
  25782. var scaledIntensity = light.getScaledIntensity();
  25783. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  25784. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25785. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  25786. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  25787. if (defines["SPECULARTERM"]) {
  25788. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  25789. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  25790. }
  25791. // Shadows
  25792. if (scene.shadowsEnabled) {
  25793. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  25794. }
  25795. light._uniformBuffer.update();
  25796. lightIndex++;
  25797. if (lightIndex === maxSimultaneousLights)
  25798. break;
  25799. }
  25800. };
  25801. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25802. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25803. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25804. effect.setColor3("vFogColor", scene.fogColor);
  25805. }
  25806. };
  25807. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25808. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25809. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25810. if (matrices) {
  25811. effect.setMatrices("mBones", matrices);
  25812. }
  25813. }
  25814. };
  25815. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  25816. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  25817. return;
  25818. }
  25819. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  25820. };
  25821. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25822. if (defines["LOGARITHMICDEPTH"]) {
  25823. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25824. }
  25825. };
  25826. MaterialHelper.BindClipPlane = function (effect, scene) {
  25827. if (scene.clipPlane) {
  25828. var clipPlane = scene.clipPlane;
  25829. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25830. }
  25831. };
  25832. return MaterialHelper;
  25833. }());
  25834. BABYLON.MaterialHelper = MaterialHelper;
  25835. })(BABYLON || (BABYLON = {}));
  25836. //# sourceMappingURL=babylon.materialHelper.js.map
  25837. var BABYLON;
  25838. (function (BABYLON) {
  25839. var MaterialDefines = (function () {
  25840. function MaterialDefines() {
  25841. this._isDirty = true;
  25842. this._areLightsDirty = true;
  25843. this._areAttributesDirty = true;
  25844. this._areTexturesDirty = true;
  25845. this._areFresnelDirty = true;
  25846. this._areMiscDirty = true;
  25847. this._areImageProcessingDirty = true;
  25848. this._normals = false;
  25849. this._uvs = false;
  25850. this._needNormals = false;
  25851. this._needUVs = false;
  25852. }
  25853. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  25854. get: function () {
  25855. return this._isDirty;
  25856. },
  25857. enumerable: true,
  25858. configurable: true
  25859. });
  25860. MaterialDefines.prototype.markAsProcessed = function () {
  25861. this._isDirty = false;
  25862. this._areAttributesDirty = false;
  25863. this._areTexturesDirty = false;
  25864. this._areFresnelDirty = false;
  25865. this._areLightsDirty = false;
  25866. this._areMiscDirty = false;
  25867. this._areImageProcessingDirty = false;
  25868. };
  25869. MaterialDefines.prototype.markAsUnprocessed = function () {
  25870. this._isDirty = true;
  25871. };
  25872. MaterialDefines.prototype.markAllAsDirty = function () {
  25873. this._areTexturesDirty = true;
  25874. this._areAttributesDirty = true;
  25875. this._areLightsDirty = true;
  25876. this._areFresnelDirty = true;
  25877. this._areMiscDirty = true;
  25878. this._areImageProcessingDirty = true;
  25879. this._isDirty = true;
  25880. };
  25881. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  25882. this._areImageProcessingDirty = true;
  25883. this._isDirty = true;
  25884. };
  25885. MaterialDefines.prototype.markAsLightDirty = function () {
  25886. this._areLightsDirty = true;
  25887. this._isDirty = true;
  25888. };
  25889. MaterialDefines.prototype.markAsAttributesDirty = function () {
  25890. this._areAttributesDirty = true;
  25891. this._isDirty = true;
  25892. };
  25893. MaterialDefines.prototype.markAsTexturesDirty = function () {
  25894. this._areTexturesDirty = true;
  25895. this._isDirty = true;
  25896. };
  25897. MaterialDefines.prototype.markAsFresnelDirty = function () {
  25898. this._areFresnelDirty = true;
  25899. this._isDirty = true;
  25900. };
  25901. MaterialDefines.prototype.markAsMiscDirty = function () {
  25902. this._areMiscDirty = true;
  25903. this._isDirty = true;
  25904. };
  25905. MaterialDefines.prototype.rebuild = function () {
  25906. if (this._keys) {
  25907. delete this._keys;
  25908. }
  25909. this._keys = [];
  25910. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  25911. var key = _a[_i];
  25912. if (key[0] === "_") {
  25913. continue;
  25914. }
  25915. this._keys.push(key);
  25916. }
  25917. };
  25918. MaterialDefines.prototype.isEqual = function (other) {
  25919. if (this._keys.length !== other._keys.length) {
  25920. return false;
  25921. }
  25922. for (var index = 0; index < this._keys.length; index++) {
  25923. var prop = this._keys[index];
  25924. if (this[prop] !== other[prop]) {
  25925. return false;
  25926. }
  25927. }
  25928. return true;
  25929. };
  25930. MaterialDefines.prototype.cloneTo = function (other) {
  25931. if (this._keys.length !== other._keys.length) {
  25932. other._keys = this._keys.slice(0);
  25933. }
  25934. for (var index = 0; index < this._keys.length; index++) {
  25935. var prop = this._keys[index];
  25936. other[prop] = this[prop];
  25937. }
  25938. };
  25939. MaterialDefines.prototype.reset = function () {
  25940. for (var index = 0; index < this._keys.length; index++) {
  25941. var prop = this._keys[index];
  25942. if (typeof (this[prop]) === "number") {
  25943. this[prop] = 0;
  25944. }
  25945. else {
  25946. this[prop] = false;
  25947. }
  25948. }
  25949. };
  25950. MaterialDefines.prototype.toString = function () {
  25951. var result = "";
  25952. for (var index = 0; index < this._keys.length; index++) {
  25953. var prop = this._keys[index];
  25954. var value = this[prop];
  25955. if (typeof (value) === "number") {
  25956. result += "#define " + prop + " " + this[prop] + "\n";
  25957. }
  25958. else if (value) {
  25959. result += "#define " + prop + "\n";
  25960. }
  25961. }
  25962. return result;
  25963. };
  25964. return MaterialDefines;
  25965. }());
  25966. BABYLON.MaterialDefines = MaterialDefines;
  25967. var Material = (function () {
  25968. function Material(name, scene, doNotAdd) {
  25969. this.checkReadyOnEveryCall = false;
  25970. this.checkReadyOnlyOnce = false;
  25971. this.state = "";
  25972. this.alpha = 1.0;
  25973. this._backFaceCulling = true;
  25974. this.doNotSerialize = false;
  25975. this.storeEffectOnSubMeshes = false;
  25976. /**
  25977. * An event triggered when the material is disposed.
  25978. * @type {BABYLON.Observable}
  25979. */
  25980. this.onDisposeObservable = new BABYLON.Observable();
  25981. /**
  25982. * An event triggered when the material is bound.
  25983. * @type {BABYLON.Observable}
  25984. */
  25985. this.onBindObservable = new BABYLON.Observable();
  25986. /**
  25987. * An event triggered when the material is unbound.
  25988. * @type {BABYLON.Observable}
  25989. */
  25990. this.onUnBindObservable = new BABYLON.Observable();
  25991. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25992. this._needDepthPrePass = false;
  25993. this.disableDepthWrite = false;
  25994. this.forceDepthWrite = false;
  25995. this.separateCullingPass = false;
  25996. this._fogEnabled = true;
  25997. this.pointSize = 1.0;
  25998. this.zOffset = 0;
  25999. this._wasPreviouslyReady = false;
  26000. this._fillMode = Material.TriangleFillMode;
  26001. this.name = name;
  26002. this.id = name || BABYLON.Tools.RandomId();
  26003. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26004. if (this._scene.useRightHandedSystem) {
  26005. this.sideOrientation = Material.ClockWiseSideOrientation;
  26006. }
  26007. else {
  26008. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  26009. }
  26010. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  26011. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  26012. if (!doNotAdd) {
  26013. this._scene.materials.push(this);
  26014. }
  26015. }
  26016. Object.defineProperty(Material, "TriangleFillMode", {
  26017. get: function () {
  26018. return Material._TriangleFillMode;
  26019. },
  26020. enumerable: true,
  26021. configurable: true
  26022. });
  26023. Object.defineProperty(Material, "WireFrameFillMode", {
  26024. get: function () {
  26025. return Material._WireFrameFillMode;
  26026. },
  26027. enumerable: true,
  26028. configurable: true
  26029. });
  26030. Object.defineProperty(Material, "PointFillMode", {
  26031. get: function () {
  26032. return Material._PointFillMode;
  26033. },
  26034. enumerable: true,
  26035. configurable: true
  26036. });
  26037. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  26038. get: function () {
  26039. return Material._ClockWiseSideOrientation;
  26040. },
  26041. enumerable: true,
  26042. configurable: true
  26043. });
  26044. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  26045. get: function () {
  26046. return Material._CounterClockWiseSideOrientation;
  26047. },
  26048. enumerable: true,
  26049. configurable: true
  26050. });
  26051. Object.defineProperty(Material, "TextureDirtyFlag", {
  26052. get: function () {
  26053. return Material._TextureDirtyFlag;
  26054. },
  26055. enumerable: true,
  26056. configurable: true
  26057. });
  26058. Object.defineProperty(Material, "LightDirtyFlag", {
  26059. get: function () {
  26060. return Material._LightDirtyFlag;
  26061. },
  26062. enumerable: true,
  26063. configurable: true
  26064. });
  26065. Object.defineProperty(Material, "FresnelDirtyFlag", {
  26066. get: function () {
  26067. return Material._FresnelDirtyFlag;
  26068. },
  26069. enumerable: true,
  26070. configurable: true
  26071. });
  26072. Object.defineProperty(Material, "AttributesDirtyFlag", {
  26073. get: function () {
  26074. return Material._AttributesDirtyFlag;
  26075. },
  26076. enumerable: true,
  26077. configurable: true
  26078. });
  26079. Object.defineProperty(Material, "MiscDirtyFlag", {
  26080. get: function () {
  26081. return Material._MiscDirtyFlag;
  26082. },
  26083. enumerable: true,
  26084. configurable: true
  26085. });
  26086. Object.defineProperty(Material.prototype, "backFaceCulling", {
  26087. get: function () {
  26088. return this._backFaceCulling;
  26089. },
  26090. set: function (value) {
  26091. if (this._backFaceCulling === value) {
  26092. return;
  26093. }
  26094. this._backFaceCulling = value;
  26095. this.markAsDirty(Material.TextureDirtyFlag);
  26096. },
  26097. enumerable: true,
  26098. configurable: true
  26099. });
  26100. Object.defineProperty(Material.prototype, "onDispose", {
  26101. set: function (callback) {
  26102. if (this._onDisposeObserver) {
  26103. this.onDisposeObservable.remove(this._onDisposeObserver);
  26104. }
  26105. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26106. },
  26107. enumerable: true,
  26108. configurable: true
  26109. });
  26110. Object.defineProperty(Material.prototype, "onBind", {
  26111. set: function (callback) {
  26112. if (this._onBindObserver) {
  26113. this.onBindObservable.remove(this._onBindObserver);
  26114. }
  26115. this._onBindObserver = this.onBindObservable.add(callback);
  26116. },
  26117. enumerable: true,
  26118. configurable: true
  26119. });
  26120. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  26121. get: function () {
  26122. return this._needDepthPrePass;
  26123. },
  26124. set: function (value) {
  26125. if (this._needDepthPrePass === value) {
  26126. return;
  26127. }
  26128. this._needDepthPrePass = value;
  26129. if (this._needDepthPrePass) {
  26130. this.checkReadyOnEveryCall = true;
  26131. }
  26132. },
  26133. enumerable: true,
  26134. configurable: true
  26135. });
  26136. Object.defineProperty(Material.prototype, "fogEnabled", {
  26137. get: function () {
  26138. return this._fogEnabled;
  26139. },
  26140. set: function (value) {
  26141. if (this._fogEnabled === value) {
  26142. return;
  26143. }
  26144. this._fogEnabled = value;
  26145. this.markAsDirty(Material.MiscDirtyFlag);
  26146. },
  26147. enumerable: true,
  26148. configurable: true
  26149. });
  26150. Object.defineProperty(Material.prototype, "wireframe", {
  26151. get: function () {
  26152. return this._fillMode === Material.WireFrameFillMode;
  26153. },
  26154. set: function (value) {
  26155. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  26156. },
  26157. enumerable: true,
  26158. configurable: true
  26159. });
  26160. Object.defineProperty(Material.prototype, "pointsCloud", {
  26161. get: function () {
  26162. return this._fillMode === Material.PointFillMode;
  26163. },
  26164. set: function (value) {
  26165. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  26166. },
  26167. enumerable: true,
  26168. configurable: true
  26169. });
  26170. Object.defineProperty(Material.prototype, "fillMode", {
  26171. get: function () {
  26172. return this._fillMode;
  26173. },
  26174. set: function (value) {
  26175. if (this._fillMode === value) {
  26176. return;
  26177. }
  26178. this._fillMode = value;
  26179. this.markAsDirty(Material.MiscDirtyFlag);
  26180. },
  26181. enumerable: true,
  26182. configurable: true
  26183. });
  26184. /**
  26185. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26186. * subclasses should override adding information pertainent to themselves
  26187. */
  26188. Material.prototype.toString = function (fullDetails) {
  26189. var ret = "Name: " + this.name;
  26190. if (fullDetails) {
  26191. }
  26192. return ret;
  26193. };
  26194. /**
  26195. * Child classes can use it to update shaders
  26196. */
  26197. Material.prototype.getClassName = function () {
  26198. return "Material";
  26199. };
  26200. Object.defineProperty(Material.prototype, "isFrozen", {
  26201. get: function () {
  26202. return this.checkReadyOnlyOnce;
  26203. },
  26204. enumerable: true,
  26205. configurable: true
  26206. });
  26207. Material.prototype.freeze = function () {
  26208. this.checkReadyOnlyOnce = true;
  26209. };
  26210. Material.prototype.unfreeze = function () {
  26211. this.checkReadyOnlyOnce = false;
  26212. };
  26213. Material.prototype.isReady = function (mesh, useInstances) {
  26214. return true;
  26215. };
  26216. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  26217. return false;
  26218. };
  26219. Material.prototype.getEffect = function () {
  26220. return this._effect;
  26221. };
  26222. Material.prototype.getScene = function () {
  26223. return this._scene;
  26224. };
  26225. Material.prototype.needAlphaBlending = function () {
  26226. return (this.alpha < 1.0);
  26227. };
  26228. Material.prototype.needAlphaTesting = function () {
  26229. return false;
  26230. };
  26231. Material.prototype.getAlphaTestTexture = function () {
  26232. return null;
  26233. };
  26234. Material.prototype.markDirty = function () {
  26235. this._wasPreviouslyReady = false;
  26236. };
  26237. Material.prototype._preBind = function (effect, overrideOrientation) {
  26238. var engine = this._scene.getEngine();
  26239. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  26240. var reverse = orientation === Material.ClockWiseSideOrientation;
  26241. engine.enableEffect(effect ? effect : this._effect);
  26242. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  26243. return reverse;
  26244. };
  26245. Material.prototype.bind = function (world, mesh) {
  26246. };
  26247. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  26248. };
  26249. Material.prototype.bindOnlyWorldMatrix = function (world) {
  26250. };
  26251. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  26252. sceneUbo.bindToEffect(effect, "Scene");
  26253. };
  26254. Material.prototype.bindView = function (effect) {
  26255. if (!this._useUBO) {
  26256. effect.setMatrix("view", this.getScene().getViewMatrix());
  26257. }
  26258. else {
  26259. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  26260. }
  26261. };
  26262. Material.prototype.bindViewProjection = function (effect) {
  26263. if (!this._useUBO) {
  26264. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  26265. }
  26266. else {
  26267. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  26268. }
  26269. };
  26270. Material.prototype._afterBind = function (mesh) {
  26271. this._scene._cachedMaterial = this;
  26272. if (mesh) {
  26273. this._scene._cachedVisibility = mesh.visibility;
  26274. }
  26275. else {
  26276. this._scene._cachedVisibility = 1;
  26277. }
  26278. this.onBindObservable.notifyObservers(mesh);
  26279. if (this.disableDepthWrite) {
  26280. var engine = this._scene.getEngine();
  26281. this._cachedDepthWriteState = engine.getDepthWrite();
  26282. engine.setDepthWrite(false);
  26283. }
  26284. };
  26285. Material.prototype.unbind = function () {
  26286. this.onUnBindObservable.notifyObservers(this);
  26287. if (this.disableDepthWrite) {
  26288. var engine = this._scene.getEngine();
  26289. engine.setDepthWrite(this._cachedDepthWriteState);
  26290. }
  26291. };
  26292. Material.prototype.getActiveTextures = function () {
  26293. return [];
  26294. };
  26295. Material.prototype.hasTexture = function (texture) {
  26296. return false;
  26297. };
  26298. Material.prototype.clone = function (name) {
  26299. return null;
  26300. };
  26301. Material.prototype.getBindedMeshes = function () {
  26302. var result = new Array();
  26303. for (var index = 0; index < this._scene.meshes.length; index++) {
  26304. var mesh = this._scene.meshes[index];
  26305. if (mesh.material === this) {
  26306. result.push(mesh);
  26307. }
  26308. }
  26309. return result;
  26310. };
  26311. /**
  26312. * Force shader compilation including textures ready check
  26313. */
  26314. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  26315. var _this = this;
  26316. var subMesh = new BABYLON.BaseSubMesh();
  26317. var scene = this.getScene();
  26318. var engine = scene.getEngine();
  26319. var checkReady = function () {
  26320. if (!_this._scene || !_this._scene.getEngine()) {
  26321. return;
  26322. }
  26323. if (subMesh._materialDefines) {
  26324. subMesh._materialDefines._renderId = -1;
  26325. }
  26326. var alphaTestState = engine.getAlphaTesting();
  26327. var clipPlaneState = scene.clipPlane;
  26328. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  26329. if (options && options.clipPlane) {
  26330. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  26331. }
  26332. if (_this.storeEffectOnSubMeshes) {
  26333. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  26334. if (onCompiled) {
  26335. onCompiled(_this);
  26336. }
  26337. }
  26338. else {
  26339. setTimeout(checkReady, 16);
  26340. }
  26341. }
  26342. else {
  26343. if (_this.isReady(mesh)) {
  26344. if (onCompiled) {
  26345. onCompiled(_this);
  26346. }
  26347. }
  26348. else {
  26349. setTimeout(checkReady, 16);
  26350. }
  26351. }
  26352. engine.setAlphaTesting(alphaTestState);
  26353. if (options && options.clipPlane) {
  26354. scene.clipPlane = clipPlaneState;
  26355. }
  26356. };
  26357. checkReady();
  26358. };
  26359. Material.prototype.markAsDirty = function (flag) {
  26360. if (flag & Material.TextureDirtyFlag) {
  26361. this._markAllSubMeshesAsTexturesDirty();
  26362. }
  26363. if (flag & Material.LightDirtyFlag) {
  26364. this._markAllSubMeshesAsLightsDirty();
  26365. }
  26366. if (flag & Material.FresnelDirtyFlag) {
  26367. this._markAllSubMeshesAsFresnelDirty();
  26368. }
  26369. if (flag & Material.AttributesDirtyFlag) {
  26370. this._markAllSubMeshesAsAttributesDirty();
  26371. }
  26372. if (flag & Material.MiscDirtyFlag) {
  26373. this._markAllSubMeshesAsMiscDirty();
  26374. }
  26375. this.getScene().resetCachedMaterial();
  26376. };
  26377. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  26378. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  26379. var mesh = _a[_i];
  26380. if (!mesh.subMeshes) {
  26381. continue;
  26382. }
  26383. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  26384. var subMesh = _c[_b];
  26385. if (subMesh.getMaterial() !== this) {
  26386. continue;
  26387. }
  26388. if (!subMesh._materialDefines) {
  26389. continue;
  26390. }
  26391. func(subMesh._materialDefines);
  26392. }
  26393. }
  26394. };
  26395. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  26396. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  26397. };
  26398. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  26399. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  26400. };
  26401. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  26402. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  26403. };
  26404. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  26405. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  26406. };
  26407. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  26408. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  26409. };
  26410. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  26411. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  26412. };
  26413. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26414. // Animations
  26415. this.getScene().stopAnimation(this);
  26416. // Remove from scene
  26417. var index = this._scene.materials.indexOf(this);
  26418. if (index >= 0) {
  26419. this._scene.materials.splice(index, 1);
  26420. }
  26421. // Remove from meshes
  26422. for (index = 0; index < this._scene.meshes.length; index++) {
  26423. var mesh = this._scene.meshes[index];
  26424. if (mesh.material === this) {
  26425. mesh.material = null;
  26426. if (mesh.geometry) {
  26427. var geometry = mesh.geometry;
  26428. if (this.storeEffectOnSubMeshes) {
  26429. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  26430. var subMesh = _a[_i];
  26431. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  26432. }
  26433. }
  26434. else {
  26435. geometry._releaseVertexArrayObject(this._effect);
  26436. }
  26437. }
  26438. }
  26439. }
  26440. this._uniformBuffer.dispose();
  26441. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  26442. if (forceDisposeEffect && this._effect) {
  26443. if (this.storeEffectOnSubMeshes) {
  26444. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  26445. var subMesh = _c[_b];
  26446. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  26447. }
  26448. }
  26449. else {
  26450. this._scene.getEngine()._releaseEffect(this._effect);
  26451. }
  26452. this._effect = null;
  26453. }
  26454. // Callback
  26455. this.onDisposeObservable.notifyObservers(this);
  26456. this.onDisposeObservable.clear();
  26457. this.onBindObservable.clear();
  26458. this.onUnBindObservable.clear();
  26459. };
  26460. Material.prototype.serialize = function () {
  26461. return BABYLON.SerializationHelper.Serialize(this);
  26462. };
  26463. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  26464. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  26465. multiMaterial.id = parsedMultiMaterial.id;
  26466. if (BABYLON.Tags) {
  26467. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  26468. }
  26469. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  26470. var subMatId = parsedMultiMaterial.materials[matIndex];
  26471. if (subMatId) {
  26472. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  26473. }
  26474. else {
  26475. multiMaterial.subMaterials.push(null);
  26476. }
  26477. }
  26478. return multiMaterial;
  26479. };
  26480. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  26481. if (!parsedMaterial.customType) {
  26482. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  26483. }
  26484. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  26485. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  26486. if (!BABYLON.LegacyPBRMaterial) {
  26487. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  26488. return;
  26489. }
  26490. }
  26491. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  26492. return materialType.Parse(parsedMaterial, scene, rootUrl);
  26493. ;
  26494. };
  26495. Material._TriangleFillMode = 0;
  26496. Material._WireFrameFillMode = 1;
  26497. Material._PointFillMode = 2;
  26498. Material._ClockWiseSideOrientation = 0;
  26499. Material._CounterClockWiseSideOrientation = 1;
  26500. Material._TextureDirtyFlag = 1;
  26501. Material._LightDirtyFlag = 2;
  26502. Material._FresnelDirtyFlag = 4;
  26503. Material._AttributesDirtyFlag = 8;
  26504. Material._MiscDirtyFlag = 16;
  26505. __decorate([
  26506. BABYLON.serialize()
  26507. ], Material.prototype, "id", void 0);
  26508. __decorate([
  26509. BABYLON.serialize()
  26510. ], Material.prototype, "name", void 0);
  26511. __decorate([
  26512. BABYLON.serialize()
  26513. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  26514. __decorate([
  26515. BABYLON.serialize()
  26516. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  26517. __decorate([
  26518. BABYLON.serialize()
  26519. ], Material.prototype, "state", void 0);
  26520. __decorate([
  26521. BABYLON.serialize()
  26522. ], Material.prototype, "alpha", void 0);
  26523. __decorate([
  26524. BABYLON.serialize("backFaceCulling")
  26525. ], Material.prototype, "_backFaceCulling", void 0);
  26526. __decorate([
  26527. BABYLON.serialize()
  26528. ], Material.prototype, "sideOrientation", void 0);
  26529. __decorate([
  26530. BABYLON.serialize()
  26531. ], Material.prototype, "alphaMode", void 0);
  26532. __decorate([
  26533. BABYLON.serialize()
  26534. ], Material.prototype, "_needDepthPrePass", void 0);
  26535. __decorate([
  26536. BABYLON.serialize()
  26537. ], Material.prototype, "disableDepthWrite", void 0);
  26538. __decorate([
  26539. BABYLON.serialize()
  26540. ], Material.prototype, "forceDepthWrite", void 0);
  26541. __decorate([
  26542. BABYLON.serialize()
  26543. ], Material.prototype, "separateCullingPass", void 0);
  26544. __decorate([
  26545. BABYLON.serialize("fogEnabled")
  26546. ], Material.prototype, "_fogEnabled", void 0);
  26547. __decorate([
  26548. BABYLON.serialize()
  26549. ], Material.prototype, "pointSize", void 0);
  26550. __decorate([
  26551. BABYLON.serialize()
  26552. ], Material.prototype, "zOffset", void 0);
  26553. __decorate([
  26554. BABYLON.serialize()
  26555. ], Material.prototype, "wireframe", null);
  26556. __decorate([
  26557. BABYLON.serialize()
  26558. ], Material.prototype, "pointsCloud", null);
  26559. __decorate([
  26560. BABYLON.serialize()
  26561. ], Material.prototype, "fillMode", null);
  26562. return Material;
  26563. }());
  26564. BABYLON.Material = Material;
  26565. })(BABYLON || (BABYLON = {}));
  26566. //# sourceMappingURL=babylon.material.js.map
  26567. var BABYLON;
  26568. (function (BABYLON) {
  26569. var UniformBuffer = (function () {
  26570. /**
  26571. * Uniform buffer objects.
  26572. *
  26573. * Handles blocks of uniform on the GPU.
  26574. *
  26575. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  26576. *
  26577. * For more information, please refer to :
  26578. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  26579. */
  26580. function UniformBuffer(engine, data, dynamic) {
  26581. this._engine = engine;
  26582. this._noUBO = !engine.supportsUniformBuffers;
  26583. this._dynamic = dynamic;
  26584. this._data = data || [];
  26585. this._uniformLocations = {};
  26586. this._uniformSizes = {};
  26587. this._uniformLocationPointer = 0;
  26588. this._needSync = false;
  26589. if (this._noUBO) {
  26590. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  26591. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  26592. this.updateFloat = this._updateFloatForEffect;
  26593. this.updateFloat2 = this._updateFloat2ForEffect;
  26594. this.updateFloat3 = this._updateFloat3ForEffect;
  26595. this.updateFloat4 = this._updateFloat4ForEffect;
  26596. this.updateMatrix = this._updateMatrixForEffect;
  26597. this.updateVector3 = this._updateVector3ForEffect;
  26598. this.updateVector4 = this._updateVector4ForEffect;
  26599. this.updateColor3 = this._updateColor3ForEffect;
  26600. this.updateColor4 = this._updateColor4ForEffect;
  26601. }
  26602. else {
  26603. this._engine._uniformBuffers.push(this);
  26604. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  26605. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  26606. this.updateFloat = this._updateFloatForUniform;
  26607. this.updateFloat2 = this._updateFloat2ForUniform;
  26608. this.updateFloat3 = this._updateFloat3ForUniform;
  26609. this.updateFloat4 = this._updateFloat4ForUniform;
  26610. this.updateMatrix = this._updateMatrixForUniform;
  26611. this.updateVector3 = this._updateVector3ForUniform;
  26612. this.updateVector4 = this._updateVector4ForUniform;
  26613. this.updateColor3 = this._updateColor3ForUniform;
  26614. this.updateColor4 = this._updateColor4ForUniform;
  26615. }
  26616. }
  26617. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  26618. // Properties
  26619. /**
  26620. * Indicates if the buffer is using the WebGL2 UBO implementation,
  26621. * or just falling back on setUniformXXX calls.
  26622. */
  26623. get: function () {
  26624. return !this._noUBO;
  26625. },
  26626. enumerable: true,
  26627. configurable: true
  26628. });
  26629. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  26630. /**
  26631. * Indicates if the WebGL underlying uniform buffer is in sync
  26632. * with the javascript cache data.
  26633. */
  26634. get: function () {
  26635. return !this._needSync;
  26636. },
  26637. enumerable: true,
  26638. configurable: true
  26639. });
  26640. /**
  26641. * Indicates if the WebGL underlying uniform buffer is dynamic.
  26642. * Also, a dynamic UniformBuffer will disable cache verification and always
  26643. * update the underlying WebGL uniform buffer to the GPU.
  26644. */
  26645. UniformBuffer.prototype.isDynamic = function () {
  26646. return this._dynamic;
  26647. };
  26648. /**
  26649. * The data cache on JS side.
  26650. */
  26651. UniformBuffer.prototype.getData = function () {
  26652. return this._bufferData;
  26653. };
  26654. /**
  26655. * The underlying WebGL Uniform buffer.
  26656. */
  26657. UniformBuffer.prototype.getBuffer = function () {
  26658. return this._buffer;
  26659. };
  26660. /**
  26661. * std140 layout specifies how to align data within an UBO structure.
  26662. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  26663. * for specs.
  26664. */
  26665. UniformBuffer.prototype._fillAlignment = function (size) {
  26666. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  26667. // and 4x4 matrices
  26668. // TODO : change if other types are used
  26669. var alignment;
  26670. if (size <= 2) {
  26671. alignment = size;
  26672. }
  26673. else {
  26674. alignment = 4;
  26675. }
  26676. if ((this._uniformLocationPointer % alignment) !== 0) {
  26677. var oldPointer = this._uniformLocationPointer;
  26678. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  26679. var diff = this._uniformLocationPointer - oldPointer;
  26680. for (var i = 0; i < diff; i++) {
  26681. this._data.push(0);
  26682. }
  26683. }
  26684. };
  26685. /**
  26686. * Adds an uniform in the buffer.
  26687. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  26688. * for the layout to be correct !
  26689. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26690. * @param {number|number[]} size Data size, or data directly.
  26691. */
  26692. UniformBuffer.prototype.addUniform = function (name, size) {
  26693. if (this._noUBO) {
  26694. return;
  26695. }
  26696. if (this._uniformLocations[name] !== undefined) {
  26697. // Already existing uniform
  26698. return;
  26699. }
  26700. // This function must be called in the order of the shader layout !
  26701. // size can be the size of the uniform, or data directly
  26702. var data;
  26703. if (size instanceof Array) {
  26704. data = size;
  26705. size = data.length;
  26706. }
  26707. else {
  26708. size = size;
  26709. data = [];
  26710. // Fill with zeros
  26711. for (var i = 0; i < size; i++) {
  26712. data.push(0);
  26713. }
  26714. }
  26715. this._fillAlignment(size);
  26716. this._uniformSizes[name] = size;
  26717. this._uniformLocations[name] = this._uniformLocationPointer;
  26718. this._uniformLocationPointer += size;
  26719. for (var i = 0; i < size; i++) {
  26720. this._data.push(data[i]);
  26721. }
  26722. this._needSync = true;
  26723. };
  26724. /**
  26725. * Wrapper for addUniform.
  26726. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26727. * @param {Matrix} mat A 4x4 matrix.
  26728. */
  26729. UniformBuffer.prototype.addMatrix = function (name, mat) {
  26730. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  26731. };
  26732. /**
  26733. * Wrapper for addUniform.
  26734. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26735. * @param {number} x
  26736. * @param {number} y
  26737. */
  26738. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  26739. var temp = [x, y];
  26740. this.addUniform(name, temp);
  26741. };
  26742. /**
  26743. * Wrapper for addUniform.
  26744. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26745. * @param {number} x
  26746. * @param {number} y
  26747. * @param {number} z
  26748. */
  26749. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  26750. var temp = [x, y, z];
  26751. this.addUniform(name, temp);
  26752. };
  26753. /**
  26754. * Wrapper for addUniform.
  26755. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26756. * @param {Color3} color
  26757. */
  26758. UniformBuffer.prototype.addColor3 = function (name, color) {
  26759. var temp = new Array();
  26760. color.toArray(temp);
  26761. this.addUniform(name, temp);
  26762. };
  26763. /**
  26764. * Wrapper for addUniform.
  26765. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26766. * @param {Color3} color
  26767. * @param {number} alpha
  26768. */
  26769. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  26770. var temp = new Array();
  26771. color.toArray(temp);
  26772. temp.push(alpha);
  26773. this.addUniform(name, temp);
  26774. };
  26775. /**
  26776. * Wrapper for addUniform.
  26777. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26778. * @param {Vector3} vector
  26779. */
  26780. UniformBuffer.prototype.addVector3 = function (name, vector) {
  26781. var temp = new Array();
  26782. vector.toArray(temp);
  26783. this.addUniform(name, temp);
  26784. };
  26785. /**
  26786. * Wrapper for addUniform.
  26787. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26788. */
  26789. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  26790. this.addUniform(name, 12);
  26791. };
  26792. /**
  26793. * Wrapper for addUniform.
  26794. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26795. */
  26796. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  26797. this.addUniform(name, 8);
  26798. };
  26799. /**
  26800. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  26801. */
  26802. UniformBuffer.prototype.create = function () {
  26803. if (this._noUBO) {
  26804. return;
  26805. }
  26806. if (this._buffer) {
  26807. return; // nothing to do
  26808. }
  26809. // See spec, alignment must be filled as a vec4
  26810. this._fillAlignment(4);
  26811. this._bufferData = new Float32Array(this._data);
  26812. this._rebuild();
  26813. this._needSync = true;
  26814. };
  26815. UniformBuffer.prototype._rebuild = function () {
  26816. if (this._noUBO) {
  26817. return;
  26818. }
  26819. if (this._dynamic) {
  26820. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  26821. }
  26822. else {
  26823. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  26824. }
  26825. };
  26826. /**
  26827. * Updates the WebGL Uniform Buffer on the GPU.
  26828. * If the `dynamic` flag is set to true, no cache comparison is done.
  26829. * Otherwise, the buffer will be updated only if the cache differs.
  26830. */
  26831. UniformBuffer.prototype.update = function () {
  26832. if (!this._buffer) {
  26833. this.create();
  26834. return;
  26835. }
  26836. if (!this._dynamic && !this._needSync) {
  26837. return;
  26838. }
  26839. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  26840. this._needSync = false;
  26841. };
  26842. /**
  26843. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  26844. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26845. * @param {number[]|Float32Array} data Flattened data
  26846. * @param {number} size Size of the data.
  26847. */
  26848. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  26849. var location = this._uniformLocations[uniformName];
  26850. if (location === undefined) {
  26851. if (this._buffer) {
  26852. // Cannot add an uniform if the buffer is already created
  26853. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  26854. return;
  26855. }
  26856. this.addUniform(uniformName, size);
  26857. location = this._uniformLocations[uniformName];
  26858. }
  26859. if (!this._buffer) {
  26860. this.create();
  26861. }
  26862. if (!this._dynamic) {
  26863. // Cache for static uniform buffers
  26864. var changed = false;
  26865. for (var i = 0; i < size; i++) {
  26866. if (this._bufferData[location + i] !== data[i]) {
  26867. changed = true;
  26868. this._bufferData[location + i] = data[i];
  26869. }
  26870. }
  26871. this._needSync = this._needSync || changed;
  26872. }
  26873. else {
  26874. // No cache for dynamic
  26875. for (var i = 0; i < size; i++) {
  26876. this._bufferData[location + i] = data[i];
  26877. }
  26878. }
  26879. };
  26880. // Update methods
  26881. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  26882. // To match std140, matrix must be realigned
  26883. for (var i = 0; i < 3; i++) {
  26884. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  26885. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  26886. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  26887. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26888. }
  26889. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  26890. };
  26891. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  26892. this._currentEffect.setMatrix3x3(name, matrix);
  26893. };
  26894. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  26895. this._currentEffect.setMatrix2x2(name, matrix);
  26896. };
  26897. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  26898. // To match std140, matrix must be realigned
  26899. for (var i = 0; i < 2; i++) {
  26900. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  26901. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  26902. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  26903. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26904. }
  26905. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  26906. };
  26907. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  26908. this._currentEffect.setFloat(name, x);
  26909. };
  26910. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  26911. UniformBuffer._tempBuffer[0] = x;
  26912. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  26913. };
  26914. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  26915. if (suffix === void 0) { suffix = ""; }
  26916. this._currentEffect.setFloat2(name + suffix, x, y);
  26917. };
  26918. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  26919. if (suffix === void 0) { suffix = ""; }
  26920. UniformBuffer._tempBuffer[0] = x;
  26921. UniformBuffer._tempBuffer[1] = y;
  26922. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  26923. };
  26924. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  26925. if (suffix === void 0) { suffix = ""; }
  26926. this._currentEffect.setFloat3(name + suffix, x, y, z);
  26927. };
  26928. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  26929. if (suffix === void 0) { suffix = ""; }
  26930. UniformBuffer._tempBuffer[0] = x;
  26931. UniformBuffer._tempBuffer[1] = y;
  26932. UniformBuffer._tempBuffer[2] = z;
  26933. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26934. };
  26935. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  26936. if (suffix === void 0) { suffix = ""; }
  26937. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  26938. };
  26939. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  26940. if (suffix === void 0) { suffix = ""; }
  26941. UniformBuffer._tempBuffer[0] = x;
  26942. UniformBuffer._tempBuffer[1] = y;
  26943. UniformBuffer._tempBuffer[2] = z;
  26944. UniformBuffer._tempBuffer[3] = w;
  26945. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26946. };
  26947. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  26948. this._currentEffect.setMatrix(name, mat);
  26949. };
  26950. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  26951. this.updateUniform(name, mat.toArray(), 16);
  26952. };
  26953. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  26954. this._currentEffect.setVector3(name, vector);
  26955. };
  26956. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  26957. vector.toArray(UniformBuffer._tempBuffer);
  26958. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26959. };
  26960. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  26961. this._currentEffect.setVector4(name, vector);
  26962. };
  26963. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  26964. vector.toArray(UniformBuffer._tempBuffer);
  26965. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26966. };
  26967. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  26968. if (suffix === void 0) { suffix = ""; }
  26969. this._currentEffect.setColor3(name + suffix, color);
  26970. };
  26971. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  26972. if (suffix === void 0) { suffix = ""; }
  26973. color.toArray(UniformBuffer._tempBuffer);
  26974. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26975. };
  26976. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  26977. if (suffix === void 0) { suffix = ""; }
  26978. this._currentEffect.setColor4(name + suffix, color, alpha);
  26979. };
  26980. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  26981. if (suffix === void 0) { suffix = ""; }
  26982. color.toArray(UniformBuffer._tempBuffer);
  26983. UniformBuffer._tempBuffer[3] = alpha;
  26984. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26985. };
  26986. /**
  26987. * Sets a sampler uniform on the effect.
  26988. * @param {string} name Name of the sampler.
  26989. * @param {Texture} texture
  26990. */
  26991. UniformBuffer.prototype.setTexture = function (name, texture) {
  26992. this._currentEffect.setTexture(name, texture);
  26993. };
  26994. /**
  26995. * Directly updates the value of the uniform in the cache AND on the GPU.
  26996. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26997. * @param {number[]|Float32Array} data Flattened data
  26998. */
  26999. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  27000. this.updateUniform(uniformName, data, data.length);
  27001. this.update();
  27002. };
  27003. /**
  27004. * Binds this uniform buffer to an effect.
  27005. * @param {Effect} effect
  27006. * @param {string} name Name of the uniform block in the shader.
  27007. */
  27008. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  27009. this._currentEffect = effect;
  27010. if (this._noUBO) {
  27011. return;
  27012. }
  27013. effect.bindUniformBuffer(this._buffer, name);
  27014. };
  27015. /**
  27016. * Disposes the uniform buffer.
  27017. */
  27018. UniformBuffer.prototype.dispose = function () {
  27019. if (this._noUBO) {
  27020. return;
  27021. }
  27022. var index = this._engine._uniformBuffers.indexOf(this);
  27023. if (index !== -1) {
  27024. this._engine._uniformBuffers.splice(index, 1);
  27025. }
  27026. if (!this._buffer) {
  27027. return;
  27028. }
  27029. if (this._engine._releaseBuffer(this._buffer)) {
  27030. this._buffer = null;
  27031. }
  27032. };
  27033. // Pool for avoiding memory leaks
  27034. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  27035. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  27036. return UniformBuffer;
  27037. }());
  27038. BABYLON.UniformBuffer = UniformBuffer;
  27039. })(BABYLON || (BABYLON = {}));
  27040. //# sourceMappingURL=babylon.uniformBuffer.js.map
  27041. var BABYLON;
  27042. (function (BABYLON) {
  27043. var PushMaterial = (function (_super) {
  27044. __extends(PushMaterial, _super);
  27045. function PushMaterial(name, scene) {
  27046. var _this = _super.call(this, name, scene) || this;
  27047. _this.storeEffectOnSubMeshes = true;
  27048. return _this;
  27049. }
  27050. PushMaterial.prototype.getEffect = function () {
  27051. return this._activeEffect;
  27052. };
  27053. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  27054. if (!mesh) {
  27055. return false;
  27056. }
  27057. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  27058. return true;
  27059. }
  27060. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  27061. };
  27062. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  27063. this._activeEffect.setMatrix("world", world);
  27064. };
  27065. PushMaterial.prototype.bind = function (world, mesh) {
  27066. if (!mesh) {
  27067. return;
  27068. }
  27069. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  27070. };
  27071. PushMaterial.prototype._afterBind = function (mesh, effect) {
  27072. _super.prototype._afterBind.call(this, mesh);
  27073. this.getScene()._cachedEffect = effect;
  27074. };
  27075. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  27076. if (visibility === void 0) { visibility = 1; }
  27077. return scene.isCachedMaterialInvalid(this, effect, visibility);
  27078. };
  27079. return PushMaterial;
  27080. }(BABYLON.Material));
  27081. BABYLON.PushMaterial = PushMaterial;
  27082. })(BABYLON || (BABYLON = {}));
  27083. //# sourceMappingURL=babylon.pushMaterial.js.map
  27084. var BABYLON;
  27085. (function (BABYLON) {
  27086. var VertexData = (function () {
  27087. function VertexData() {
  27088. }
  27089. VertexData.prototype.set = function (data, kind) {
  27090. switch (kind) {
  27091. case BABYLON.VertexBuffer.PositionKind:
  27092. this.positions = data;
  27093. break;
  27094. case BABYLON.VertexBuffer.NormalKind:
  27095. this.normals = data;
  27096. break;
  27097. case BABYLON.VertexBuffer.TangentKind:
  27098. this.tangents = data;
  27099. break;
  27100. case BABYLON.VertexBuffer.UVKind:
  27101. this.uvs = data;
  27102. break;
  27103. case BABYLON.VertexBuffer.UV2Kind:
  27104. this.uvs2 = data;
  27105. break;
  27106. case BABYLON.VertexBuffer.UV3Kind:
  27107. this.uvs3 = data;
  27108. break;
  27109. case BABYLON.VertexBuffer.UV4Kind:
  27110. this.uvs4 = data;
  27111. break;
  27112. case BABYLON.VertexBuffer.UV5Kind:
  27113. this.uvs5 = data;
  27114. break;
  27115. case BABYLON.VertexBuffer.UV6Kind:
  27116. this.uvs6 = data;
  27117. break;
  27118. case BABYLON.VertexBuffer.ColorKind:
  27119. this.colors = data;
  27120. break;
  27121. case BABYLON.VertexBuffer.MatricesIndicesKind:
  27122. this.matricesIndices = data;
  27123. break;
  27124. case BABYLON.VertexBuffer.MatricesWeightsKind:
  27125. this.matricesWeights = data;
  27126. break;
  27127. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  27128. this.matricesIndicesExtra = data;
  27129. break;
  27130. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  27131. this.matricesWeightsExtra = data;
  27132. break;
  27133. }
  27134. };
  27135. /**
  27136. * Associates the vertexData to the passed Mesh.
  27137. * Sets it as updatable or not (default `false`).
  27138. * Returns the VertexData.
  27139. */
  27140. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  27141. this._applyTo(mesh, updatable);
  27142. return this;
  27143. };
  27144. /**
  27145. * Associates the vertexData to the passed Geometry.
  27146. * Sets it as updatable or not (default `false`).
  27147. * Returns the VertexData.
  27148. */
  27149. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  27150. this._applyTo(geometry, updatable);
  27151. return this;
  27152. };
  27153. /**
  27154. * Updates the associated mesh.
  27155. * Returns the VertexData.
  27156. */
  27157. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  27158. this._update(mesh);
  27159. return this;
  27160. };
  27161. /**
  27162. * Updates the associated geometry.
  27163. * Returns the VertexData.
  27164. */
  27165. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  27166. this._update(geometry);
  27167. return this;
  27168. };
  27169. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  27170. if (this.positions) {
  27171. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  27172. }
  27173. if (this.normals) {
  27174. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  27175. }
  27176. if (this.tangents) {
  27177. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  27178. }
  27179. if (this.uvs) {
  27180. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  27181. }
  27182. if (this.uvs2) {
  27183. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  27184. }
  27185. if (this.uvs3) {
  27186. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  27187. }
  27188. if (this.uvs4) {
  27189. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  27190. }
  27191. if (this.uvs5) {
  27192. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  27193. }
  27194. if (this.uvs6) {
  27195. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  27196. }
  27197. if (this.colors) {
  27198. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  27199. }
  27200. if (this.matricesIndices) {
  27201. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  27202. }
  27203. if (this.matricesWeights) {
  27204. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  27205. }
  27206. if (this.matricesIndicesExtra) {
  27207. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  27208. }
  27209. if (this.matricesWeightsExtra) {
  27210. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  27211. }
  27212. if (this.indices) {
  27213. meshOrGeometry.setIndices(this.indices, null, updatable);
  27214. }
  27215. return this;
  27216. };
  27217. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  27218. if (this.positions) {
  27219. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  27220. }
  27221. if (this.normals) {
  27222. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  27223. }
  27224. if (this.tangents) {
  27225. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  27226. }
  27227. if (this.uvs) {
  27228. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  27229. }
  27230. if (this.uvs2) {
  27231. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  27232. }
  27233. if (this.uvs3) {
  27234. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  27235. }
  27236. if (this.uvs4) {
  27237. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  27238. }
  27239. if (this.uvs5) {
  27240. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  27241. }
  27242. if (this.uvs6) {
  27243. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  27244. }
  27245. if (this.colors) {
  27246. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  27247. }
  27248. if (this.matricesIndices) {
  27249. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  27250. }
  27251. if (this.matricesWeights) {
  27252. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  27253. }
  27254. if (this.matricesIndicesExtra) {
  27255. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  27256. }
  27257. if (this.matricesWeightsExtra) {
  27258. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  27259. }
  27260. if (this.indices) {
  27261. meshOrGeometry.setIndices(this.indices);
  27262. }
  27263. return this;
  27264. };
  27265. /**
  27266. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  27267. * Returns the VertexData.
  27268. */
  27269. VertexData.prototype.transform = function (matrix) {
  27270. var transformed = BABYLON.Vector3.Zero();
  27271. var index;
  27272. if (this.positions) {
  27273. var position = BABYLON.Vector3.Zero();
  27274. for (index = 0; index < this.positions.length; index += 3) {
  27275. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  27276. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  27277. this.positions[index] = transformed.x;
  27278. this.positions[index + 1] = transformed.y;
  27279. this.positions[index + 2] = transformed.z;
  27280. }
  27281. }
  27282. if (this.normals) {
  27283. var normal = BABYLON.Vector3.Zero();
  27284. for (index = 0; index < this.normals.length; index += 3) {
  27285. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  27286. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  27287. this.normals[index] = transformed.x;
  27288. this.normals[index + 1] = transformed.y;
  27289. this.normals[index + 2] = transformed.z;
  27290. }
  27291. }
  27292. if (this.tangents) {
  27293. var tangent = BABYLON.Vector4.Zero();
  27294. var tangentTransformed = BABYLON.Vector4.Zero();
  27295. for (index = 0; index < this.tangents.length; index += 4) {
  27296. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  27297. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  27298. this.tangents[index] = tangentTransformed.x;
  27299. this.tangents[index + 1] = tangentTransformed.y;
  27300. this.tangents[index + 2] = tangentTransformed.z;
  27301. this.tangents[index + 3] = tangentTransformed.w;
  27302. }
  27303. }
  27304. return this;
  27305. };
  27306. /**
  27307. * Merges the passed VertexData into the current one.
  27308. * Returns the modified VertexData.
  27309. */
  27310. VertexData.prototype.merge = function (other) {
  27311. if (other.indices) {
  27312. if (!this.indices) {
  27313. this.indices = [];
  27314. }
  27315. var offset = this.positions ? this.positions.length / 3 : 0;
  27316. for (var index = 0; index < other.indices.length; index++) {
  27317. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  27318. this.indices.push(other.indices[index] + offset);
  27319. }
  27320. }
  27321. this.positions = this._mergeElement(this.positions, other.positions);
  27322. var count = this.positions.length / 3;
  27323. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  27324. this.tangents = this._mergeElement(this.tangents, other.tangents, count * 4);
  27325. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  27326. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  27327. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  27328. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  27329. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  27330. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  27331. this.colors = this._mergeElement(this.colors, other.colors, count * 4);
  27332. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  27333. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  27334. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  27335. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  27336. return this;
  27337. };
  27338. VertexData.prototype._mergeElement = function (source, other, length) {
  27339. if (length === void 0) { length = 0; }
  27340. if (!other && !source) {
  27341. return null;
  27342. }
  27343. if (!other) {
  27344. return this._mergeElement(source, new Float32Array(source.length), length);
  27345. }
  27346. if (!source) {
  27347. if (length === 0 || length === other.length) {
  27348. return other;
  27349. }
  27350. return this._mergeElement(new Float32Array(length - other.length), other, length);
  27351. }
  27352. var len = other.length + source.length;
  27353. var isSrcTypedArray = source instanceof Float32Array;
  27354. var isOthTypedArray = other instanceof Float32Array;
  27355. // use non-loop method when the source is Float32Array
  27356. if (isSrcTypedArray) {
  27357. var ret32 = new Float32Array(len);
  27358. ret32.set(source);
  27359. ret32.set(other, source.length);
  27360. return ret32;
  27361. // source is number[], when other is also use concat
  27362. }
  27363. else if (!isOthTypedArray) {
  27364. return source.concat(other);
  27365. // source is a number[], but other is a Float32Array, loop required
  27366. }
  27367. else {
  27368. var ret = source.slice(0); // copy source to a separate array
  27369. for (var i = 0, len = other.length; i < len; i++) {
  27370. ret.push(other[i]);
  27371. }
  27372. return ret;
  27373. }
  27374. };
  27375. /**
  27376. * Serializes the VertexData.
  27377. * Returns a serialized object.
  27378. */
  27379. VertexData.prototype.serialize = function () {
  27380. var serializationObject = this.serialize();
  27381. if (this.positions) {
  27382. serializationObject.positions = this.positions;
  27383. }
  27384. if (this.normals) {
  27385. serializationObject.normals = this.normals;
  27386. }
  27387. if (this.tangents) {
  27388. serializationObject.tangents = this.tangents;
  27389. }
  27390. if (this.uvs) {
  27391. serializationObject.uvs = this.uvs;
  27392. }
  27393. if (this.uvs2) {
  27394. serializationObject.uvs2 = this.uvs2;
  27395. }
  27396. if (this.uvs3) {
  27397. serializationObject.uvs3 = this.uvs3;
  27398. }
  27399. if (this.uvs4) {
  27400. serializationObject.uvs4 = this.uvs4;
  27401. }
  27402. if (this.uvs5) {
  27403. serializationObject.uvs5 = this.uvs5;
  27404. }
  27405. if (this.uvs6) {
  27406. serializationObject.uvs6 = this.uvs6;
  27407. }
  27408. if (this.colors) {
  27409. serializationObject.colors = this.colors;
  27410. }
  27411. if (this.matricesIndices) {
  27412. serializationObject.matricesIndices = this.matricesIndices;
  27413. serializationObject.matricesIndices._isExpanded = true;
  27414. }
  27415. if (this.matricesWeights) {
  27416. serializationObject.matricesWeights = this.matricesWeights;
  27417. }
  27418. if (this.matricesIndicesExtra) {
  27419. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  27420. serializationObject.matricesIndicesExtra._isExpanded = true;
  27421. }
  27422. if (this.matricesWeightsExtra) {
  27423. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  27424. }
  27425. serializationObject.indices = this.indices;
  27426. return serializationObject;
  27427. };
  27428. // Statics
  27429. /**
  27430. * Returns the object VertexData associated to the passed mesh.
  27431. */
  27432. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  27433. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  27434. };
  27435. /**
  27436. * Returns the object VertexData associated to the passed geometry.
  27437. */
  27438. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  27439. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  27440. };
  27441. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  27442. var result = new VertexData();
  27443. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27444. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  27445. }
  27446. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27447. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  27448. }
  27449. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  27450. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  27451. }
  27452. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27453. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  27454. }
  27455. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27456. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  27457. }
  27458. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27459. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  27460. }
  27461. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27462. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  27463. }
  27464. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27465. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  27466. }
  27467. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27468. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  27469. }
  27470. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27471. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  27472. }
  27473. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27474. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  27475. }
  27476. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27477. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  27478. }
  27479. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  27480. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  27481. }
  27482. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  27483. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  27484. }
  27485. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  27486. return result;
  27487. };
  27488. /**
  27489. * Creates the vertexData of the Ribbon.
  27490. */
  27491. VertexData.CreateRibbon = function (options) {
  27492. var pathArray = options.pathArray;
  27493. var closeArray = options.closeArray || false;
  27494. var closePath = options.closePath || false;
  27495. var invertUV = options.invertUV || false;
  27496. var defaultOffset = Math.floor(pathArray[0].length / 2);
  27497. var offset = options.offset || defaultOffset;
  27498. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  27499. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27500. var customUV = options.uvs;
  27501. var customColors = options.colors;
  27502. var positions = [];
  27503. var indices = [];
  27504. var normals = [];
  27505. var uvs = [];
  27506. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  27507. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  27508. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  27509. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  27510. var minlg; // minimal length among all paths from pathArray
  27511. var lg = []; // array of path lengths : nb of vertex per path
  27512. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  27513. var p; // path iterator
  27514. var i; // point iterator
  27515. var j; // point iterator
  27516. // if single path in pathArray
  27517. if (pathArray.length < 2) {
  27518. var ar1 = [];
  27519. var ar2 = [];
  27520. for (i = 0; i < pathArray[0].length - offset; i++) {
  27521. ar1.push(pathArray[0][i]);
  27522. ar2.push(pathArray[0][i + offset]);
  27523. }
  27524. pathArray = [ar1, ar2];
  27525. }
  27526. // positions and horizontal distances (u)
  27527. var idc = 0;
  27528. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  27529. var path;
  27530. var l;
  27531. minlg = pathArray[0].length;
  27532. var vectlg;
  27533. var dist;
  27534. for (p = 0; p < pathArray.length; p++) {
  27535. uTotalDistance[p] = 0;
  27536. us[p] = [0];
  27537. path = pathArray[p];
  27538. l = path.length;
  27539. minlg = (minlg < l) ? minlg : l;
  27540. j = 0;
  27541. while (j < l) {
  27542. positions.push(path[j].x, path[j].y, path[j].z);
  27543. if (j > 0) {
  27544. vectlg = path[j].subtract(path[j - 1]).length();
  27545. dist = vectlg + uTotalDistance[p];
  27546. us[p].push(dist);
  27547. uTotalDistance[p] = dist;
  27548. }
  27549. j++;
  27550. }
  27551. if (closePath) {
  27552. j--;
  27553. positions.push(path[0].x, path[0].y, path[0].z);
  27554. vectlg = path[j].subtract(path[0]).length();
  27555. dist = vectlg + uTotalDistance[p];
  27556. us[p].push(dist);
  27557. uTotalDistance[p] = dist;
  27558. }
  27559. lg[p] = l + closePathCorr;
  27560. idx[p] = idc;
  27561. idc += (l + closePathCorr);
  27562. }
  27563. // vertical distances (v)
  27564. var path1;
  27565. var path2;
  27566. var vertex1;
  27567. var vertex2;
  27568. for (i = 0; i < minlg + closePathCorr; i++) {
  27569. vTotalDistance[i] = 0;
  27570. vs[i] = [0];
  27571. for (p = 0; p < pathArray.length - 1; p++) {
  27572. path1 = pathArray[p];
  27573. path2 = pathArray[p + 1];
  27574. if (i === minlg) {
  27575. vertex1 = path1[0];
  27576. vertex2 = path2[0];
  27577. }
  27578. else {
  27579. vertex1 = path1[i];
  27580. vertex2 = path2[i];
  27581. }
  27582. vectlg = vertex2.subtract(vertex1).length();
  27583. dist = vectlg + vTotalDistance[i];
  27584. vs[i].push(dist);
  27585. vTotalDistance[i] = dist;
  27586. }
  27587. if (closeArray) {
  27588. path1 = pathArray[p];
  27589. path2 = pathArray[0];
  27590. if (i === minlg) {
  27591. vertex2 = path2[0];
  27592. }
  27593. vectlg = vertex2.subtract(vertex1).length();
  27594. dist = vectlg + vTotalDistance[i];
  27595. vTotalDistance[i] = dist;
  27596. }
  27597. }
  27598. // uvs
  27599. var u;
  27600. var v;
  27601. if (customUV) {
  27602. for (p = 0; p < customUV.length; p++) {
  27603. uvs.push(customUV[p].x, customUV[p].y);
  27604. }
  27605. }
  27606. else {
  27607. for (p = 0; p < pathArray.length; p++) {
  27608. for (i = 0; i < minlg + closePathCorr; i++) {
  27609. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  27610. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  27611. if (invertUV) {
  27612. uvs.push(v, u);
  27613. }
  27614. else {
  27615. uvs.push(u, v);
  27616. }
  27617. }
  27618. }
  27619. }
  27620. // indices
  27621. p = 0; // path index
  27622. var pi = 0; // positions array index
  27623. var l1 = lg[p] - 1; // path1 length
  27624. var l2 = lg[p + 1] - 1; // path2 length
  27625. var min = (l1 < l2) ? l1 : l2; // current path stop index
  27626. var shft = idx[1] - idx[0]; // shift
  27627. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  27628. while (pi <= min && p < path1nb) {
  27629. // 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
  27630. indices.push(pi, pi + shft, pi + 1);
  27631. indices.push(pi + shft + 1, pi + 1, pi + shft);
  27632. pi += 1;
  27633. if (pi === min) {
  27634. p++;
  27635. if (p === lg.length - 1) {
  27636. shft = idx[0] - idx[p];
  27637. l1 = lg[p] - 1;
  27638. l2 = lg[0] - 1;
  27639. }
  27640. else {
  27641. shft = idx[p + 1] - idx[p];
  27642. l1 = lg[p] - 1;
  27643. l2 = lg[p + 1] - 1;
  27644. }
  27645. pi = idx[p];
  27646. min = (l1 < l2) ? l1 + pi : l2 + pi;
  27647. }
  27648. }
  27649. // normals
  27650. VertexData.ComputeNormals(positions, indices, normals);
  27651. if (closePath) {
  27652. var indexFirst = 0;
  27653. var indexLast = 0;
  27654. for (p = 0; p < pathArray.length; p++) {
  27655. indexFirst = idx[p] * 3;
  27656. if (p + 1 < pathArray.length) {
  27657. indexLast = (idx[p + 1] - 1) * 3;
  27658. }
  27659. else {
  27660. indexLast = normals.length - 3;
  27661. }
  27662. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  27663. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  27664. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  27665. normals[indexLast] = normals[indexFirst];
  27666. normals[indexLast + 1] = normals[indexFirst + 1];
  27667. normals[indexLast + 2] = normals[indexFirst + 2];
  27668. }
  27669. }
  27670. // sides
  27671. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27672. // Colors
  27673. if (customColors) {
  27674. var colors = new Float32Array(customColors.length * 4);
  27675. for (var c = 0; c < customColors.length; c++) {
  27676. colors[c * 4] = customColors[c].r;
  27677. colors[c * 4 + 1] = customColors[c].g;
  27678. colors[c * 4 + 2] = customColors[c].b;
  27679. colors[c * 4 + 3] = customColors[c].a;
  27680. }
  27681. }
  27682. // Result
  27683. var vertexData = new VertexData();
  27684. var positions32 = new Float32Array(positions);
  27685. var normals32 = new Float32Array(normals);
  27686. var uvs32 = new Float32Array(uvs);
  27687. vertexData.indices = indices;
  27688. vertexData.positions = positions32;
  27689. vertexData.normals = normals32;
  27690. vertexData.uvs = uvs32;
  27691. if (customColors) {
  27692. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  27693. }
  27694. if (closePath) {
  27695. vertexData._idx = idx;
  27696. }
  27697. return vertexData;
  27698. };
  27699. /**
  27700. * Creates the VertexData of the Box.
  27701. */
  27702. VertexData.CreateBox = function (options) {
  27703. var normalsSource = [
  27704. new BABYLON.Vector3(0, 0, 1),
  27705. new BABYLON.Vector3(0, 0, -1),
  27706. new BABYLON.Vector3(1, 0, 0),
  27707. new BABYLON.Vector3(-1, 0, 0),
  27708. new BABYLON.Vector3(0, 1, 0),
  27709. new BABYLON.Vector3(0, -1, 0)
  27710. ];
  27711. var indices = [];
  27712. var positions = [];
  27713. var normals = [];
  27714. var uvs = [];
  27715. var width = options.width || options.size || 1;
  27716. var height = options.height || options.size || 1;
  27717. var depth = options.depth || options.size || 1;
  27718. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27719. var faceUV = options.faceUV || new Array(6);
  27720. var faceColors = options.faceColors;
  27721. var colors = [];
  27722. // default face colors and UV if undefined
  27723. for (var f = 0; f < 6; f++) {
  27724. if (faceUV[f] === undefined) {
  27725. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27726. }
  27727. if (faceColors && faceColors[f] === undefined) {
  27728. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27729. }
  27730. }
  27731. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  27732. // Create each face in turn.
  27733. for (var index = 0; index < normalsSource.length; index++) {
  27734. var normal = normalsSource[index];
  27735. // Get two vectors perpendicular to the face normal and to each other.
  27736. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  27737. var side2 = BABYLON.Vector3.Cross(normal, side1);
  27738. // Six indices (two triangles) per face.
  27739. var verticesLength = positions.length / 3;
  27740. indices.push(verticesLength);
  27741. indices.push(verticesLength + 1);
  27742. indices.push(verticesLength + 2);
  27743. indices.push(verticesLength);
  27744. indices.push(verticesLength + 2);
  27745. indices.push(verticesLength + 3);
  27746. // Four vertices per face.
  27747. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  27748. positions.push(vertex.x, vertex.y, vertex.z);
  27749. normals.push(normal.x, normal.y, normal.z);
  27750. uvs.push(faceUV[index].z, faceUV[index].w);
  27751. if (faceColors) {
  27752. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27753. }
  27754. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  27755. positions.push(vertex.x, vertex.y, vertex.z);
  27756. normals.push(normal.x, normal.y, normal.z);
  27757. uvs.push(faceUV[index].x, faceUV[index].w);
  27758. if (faceColors) {
  27759. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27760. }
  27761. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  27762. positions.push(vertex.x, vertex.y, vertex.z);
  27763. normals.push(normal.x, normal.y, normal.z);
  27764. uvs.push(faceUV[index].x, faceUV[index].y);
  27765. if (faceColors) {
  27766. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27767. }
  27768. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  27769. positions.push(vertex.x, vertex.y, vertex.z);
  27770. normals.push(normal.x, normal.y, normal.z);
  27771. uvs.push(faceUV[index].z, faceUV[index].y);
  27772. if (faceColors) {
  27773. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27774. }
  27775. }
  27776. // sides
  27777. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27778. // Result
  27779. var vertexData = new VertexData();
  27780. vertexData.indices = indices;
  27781. vertexData.positions = positions;
  27782. vertexData.normals = normals;
  27783. vertexData.uvs = uvs;
  27784. if (faceColors) {
  27785. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27786. vertexData.colors = totalColors;
  27787. }
  27788. return vertexData;
  27789. };
  27790. /**
  27791. * Creates the VertexData of the Sphere.
  27792. */
  27793. VertexData.CreateSphere = function (options) {
  27794. var segments = options.segments || 32;
  27795. var diameterX = options.diameterX || options.diameter || 1;
  27796. var diameterY = options.diameterY || options.diameter || 1;
  27797. var diameterZ = options.diameterZ || options.diameter || 1;
  27798. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27799. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  27800. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27801. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  27802. var totalZRotationSteps = 2 + segments;
  27803. var totalYRotationSteps = 2 * totalZRotationSteps;
  27804. var indices = [];
  27805. var positions = [];
  27806. var normals = [];
  27807. var uvs = [];
  27808. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  27809. var normalizedZ = zRotationStep / totalZRotationSteps;
  27810. var angleZ = normalizedZ * Math.PI * slice;
  27811. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  27812. var normalizedY = yRotationStep / totalYRotationSteps;
  27813. var angleY = normalizedY * Math.PI * 2 * arc;
  27814. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  27815. var rotationY = BABYLON.Matrix.RotationY(angleY);
  27816. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  27817. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  27818. var vertex = complete.multiply(radius);
  27819. var normal = complete.divide(radius).normalize();
  27820. positions.push(vertex.x, vertex.y, vertex.z);
  27821. normals.push(normal.x, normal.y, normal.z);
  27822. uvs.push(normalizedY, normalizedZ);
  27823. }
  27824. if (zRotationStep > 0) {
  27825. var verticesCount = positions.length / 3;
  27826. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  27827. indices.push((firstIndex));
  27828. indices.push((firstIndex + 1));
  27829. indices.push(firstIndex + totalYRotationSteps + 1);
  27830. indices.push((firstIndex + totalYRotationSteps + 1));
  27831. indices.push((firstIndex + 1));
  27832. indices.push((firstIndex + totalYRotationSteps + 2));
  27833. }
  27834. }
  27835. }
  27836. // Sides
  27837. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27838. // Result
  27839. var vertexData = new VertexData();
  27840. vertexData.indices = indices;
  27841. vertexData.positions = positions;
  27842. vertexData.normals = normals;
  27843. vertexData.uvs = uvs;
  27844. return vertexData;
  27845. };
  27846. /**
  27847. * Creates the VertexData of the Cylinder or Cone.
  27848. */
  27849. VertexData.CreateCylinder = function (options) {
  27850. var height = options.height || 2;
  27851. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  27852. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  27853. var tessellation = options.tessellation || 24;
  27854. var subdivisions = options.subdivisions || 1;
  27855. var hasRings = options.hasRings;
  27856. var enclose = options.enclose;
  27857. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27858. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27859. var faceUV = options.faceUV || new Array(3);
  27860. var faceColors = options.faceColors;
  27861. // default face colors and UV if undefined
  27862. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  27863. var ringNb = (hasRings) ? subdivisions : 1;
  27864. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  27865. var f;
  27866. for (f = 0; f < surfaceNb; f++) {
  27867. if (faceColors && faceColors[f] === undefined) {
  27868. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27869. }
  27870. }
  27871. for (f = 0; f < surfaceNb; f++) {
  27872. if (faceUV && faceUV[f] === undefined) {
  27873. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27874. }
  27875. }
  27876. var indices = new Array();
  27877. var positions = new Array();
  27878. var normals = new Array();
  27879. var uvs = new Array();
  27880. var colors = new Array();
  27881. var angle_step = Math.PI * 2 * arc / tessellation;
  27882. var angle;
  27883. var h;
  27884. var radius;
  27885. var tan = (diameterBottom - diameterTop) / 2 / height;
  27886. var ringVertex = BABYLON.Vector3.Zero();
  27887. var ringNormal = BABYLON.Vector3.Zero();
  27888. var ringFirstVertex = BABYLON.Vector3.Zero();
  27889. var ringFirstNormal = BABYLON.Vector3.Zero();
  27890. var quadNormal = BABYLON.Vector3.Zero();
  27891. var Y = BABYLON.Axis.Y;
  27892. // positions, normals, uvs
  27893. var i;
  27894. var j;
  27895. var r;
  27896. var ringIdx = 1;
  27897. var s = 1; // surface index
  27898. var cs = 0;
  27899. var v = 0;
  27900. for (i = 0; i <= subdivisions; i++) {
  27901. h = i / subdivisions;
  27902. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  27903. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  27904. for (r = 0; r < ringIdx; r++) {
  27905. if (hasRings) {
  27906. s += r;
  27907. }
  27908. if (enclose) {
  27909. s += 2 * r;
  27910. }
  27911. for (j = 0; j <= tessellation; j++) {
  27912. angle = j * angle_step;
  27913. // position
  27914. ringVertex.x = Math.cos(-angle) * radius;
  27915. ringVertex.y = -height / 2 + h * height;
  27916. ringVertex.z = Math.sin(-angle) * radius;
  27917. // normal
  27918. if (diameterTop === 0 && i === subdivisions) {
  27919. // if no top cap, reuse former normals
  27920. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  27921. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  27922. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  27923. }
  27924. else {
  27925. ringNormal.x = ringVertex.x;
  27926. ringNormal.z = ringVertex.z;
  27927. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  27928. ringNormal.normalize();
  27929. }
  27930. // keep first ring vertex values for enclose
  27931. if (j === 0) {
  27932. ringFirstVertex.copyFrom(ringVertex);
  27933. ringFirstNormal.copyFrom(ringNormal);
  27934. }
  27935. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27936. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27937. if (hasRings) {
  27938. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  27939. }
  27940. else {
  27941. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  27942. }
  27943. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  27944. if (faceColors) {
  27945. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  27946. }
  27947. }
  27948. // if enclose, add four vertices and their dedicated normals
  27949. if (arc !== 1 && enclose) {
  27950. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27951. positions.push(0, ringVertex.y, 0);
  27952. positions.push(0, ringVertex.y, 0);
  27953. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  27954. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  27955. quadNormal.normalize();
  27956. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27957. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  27958. quadNormal.normalize();
  27959. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27960. if (hasRings) {
  27961. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  27962. }
  27963. else {
  27964. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  27965. }
  27966. uvs.push(faceUV[s + 1].x, v);
  27967. uvs.push(faceUV[s + 1].z, v);
  27968. if (hasRings) {
  27969. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  27970. }
  27971. else {
  27972. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  27973. }
  27974. uvs.push(faceUV[s + 2].x, v);
  27975. uvs.push(faceUV[s + 2].z, v);
  27976. if (faceColors) {
  27977. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27978. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27979. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27980. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27981. }
  27982. }
  27983. if (cs !== s) {
  27984. cs = s;
  27985. }
  27986. }
  27987. }
  27988. // indices
  27989. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  27990. var s;
  27991. i = 0;
  27992. for (s = 0; s < subdivisions; s++) {
  27993. for (j = 0; j < tessellation; j++) {
  27994. var i0 = i * (e + 1) + j;
  27995. var i1 = (i + 1) * (e + 1) + j;
  27996. var i2 = i * (e + 1) + (j + 1);
  27997. var i3 = (i + 1) * (e + 1) + (j + 1);
  27998. indices.push(i0, i1, i2);
  27999. indices.push(i3, i2, i1);
  28000. }
  28001. if (arc !== 1 && enclose) {
  28002. indices.push(i0 + 2, i1 + 2, i2 + 2);
  28003. indices.push(i3 + 2, i2 + 2, i1 + 2);
  28004. indices.push(i0 + 4, i1 + 4, i2 + 4);
  28005. indices.push(i3 + 4, i2 + 4, i1 + 4);
  28006. }
  28007. i = (hasRings) ? (i + 2) : (i + 1);
  28008. }
  28009. // Caps
  28010. var createCylinderCap = function (isTop) {
  28011. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  28012. if (radius === 0) {
  28013. return;
  28014. }
  28015. // Cap positions, normals & uvs
  28016. var angle;
  28017. var circleVector;
  28018. var i;
  28019. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  28020. var c;
  28021. if (faceColors) {
  28022. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  28023. }
  28024. // cap center
  28025. var vbase = positions.length / 3;
  28026. var offset = isTop ? height / 2 : -height / 2;
  28027. var center = new BABYLON.Vector3(0, offset, 0);
  28028. positions.push(center.x, center.y, center.z);
  28029. normals.push(0, isTop ? 1 : -1, 0);
  28030. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  28031. if (faceColors) {
  28032. colors.push(c.r, c.g, c.b, c.a);
  28033. }
  28034. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  28035. for (i = 0; i <= tessellation; i++) {
  28036. angle = Math.PI * 2 * i * arc / tessellation;
  28037. var cos = Math.cos(-angle);
  28038. var sin = Math.sin(-angle);
  28039. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  28040. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  28041. positions.push(circleVector.x, circleVector.y, circleVector.z);
  28042. normals.push(0, isTop ? 1 : -1, 0);
  28043. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  28044. if (faceColors) {
  28045. colors.push(c.r, c.g, c.b, c.a);
  28046. }
  28047. }
  28048. // Cap indices
  28049. for (i = 0; i < tessellation; i++) {
  28050. if (!isTop) {
  28051. indices.push(vbase);
  28052. indices.push(vbase + (i + 1));
  28053. indices.push(vbase + (i + 2));
  28054. }
  28055. else {
  28056. indices.push(vbase);
  28057. indices.push(vbase + (i + 2));
  28058. indices.push(vbase + (i + 1));
  28059. }
  28060. }
  28061. };
  28062. // add caps to geometry
  28063. createCylinderCap(false);
  28064. createCylinderCap(true);
  28065. // Sides
  28066. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28067. var vertexData = new VertexData();
  28068. vertexData.indices = indices;
  28069. vertexData.positions = positions;
  28070. vertexData.normals = normals;
  28071. vertexData.uvs = uvs;
  28072. if (faceColors) {
  28073. vertexData.colors = colors;
  28074. }
  28075. return vertexData;
  28076. };
  28077. /**
  28078. * Creates the VertexData of the Torus.
  28079. */
  28080. VertexData.CreateTorus = function (options) {
  28081. var indices = [];
  28082. var positions = [];
  28083. var normals = [];
  28084. var uvs = [];
  28085. var diameter = options.diameter || 1;
  28086. var thickness = options.thickness || 0.5;
  28087. var tessellation = options.tessellation || 16;
  28088. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28089. var stride = tessellation + 1;
  28090. for (var i = 0; i <= tessellation; i++) {
  28091. var u = i / tessellation;
  28092. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  28093. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  28094. for (var j = 0; j <= tessellation; j++) {
  28095. var v = 1 - j / tessellation;
  28096. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  28097. var dx = Math.cos(innerAngle);
  28098. var dy = Math.sin(innerAngle);
  28099. // Create a vertex.
  28100. var normal = new BABYLON.Vector3(dx, dy, 0);
  28101. var position = normal.scale(thickness / 2);
  28102. var textureCoordinate = new BABYLON.Vector2(u, v);
  28103. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  28104. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  28105. positions.push(position.x, position.y, position.z);
  28106. normals.push(normal.x, normal.y, normal.z);
  28107. uvs.push(textureCoordinate.x, textureCoordinate.y);
  28108. // And create indices for two triangles.
  28109. var nextI = (i + 1) % stride;
  28110. var nextJ = (j + 1) % stride;
  28111. indices.push(i * stride + j);
  28112. indices.push(i * stride + nextJ);
  28113. indices.push(nextI * stride + j);
  28114. indices.push(i * stride + nextJ);
  28115. indices.push(nextI * stride + nextJ);
  28116. indices.push(nextI * stride + j);
  28117. }
  28118. }
  28119. // Sides
  28120. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28121. // Result
  28122. var vertexData = new VertexData();
  28123. vertexData.indices = indices;
  28124. vertexData.positions = positions;
  28125. vertexData.normals = normals;
  28126. vertexData.uvs = uvs;
  28127. return vertexData;
  28128. };
  28129. /**
  28130. * Creates the VertexData of the LineSystem.
  28131. */
  28132. VertexData.CreateLineSystem = function (options) {
  28133. var indices = [];
  28134. var positions = [];
  28135. var lines = options.lines;
  28136. var idx = 0;
  28137. for (var l = 0; l < lines.length; l++) {
  28138. var points = lines[l];
  28139. for (var index = 0; index < points.length; index++) {
  28140. positions.push(points[index].x, points[index].y, points[index].z);
  28141. if (index > 0) {
  28142. indices.push(idx - 1);
  28143. indices.push(idx);
  28144. }
  28145. idx++;
  28146. }
  28147. }
  28148. var vertexData = new VertexData();
  28149. vertexData.indices = indices;
  28150. vertexData.positions = positions;
  28151. return vertexData;
  28152. };
  28153. /**
  28154. * Create the VertexData of the DashedLines.
  28155. */
  28156. VertexData.CreateDashedLines = function (options) {
  28157. var dashSize = options.dashSize || 3;
  28158. var gapSize = options.gapSize || 1;
  28159. var dashNb = options.dashNb || 200;
  28160. var points = options.points;
  28161. var positions = new Array();
  28162. var indices = new Array();
  28163. var curvect = BABYLON.Vector3.Zero();
  28164. var lg = 0;
  28165. var nb = 0;
  28166. var shft = 0;
  28167. var dashshft = 0;
  28168. var curshft = 0;
  28169. var idx = 0;
  28170. var i = 0;
  28171. for (i = 0; i < points.length - 1; i++) {
  28172. points[i + 1].subtractToRef(points[i], curvect);
  28173. lg += curvect.length();
  28174. }
  28175. shft = lg / dashNb;
  28176. dashshft = dashSize * shft / (dashSize + gapSize);
  28177. for (i = 0; i < points.length - 1; i++) {
  28178. points[i + 1].subtractToRef(points[i], curvect);
  28179. nb = Math.floor(curvect.length() / shft);
  28180. curvect.normalize();
  28181. for (var j = 0; j < nb; j++) {
  28182. curshft = shft * j;
  28183. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  28184. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  28185. indices.push(idx, idx + 1);
  28186. idx += 2;
  28187. }
  28188. }
  28189. // Result
  28190. var vertexData = new VertexData();
  28191. vertexData.positions = positions;
  28192. vertexData.indices = indices;
  28193. return vertexData;
  28194. };
  28195. /**
  28196. * Creates the VertexData of the Ground.
  28197. */
  28198. VertexData.CreateGround = function (options) {
  28199. var indices = [];
  28200. var positions = [];
  28201. var normals = [];
  28202. var uvs = [];
  28203. var row, col;
  28204. var width = options.width || 1;
  28205. var height = options.height || 1;
  28206. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  28207. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  28208. for (row = 0; row <= subdivisionsY; row++) {
  28209. for (col = 0; col <= subdivisionsX; col++) {
  28210. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  28211. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28212. positions.push(position.x, position.y, position.z);
  28213. normals.push(normal.x, normal.y, normal.z);
  28214. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  28215. }
  28216. }
  28217. for (row = 0; row < subdivisionsY; row++) {
  28218. for (col = 0; col < subdivisionsX; col++) {
  28219. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  28220. indices.push(col + 1 + row * (subdivisionsX + 1));
  28221. indices.push(col + row * (subdivisionsX + 1));
  28222. indices.push(col + (row + 1) * (subdivisionsX + 1));
  28223. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  28224. indices.push(col + row * (subdivisionsX + 1));
  28225. }
  28226. }
  28227. // Result
  28228. var vertexData = new VertexData();
  28229. vertexData.indices = indices;
  28230. vertexData.positions = positions;
  28231. vertexData.normals = normals;
  28232. vertexData.uvs = uvs;
  28233. return vertexData;
  28234. };
  28235. /**
  28236. * Creates the VertexData of the TiledGround.
  28237. */
  28238. VertexData.CreateTiledGround = function (options) {
  28239. var xmin = options.xmin || -1.0;
  28240. var zmin = options.zmin || -1.0;
  28241. var xmax = options.xmax || 1.0;
  28242. var zmax = options.zmax || 1.0;
  28243. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  28244. var precision = options.precision || { w: 1, h: 1 };
  28245. var indices = new Array();
  28246. var positions = new Array();
  28247. var normals = new Array();
  28248. var uvs = new Array();
  28249. var row, col, tileRow, tileCol;
  28250. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  28251. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  28252. precision.w = (precision.w < 1) ? 1 : precision.w;
  28253. precision.h = (precision.h < 1) ? 1 : precision.h;
  28254. var tileSize = {
  28255. 'w': (xmax - xmin) / subdivisions.w,
  28256. 'h': (zmax - zmin) / subdivisions.h
  28257. };
  28258. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  28259. // Indices
  28260. var base = positions.length / 3;
  28261. var rowLength = precision.w + 1;
  28262. for (row = 0; row < precision.h; row++) {
  28263. for (col = 0; col < precision.w; col++) {
  28264. var square = [
  28265. base + col + row * rowLength,
  28266. base + (col + 1) + row * rowLength,
  28267. base + (col + 1) + (row + 1) * rowLength,
  28268. base + col + (row + 1) * rowLength
  28269. ];
  28270. indices.push(square[1]);
  28271. indices.push(square[2]);
  28272. indices.push(square[3]);
  28273. indices.push(square[0]);
  28274. indices.push(square[1]);
  28275. indices.push(square[3]);
  28276. }
  28277. }
  28278. // Position, normals and uvs
  28279. var position = BABYLON.Vector3.Zero();
  28280. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28281. for (row = 0; row <= precision.h; row++) {
  28282. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  28283. for (col = 0; col <= precision.w; col++) {
  28284. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  28285. position.y = 0;
  28286. positions.push(position.x, position.y, position.z);
  28287. normals.push(normal.x, normal.y, normal.z);
  28288. uvs.push(col / precision.w, row / precision.h);
  28289. }
  28290. }
  28291. }
  28292. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  28293. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  28294. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  28295. }
  28296. }
  28297. // Result
  28298. var vertexData = new VertexData();
  28299. vertexData.indices = indices;
  28300. vertexData.positions = positions;
  28301. vertexData.normals = normals;
  28302. vertexData.uvs = uvs;
  28303. return vertexData;
  28304. };
  28305. /**
  28306. * Creates the VertexData of the Ground designed from a heightmap.
  28307. */
  28308. VertexData.CreateGroundFromHeightMap = function (options) {
  28309. var indices = [];
  28310. var positions = [];
  28311. var normals = [];
  28312. var uvs = [];
  28313. var row, col;
  28314. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  28315. // Vertices
  28316. for (row = 0; row <= options.subdivisions; row++) {
  28317. for (col = 0; col <= options.subdivisions; col++) {
  28318. 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));
  28319. // Compute height
  28320. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  28321. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  28322. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  28323. var r = options.buffer[pos] / 255.0;
  28324. var g = options.buffer[pos + 1] / 255.0;
  28325. var b = options.buffer[pos + 2] / 255.0;
  28326. var gradient = r * filter.r + g * filter.g + b * filter.b;
  28327. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  28328. // Add vertex
  28329. positions.push(position.x, position.y, position.z);
  28330. normals.push(0, 0, 0);
  28331. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  28332. }
  28333. }
  28334. // Indices
  28335. for (row = 0; row < options.subdivisions; row++) {
  28336. for (col = 0; col < options.subdivisions; col++) {
  28337. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28338. indices.push(col + 1 + row * (options.subdivisions + 1));
  28339. indices.push(col + row * (options.subdivisions + 1));
  28340. indices.push(col + (row + 1) * (options.subdivisions + 1));
  28341. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28342. indices.push(col + row * (options.subdivisions + 1));
  28343. }
  28344. }
  28345. // Normals
  28346. VertexData.ComputeNormals(positions, indices, normals);
  28347. // Result
  28348. var vertexData = new VertexData();
  28349. vertexData.indices = indices;
  28350. vertexData.positions = positions;
  28351. vertexData.normals = normals;
  28352. vertexData.uvs = uvs;
  28353. return vertexData;
  28354. };
  28355. /**
  28356. * Creates the VertexData of the Plane.
  28357. */
  28358. VertexData.CreatePlane = function (options) {
  28359. var indices = [];
  28360. var positions = [];
  28361. var normals = [];
  28362. var uvs = [];
  28363. var width = options.width || options.size || 1;
  28364. var height = options.height || options.size || 1;
  28365. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28366. // Vertices
  28367. var halfWidth = width / 2.0;
  28368. var halfHeight = height / 2.0;
  28369. positions.push(-halfWidth, -halfHeight, 0);
  28370. normals.push(0, 0, -1.0);
  28371. uvs.push(0.0, 0.0);
  28372. positions.push(halfWidth, -halfHeight, 0);
  28373. normals.push(0, 0, -1.0);
  28374. uvs.push(1.0, 0.0);
  28375. positions.push(halfWidth, halfHeight, 0);
  28376. normals.push(0, 0, -1.0);
  28377. uvs.push(1.0, 1.0);
  28378. positions.push(-halfWidth, halfHeight, 0);
  28379. normals.push(0, 0, -1.0);
  28380. uvs.push(0.0, 1.0);
  28381. // Indices
  28382. indices.push(0);
  28383. indices.push(1);
  28384. indices.push(2);
  28385. indices.push(0);
  28386. indices.push(2);
  28387. indices.push(3);
  28388. // Sides
  28389. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28390. // Result
  28391. var vertexData = new VertexData();
  28392. vertexData.indices = indices;
  28393. vertexData.positions = positions;
  28394. vertexData.normals = normals;
  28395. vertexData.uvs = uvs;
  28396. return vertexData;
  28397. };
  28398. /**
  28399. * Creates the VertexData of the Disc or regular Polygon.
  28400. */
  28401. VertexData.CreateDisc = function (options) {
  28402. var positions = new Array();
  28403. var indices = new Array();
  28404. var normals = new Array();
  28405. var uvs = new Array();
  28406. var radius = options.radius || 0.5;
  28407. var tessellation = options.tessellation || 64;
  28408. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28409. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28410. // positions and uvs
  28411. positions.push(0, 0, 0); // disc center first
  28412. uvs.push(0.5, 0.5);
  28413. var theta = Math.PI * 2 * arc;
  28414. var step = theta / tessellation;
  28415. for (var a = 0; a < theta; a += step) {
  28416. var x = Math.cos(a);
  28417. var y = Math.sin(a);
  28418. var u = (x + 1) / 2;
  28419. var v = (1 - y) / 2;
  28420. positions.push(radius * x, radius * y, 0);
  28421. uvs.push(u, v);
  28422. }
  28423. if (arc === 1) {
  28424. positions.push(positions[3], positions[4], positions[5]); // close the circle
  28425. uvs.push(uvs[2], uvs[3]);
  28426. }
  28427. //indices
  28428. var vertexNb = positions.length / 3;
  28429. for (var i = 1; i < vertexNb - 1; i++) {
  28430. indices.push(i + 1, 0, i);
  28431. }
  28432. // result
  28433. VertexData.ComputeNormals(positions, indices, normals);
  28434. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28435. var vertexData = new VertexData();
  28436. vertexData.indices = indices;
  28437. vertexData.positions = positions;
  28438. vertexData.normals = normals;
  28439. vertexData.uvs = uvs;
  28440. return vertexData;
  28441. };
  28442. /**
  28443. * Re-creates the VertexData of the Polygon for sideOrientation.
  28444. */
  28445. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  28446. var faceUV = fUV || new Array(3);
  28447. var faceColors = fColors;
  28448. var colors = [];
  28449. // default face colors and UV if undefined
  28450. for (var f = 0; f < 3; f++) {
  28451. if (faceUV[f] === undefined) {
  28452. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28453. }
  28454. if (faceColors && faceColors[f] === undefined) {
  28455. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28456. }
  28457. }
  28458. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28459. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28460. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28461. var indices = polygon.getIndices();
  28462. // set face colours and textures
  28463. var idx = 0;
  28464. var face = 0;
  28465. for (var index = 0; index < normals.length; index += 3) {
  28466. //Edge Face no. 1
  28467. if (Math.abs(normals[index + 1]) < 0.001) {
  28468. face = 1;
  28469. }
  28470. //Top Face no. 0
  28471. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  28472. face = 0;
  28473. }
  28474. //Bottom Face no. 2
  28475. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  28476. face = 2;
  28477. }
  28478. idx = index / 3;
  28479. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  28480. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  28481. if (faceColors) {
  28482. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  28483. }
  28484. }
  28485. // sides
  28486. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  28487. // Result
  28488. var vertexData = new VertexData();
  28489. vertexData.indices = indices;
  28490. vertexData.positions = positions;
  28491. vertexData.normals = normals;
  28492. vertexData.uvs = uvs;
  28493. if (faceColors) {
  28494. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28495. vertexData.colors = totalColors;
  28496. }
  28497. return vertexData;
  28498. };
  28499. /**
  28500. * Creates the VertexData of the IcoSphere.
  28501. */
  28502. VertexData.CreateIcoSphere = function (options) {
  28503. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28504. var radius = options.radius || 1;
  28505. var flat = (options.flat === undefined) ? true : options.flat;
  28506. var subdivisions = options.subdivisions || 4;
  28507. var radiusX = options.radiusX || radius;
  28508. var radiusY = options.radiusY || radius;
  28509. var radiusZ = options.radiusZ || radius;
  28510. var t = (1 + Math.sqrt(5)) / 2;
  28511. // 12 vertex x,y,z
  28512. var ico_vertices = [
  28513. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  28514. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  28515. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  28516. ];
  28517. // index of 3 vertex makes a face of icopshere
  28518. var ico_indices = [
  28519. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  28520. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  28521. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  28522. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  28523. ];
  28524. // vertex for uv have aliased position, not for UV
  28525. var vertices_unalias_id = [
  28526. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  28527. // vertex alias
  28528. 0,
  28529. 2,
  28530. 3,
  28531. 3,
  28532. 3,
  28533. 4,
  28534. 7,
  28535. 8,
  28536. 9,
  28537. 9,
  28538. 10,
  28539. 11 // 23: B + 12
  28540. ];
  28541. // uv as integer step (not pixels !)
  28542. var ico_vertexuv = [
  28543. 5, 1, 3, 1, 6, 4, 0, 0,
  28544. 5, 3, 4, 2, 2, 2, 4, 0,
  28545. 2, 0, 1, 1, 6, 0, 6, 2,
  28546. // vertex alias (for same vertex on different faces)
  28547. 0, 4,
  28548. 3, 3,
  28549. 4, 4,
  28550. 3, 1,
  28551. 4, 2,
  28552. 4, 4,
  28553. 0, 2,
  28554. 1, 1,
  28555. 2, 2,
  28556. 3, 3,
  28557. 1, 3,
  28558. 2, 4 // 23: B + 12
  28559. ];
  28560. // Vertices[0, 1, ...9, A, B] : position on UV plane
  28561. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  28562. // First island of uv mapping
  28563. // v = 4h 3+ 2
  28564. // v = 3h 9+ 4
  28565. // v = 2h 9+ 5 B
  28566. // v = 1h 9 1 0
  28567. // v = 0h 3 8 7 A
  28568. // u = 0 1 2 3 4 5 6 *a
  28569. // Second island of uv mapping
  28570. // v = 4h 0+ B+ 4+
  28571. // v = 3h A+ 2+
  28572. // v = 2h 7+ 6 3+
  28573. // v = 1h 8+ 3+
  28574. // v = 0h
  28575. // u = 0 1 2 3 4 5 6 *a
  28576. // Face layout on texture UV mapping
  28577. // ============
  28578. // \ 4 /\ 16 / ======
  28579. // \ / \ / /\ 11 /
  28580. // \/ 7 \/ / \ /
  28581. // ======= / 10 \/
  28582. // /\ 17 /\ =======
  28583. // / \ / \ \ 15 /\
  28584. // / 8 \/ 12 \ \ / \
  28585. // ============ \/ 6 \
  28586. // \ 18 /\ ============
  28587. // \ / \ \ 5 /\ 0 /
  28588. // \/ 13 \ \ / \ /
  28589. // ======= \/ 1 \/
  28590. // =============
  28591. // /\ 19 /\ 2 /\
  28592. // / \ / \ / \
  28593. // / 14 \/ 9 \/ 3 \
  28594. // ===================
  28595. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  28596. var ustep = 138 / 1024;
  28597. var vstep = 239 / 1024;
  28598. var uoffset = 60 / 1024;
  28599. var voffset = 26 / 1024;
  28600. // Second island should have margin, not to touch the first island
  28601. // avoid any borderline artefact in pixel rounding
  28602. var island_u_offset = -40 / 1024;
  28603. var island_v_offset = +20 / 1024;
  28604. // face is either island 0 or 1 :
  28605. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  28606. var island = [
  28607. 0, 0, 0, 0, 1,
  28608. 0, 0, 1, 1, 0,
  28609. 0, 0, 1, 1, 0,
  28610. 0, 1, 1, 1, 0 // 15 - 19
  28611. ];
  28612. var indices = new Array();
  28613. var positions = new Array();
  28614. var normals = new Array();
  28615. var uvs = new Array();
  28616. var current_indice = 0;
  28617. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  28618. var face_vertex_pos = new Array(3);
  28619. var face_vertex_uv = new Array(3);
  28620. var v012;
  28621. for (v012 = 0; v012 < 3; v012++) {
  28622. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  28623. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  28624. }
  28625. // create all with normals
  28626. for (var face = 0; face < 20; face++) {
  28627. // 3 vertex per face
  28628. for (v012 = 0; v012 < 3; v012++) {
  28629. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  28630. var v_id = ico_indices[3 * face + v012];
  28631. // vertex have 3D position (x,y,z)
  28632. 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]);
  28633. // Normalize to get normal, then scale to radius
  28634. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  28635. // uv Coordinates from vertex ID
  28636. 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);
  28637. }
  28638. // Subdivide the face (interpolate pos, norm, uv)
  28639. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  28640. // - norm is linear interpolation of vertex corner normal
  28641. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  28642. // - uv is linear interpolation
  28643. //
  28644. // Topology is as below for sub-divide by 2
  28645. // vertex shown as v0,v1,v2
  28646. // interp index is i1 to progress in range [v0,v1[
  28647. // interp index is i2 to progress in range [v0,v2[
  28648. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  28649. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28650. //
  28651. //
  28652. // i2 v2
  28653. // ^ ^
  28654. // / / \
  28655. // / / \
  28656. // / / \
  28657. // / / (0,1) \
  28658. // / #---------\
  28659. // / / \ (0,0)'/ \
  28660. // / / \ / \
  28661. // / / \ / \
  28662. // / / (0,0) \ / (1,0) \
  28663. // / #---------#---------\
  28664. // v0 v1
  28665. //
  28666. // --------------------> i1
  28667. //
  28668. // interp of (i1,i2):
  28669. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  28670. // along i1 : lerp(x0,x1, i1/(S-i2))
  28671. //
  28672. // centroid of triangle is needed to get help normal computation
  28673. // (c1,c2) are used for centroid location
  28674. var interp_vertex = function (i1, i2, c1, c2) {
  28675. // vertex is interpolated from
  28676. // - face_vertex_pos[0..2]
  28677. // - face_vertex_uv[0..2]
  28678. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  28679. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  28680. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  28681. pos_interp.normalize();
  28682. var vertex_normal;
  28683. if (flat) {
  28684. // in flat mode, recalculate normal as face centroid normal
  28685. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  28686. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  28687. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  28688. }
  28689. else {
  28690. // in smooth mode, recalculate normal from each single vertex position
  28691. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  28692. }
  28693. // Vertex normal need correction due to X,Y,Z radius scaling
  28694. vertex_normal.x /= radiusX;
  28695. vertex_normal.y /= radiusY;
  28696. vertex_normal.z /= radiusZ;
  28697. vertex_normal.normalize();
  28698. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  28699. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  28700. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  28701. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  28702. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  28703. uvs.push(uv_interp.x, uv_interp.y);
  28704. // push each vertex has member of a face
  28705. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  28706. indices.push(current_indice);
  28707. current_indice++;
  28708. };
  28709. for (var i2 = 0; i2 < subdivisions; i2++) {
  28710. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  28711. // face : (i1,i2) for /\ :
  28712. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  28713. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28714. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28715. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28716. if (i1 + i2 + 1 < subdivisions) {
  28717. // face : (i1,i2)' for \/ :
  28718. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28719. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28720. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28721. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28722. }
  28723. }
  28724. }
  28725. }
  28726. // Sides
  28727. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28728. // Result
  28729. var vertexData = new VertexData();
  28730. vertexData.indices = indices;
  28731. vertexData.positions = positions;
  28732. vertexData.normals = normals;
  28733. vertexData.uvs = uvs;
  28734. return vertexData;
  28735. };
  28736. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  28737. /**
  28738. * Creates the VertexData of the Polyhedron.
  28739. */
  28740. VertexData.CreatePolyhedron = function (options) {
  28741. // provided polyhedron types :
  28742. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  28743. // 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)
  28744. var polyhedra = [];
  28745. 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]] };
  28746. 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]] };
  28747. polyhedra[2] = {
  28748. 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]],
  28749. 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]]
  28750. };
  28751. polyhedra[3] = {
  28752. 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]],
  28753. 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]]
  28754. };
  28755. polyhedra[4] = {
  28756. 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]],
  28757. 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]]
  28758. };
  28759. 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]] };
  28760. 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]] };
  28761. 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]] };
  28762. 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]] };
  28763. 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]] };
  28764. 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]] };
  28765. 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]] };
  28766. 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]] };
  28767. 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]] };
  28768. polyhedra[14] = {
  28769. 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]],
  28770. 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]]
  28771. };
  28772. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  28773. var size = options.size;
  28774. var sizeX = options.sizeX || size || 1;
  28775. var sizeY = options.sizeY || size || 1;
  28776. var sizeZ = options.sizeZ || size || 1;
  28777. var data = options.custom || polyhedra[type];
  28778. var nbfaces = data.face.length;
  28779. var faceUV = options.faceUV || new Array(nbfaces);
  28780. var faceColors = options.faceColors;
  28781. var flat = (options.flat === undefined) ? true : options.flat;
  28782. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28783. var positions = new Array();
  28784. var indices = new Array();
  28785. var normals = new Array();
  28786. var uvs = new Array();
  28787. var colors = new Array();
  28788. var index = 0;
  28789. var faceIdx = 0; // face cursor in the array "indexes"
  28790. var indexes = new Array();
  28791. var i = 0;
  28792. var f = 0;
  28793. var u, v, ang, x, y, tmp;
  28794. // default face colors and UV if undefined
  28795. if (flat) {
  28796. for (f = 0; f < nbfaces; f++) {
  28797. if (faceColors && faceColors[f] === undefined) {
  28798. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28799. }
  28800. if (faceUV && faceUV[f] === undefined) {
  28801. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28802. }
  28803. }
  28804. }
  28805. if (!flat) {
  28806. for (i = 0; i < data.vertex.length; i++) {
  28807. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  28808. uvs.push(0, 0);
  28809. }
  28810. for (f = 0; f < nbfaces; f++) {
  28811. for (i = 0; i < data.face[f].length - 2; i++) {
  28812. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  28813. }
  28814. }
  28815. }
  28816. else {
  28817. for (f = 0; f < nbfaces; f++) {
  28818. var fl = data.face[f].length; // number of vertices of the current face
  28819. ang = 2 * Math.PI / fl;
  28820. x = 0.5 * Math.tan(ang / 2);
  28821. y = 0.5;
  28822. // positions, uvs, colors
  28823. for (i = 0; i < fl; i++) {
  28824. // positions
  28825. 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);
  28826. indexes.push(index);
  28827. index++;
  28828. // uvs
  28829. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  28830. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  28831. uvs.push(u, v);
  28832. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  28833. y = x * Math.sin(ang) + y * Math.cos(ang);
  28834. x = tmp;
  28835. // colors
  28836. if (faceColors) {
  28837. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  28838. }
  28839. }
  28840. // indices from indexes
  28841. for (i = 0; i < fl - 2; i++) {
  28842. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  28843. }
  28844. faceIdx += fl;
  28845. }
  28846. }
  28847. VertexData.ComputeNormals(positions, indices, normals);
  28848. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28849. var vertexData = new VertexData();
  28850. vertexData.positions = positions;
  28851. vertexData.indices = indices;
  28852. vertexData.normals = normals;
  28853. vertexData.uvs = uvs;
  28854. if (faceColors && flat) {
  28855. vertexData.colors = colors;
  28856. }
  28857. return vertexData;
  28858. };
  28859. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  28860. /**
  28861. * Creates the VertexData of the Torus Knot.
  28862. */
  28863. VertexData.CreateTorusKnot = function (options) {
  28864. var indices = new Array();
  28865. var positions = new Array();
  28866. var normals = new Array();
  28867. var uvs = new Array();
  28868. var radius = options.radius || 2;
  28869. var tube = options.tube || 0.5;
  28870. var radialSegments = options.radialSegments || 32;
  28871. var tubularSegments = options.tubularSegments || 32;
  28872. var p = options.p || 2;
  28873. var q = options.q || 3;
  28874. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28875. // Helper
  28876. var getPos = function (angle) {
  28877. var cu = Math.cos(angle);
  28878. var su = Math.sin(angle);
  28879. var quOverP = q / p * angle;
  28880. var cs = Math.cos(quOverP);
  28881. var tx = radius * (2 + cs) * 0.5 * cu;
  28882. var ty = radius * (2 + cs) * su * 0.5;
  28883. var tz = radius * Math.sin(quOverP) * 0.5;
  28884. return new BABYLON.Vector3(tx, ty, tz);
  28885. };
  28886. // Vertices
  28887. var i;
  28888. var j;
  28889. for (i = 0; i <= radialSegments; i++) {
  28890. var modI = i % radialSegments;
  28891. var u = modI / radialSegments * 2 * p * Math.PI;
  28892. var p1 = getPos(u);
  28893. var p2 = getPos(u + 0.01);
  28894. var tang = p2.subtract(p1);
  28895. var n = p2.add(p1);
  28896. var bitan = BABYLON.Vector3.Cross(tang, n);
  28897. n = BABYLON.Vector3.Cross(bitan, tang);
  28898. bitan.normalize();
  28899. n.normalize();
  28900. for (j = 0; j < tubularSegments; j++) {
  28901. var modJ = j % tubularSegments;
  28902. var v = modJ / tubularSegments * 2 * Math.PI;
  28903. var cx = -tube * Math.cos(v);
  28904. var cy = tube * Math.sin(v);
  28905. positions.push(p1.x + cx * n.x + cy * bitan.x);
  28906. positions.push(p1.y + cx * n.y + cy * bitan.y);
  28907. positions.push(p1.z + cx * n.z + cy * bitan.z);
  28908. uvs.push(i / radialSegments);
  28909. uvs.push(j / tubularSegments);
  28910. }
  28911. }
  28912. for (i = 0; i < radialSegments; i++) {
  28913. for (j = 0; j < tubularSegments; j++) {
  28914. var jNext = (j + 1) % tubularSegments;
  28915. var a = i * tubularSegments + j;
  28916. var b = (i + 1) * tubularSegments + j;
  28917. var c = (i + 1) * tubularSegments + jNext;
  28918. var d = i * tubularSegments + jNext;
  28919. indices.push(d);
  28920. indices.push(b);
  28921. indices.push(a);
  28922. indices.push(d);
  28923. indices.push(c);
  28924. indices.push(b);
  28925. }
  28926. }
  28927. // Normals
  28928. VertexData.ComputeNormals(positions, indices, normals);
  28929. // Sides
  28930. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28931. // Result
  28932. var vertexData = new VertexData();
  28933. vertexData.indices = indices;
  28934. vertexData.positions = positions;
  28935. vertexData.normals = normals;
  28936. vertexData.uvs = uvs;
  28937. return vertexData;
  28938. };
  28939. // Tools
  28940. /**
  28941. * @param {any} - positions (number[] or Float32Array)
  28942. * @param {any} - indices (number[] or Uint16Array)
  28943. * @param {any} - normals (number[] or Float32Array)
  28944. * options (optional) :
  28945. * facetPositions : optional array of facet positions (vector3)
  28946. * facetNormals : optional array of facet normals (vector3)
  28947. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  28948. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  28949. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  28950. * bbSize : optional bounding box size data, required for facetPartitioning computation
  28951. * bInfo : optional bounding info, required for facetPartitioning computation
  28952. */
  28953. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  28954. // temporary scalar variables
  28955. var index = 0; // facet index
  28956. var p1p2x = 0.0; // p1p2 vector x coordinate
  28957. var p1p2y = 0.0; // p1p2 vector y coordinate
  28958. var p1p2z = 0.0; // p1p2 vector z coordinate
  28959. var p3p2x = 0.0; // p3p2 vector x coordinate
  28960. var p3p2y = 0.0; // p3p2 vector y coordinate
  28961. var p3p2z = 0.0; // p3p2 vector z coordinate
  28962. var faceNormalx = 0.0; // facet normal x coordinate
  28963. var faceNormaly = 0.0; // facet normal y coordinate
  28964. var faceNormalz = 0.0; // facet normal z coordinate
  28965. var length = 0.0; // facet normal length before normalization
  28966. var v1x = 0; // vector1 x index in the positions array
  28967. var v1y = 0; // vector1 y index in the positions array
  28968. var v1z = 0; // vector1 z index in the positions array
  28969. var v2x = 0; // vector2 x index in the positions array
  28970. var v2y = 0; // vector2 y index in the positions array
  28971. var v2z = 0; // vector2 z index in the positions array
  28972. var v3x = 0; // vector3 x index in the positions array
  28973. var v3y = 0; // vector3 y index in the positions array
  28974. var v3z = 0; // vector3 z index in the positions array
  28975. var computeFacetNormals = false;
  28976. var computeFacetPositions = false;
  28977. var computeFacetPartitioning = false;
  28978. var faceNormalSign = 1;
  28979. if (options) {
  28980. computeFacetNormals = (options.facetNormals) ? true : false;
  28981. computeFacetPositions = (options.facetPositions) ? true : false;
  28982. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  28983. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  28984. }
  28985. // facetPartitioning reinit if needed
  28986. if (computeFacetPartitioning) {
  28987. var ox = 0; // X partitioning index for facet position
  28988. var oy = 0; // Y partinioning index for facet position
  28989. var oz = 0; // Z partinioning index for facet position
  28990. var b1x = 0; // X partitioning index for facet v1 vertex
  28991. var b1y = 0; // Y partitioning index for facet v1 vertex
  28992. var b1z = 0; // z partitioning index for facet v1 vertex
  28993. var b2x = 0; // X partitioning index for facet v2 vertex
  28994. var b2y = 0; // Y partitioning index for facet v2 vertex
  28995. var b2z = 0; // Z partitioning index for facet v2 vertex
  28996. var b3x = 0; // X partitioning index for facet v3 vertex
  28997. var b3y = 0; // Y partitioning index for facet v3 vertex
  28998. var b3z = 0; // Z partitioning index for facet v3 vertex
  28999. var block_idx_o = 0; // facet barycenter block index
  29000. var block_idx_v1 = 0; // v1 vertex block index
  29001. var block_idx_v2 = 0; // v2 vertex block index
  29002. var block_idx_v3 = 0; // v3 vertex block index
  29003. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  29004. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  29005. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  29006. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  29007. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  29008. var subSq = options.subDiv.max * options.subDiv.max;
  29009. options.facetPartitioning.length = 0;
  29010. }
  29011. // reset the normals
  29012. for (index = 0; index < positions.length; index++) {
  29013. normals[index] = 0.0;
  29014. }
  29015. // Loop : 1 indice triplet = 1 facet
  29016. var nbFaces = indices.length / 3;
  29017. for (index = 0; index < nbFaces; index++) {
  29018. // get the indexes of the coordinates of each vertex of the facet
  29019. v1x = indices[index * 3] * 3;
  29020. v1y = v1x + 1;
  29021. v1z = v1x + 2;
  29022. v2x = indices[index * 3 + 1] * 3;
  29023. v2y = v2x + 1;
  29024. v2z = v2x + 2;
  29025. v3x = indices[index * 3 + 2] * 3;
  29026. v3y = v3x + 1;
  29027. v3z = v3x + 2;
  29028. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  29029. p1p2y = positions[v1y] - positions[v2y];
  29030. p1p2z = positions[v1z] - positions[v2z];
  29031. p3p2x = positions[v3x] - positions[v2x];
  29032. p3p2y = positions[v3y] - positions[v2y];
  29033. p3p2z = positions[v3z] - positions[v2z];
  29034. // compute the face normal with the cross product
  29035. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  29036. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  29037. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  29038. // normalize this normal and store it in the array facetData
  29039. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29040. length = (length === 0) ? 1.0 : length;
  29041. faceNormalx /= length;
  29042. faceNormaly /= length;
  29043. faceNormalz /= length;
  29044. if (computeFacetNormals) {
  29045. options.facetNormals[index].x = faceNormalx;
  29046. options.facetNormals[index].y = faceNormaly;
  29047. options.facetNormals[index].z = faceNormalz;
  29048. }
  29049. if (computeFacetPositions) {
  29050. // compute and the facet barycenter coordinates in the array facetPositions
  29051. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  29052. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  29053. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  29054. }
  29055. if (computeFacetPartitioning) {
  29056. // store the facet indexes in arrays in the main facetPartitioning array :
  29057. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  29058. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  29059. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  29060. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  29061. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  29062. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  29063. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  29064. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  29065. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  29066. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  29067. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  29068. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  29069. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  29070. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  29071. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  29072. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  29073. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  29074. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  29075. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  29076. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  29077. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  29078. // push each facet index in each block containing the vertex
  29079. options.facetPartitioning[block_idx_v1].push(index);
  29080. if (block_idx_v2 != block_idx_v1) {
  29081. options.facetPartitioning[block_idx_v2].push(index);
  29082. }
  29083. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  29084. options.facetPartitioning[block_idx_v3].push(index);
  29085. }
  29086. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  29087. options.facetPartitioning[block_idx_o].push(index);
  29088. }
  29089. }
  29090. // compute the normals anyway
  29091. normals[v1x] += faceNormalx; // accumulate all the normals per face
  29092. normals[v1y] += faceNormaly;
  29093. normals[v1z] += faceNormalz;
  29094. normals[v2x] += faceNormalx;
  29095. normals[v2y] += faceNormaly;
  29096. normals[v2z] += faceNormalz;
  29097. normals[v3x] += faceNormalx;
  29098. normals[v3y] += faceNormaly;
  29099. normals[v3z] += faceNormalz;
  29100. }
  29101. // last normalization of each normal
  29102. for (index = 0; index < normals.length / 3; index++) {
  29103. faceNormalx = normals[index * 3];
  29104. faceNormaly = normals[index * 3 + 1];
  29105. faceNormalz = normals[index * 3 + 2];
  29106. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29107. length = (length === 0) ? 1.0 : length;
  29108. faceNormalx /= length;
  29109. faceNormaly /= length;
  29110. faceNormalz /= length;
  29111. normals[index * 3] = faceNormalx;
  29112. normals[index * 3 + 1] = faceNormaly;
  29113. normals[index * 3 + 2] = faceNormalz;
  29114. }
  29115. };
  29116. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  29117. var li = indices.length;
  29118. var ln = normals.length;
  29119. var i;
  29120. var n;
  29121. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29122. switch (sideOrientation) {
  29123. case BABYLON.Mesh.FRONTSIDE:
  29124. // nothing changed
  29125. break;
  29126. case BABYLON.Mesh.BACKSIDE:
  29127. var tmp;
  29128. // indices
  29129. for (i = 0; i < li; i += 3) {
  29130. tmp = indices[i];
  29131. indices[i] = indices[i + 2];
  29132. indices[i + 2] = tmp;
  29133. }
  29134. // normals
  29135. for (n = 0; n < ln; n++) {
  29136. normals[n] = -normals[n];
  29137. }
  29138. break;
  29139. case BABYLON.Mesh.DOUBLESIDE:
  29140. // positions
  29141. var lp = positions.length;
  29142. var l = lp / 3;
  29143. for (var p = 0; p < lp; p++) {
  29144. positions[lp + p] = positions[p];
  29145. }
  29146. // indices
  29147. for (i = 0; i < li; i += 3) {
  29148. indices[i + li] = indices[i + 2] + l;
  29149. indices[i + 1 + li] = indices[i + 1] + l;
  29150. indices[i + 2 + li] = indices[i] + l;
  29151. }
  29152. // normals
  29153. for (n = 0; n < ln; n++) {
  29154. normals[ln + n] = -normals[n];
  29155. }
  29156. // uvs
  29157. var lu = uvs.length;
  29158. var u = 0;
  29159. for (u = 0; u < lu; u++) {
  29160. uvs[u + lu] = uvs[u];
  29161. }
  29162. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  29163. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  29164. u = 0;
  29165. for (i = 0; i < lu / 2; i++) {
  29166. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  29167. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  29168. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  29169. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  29170. u += 2;
  29171. }
  29172. break;
  29173. }
  29174. };
  29175. /**
  29176. * Creates a new VertexData from the imported parameters.
  29177. */
  29178. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  29179. var vertexData = new VertexData();
  29180. // positions
  29181. var positions = parsedVertexData.positions;
  29182. if (positions) {
  29183. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  29184. }
  29185. // normals
  29186. var normals = parsedVertexData.normals;
  29187. if (normals) {
  29188. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  29189. }
  29190. // tangents
  29191. var tangents = parsedVertexData.tangents;
  29192. if (tangents) {
  29193. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  29194. }
  29195. // uvs
  29196. var uvs = parsedVertexData.uvs;
  29197. if (uvs) {
  29198. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  29199. }
  29200. // uv2s
  29201. var uv2s = parsedVertexData.uv2s;
  29202. if (uv2s) {
  29203. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  29204. }
  29205. // uv3s
  29206. var uv3s = parsedVertexData.uv3s;
  29207. if (uv3s) {
  29208. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  29209. }
  29210. // uv4s
  29211. var uv4s = parsedVertexData.uv4s;
  29212. if (uv4s) {
  29213. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  29214. }
  29215. // uv5s
  29216. var uv5s = parsedVertexData.uv5s;
  29217. if (uv5s) {
  29218. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  29219. }
  29220. // uv6s
  29221. var uv6s = parsedVertexData.uv6s;
  29222. if (uv6s) {
  29223. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  29224. }
  29225. // colors
  29226. var colors = parsedVertexData.colors;
  29227. if (colors) {
  29228. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  29229. }
  29230. // matricesIndices
  29231. var matricesIndices = parsedVertexData.matricesIndices;
  29232. if (matricesIndices) {
  29233. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  29234. }
  29235. // matricesWeights
  29236. var matricesWeights = parsedVertexData.matricesWeights;
  29237. if (matricesWeights) {
  29238. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  29239. }
  29240. // indices
  29241. var indices = parsedVertexData.indices;
  29242. if (indices) {
  29243. vertexData.indices = indices;
  29244. }
  29245. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  29246. };
  29247. return VertexData;
  29248. }());
  29249. BABYLON.VertexData = VertexData;
  29250. })(BABYLON || (BABYLON = {}));
  29251. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  29252. var BABYLON;
  29253. (function (BABYLON) {
  29254. var Geometry = (function () {
  29255. function Geometry(id, scene, vertexData, updatable, mesh) {
  29256. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29257. this._totalVertices = 0;
  29258. this._isDisposed = false;
  29259. this._indexBufferIsUpdatable = false;
  29260. this.id = id;
  29261. this._engine = scene.getEngine();
  29262. this._meshes = [];
  29263. this._scene = scene;
  29264. //Init vertex buffer cache
  29265. this._vertexBuffers = {};
  29266. this._indices = [];
  29267. this._updatable = updatable;
  29268. // vertexData
  29269. if (vertexData) {
  29270. this.setAllVerticesData(vertexData, updatable);
  29271. }
  29272. else {
  29273. this._totalVertices = 0;
  29274. this._indices = [];
  29275. }
  29276. if (this._engine.getCaps().vertexArrayObject) {
  29277. this._vertexArrayObjects = {};
  29278. }
  29279. // applyToMesh
  29280. if (mesh) {
  29281. if (mesh.getClassName() === "LinesMesh") {
  29282. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  29283. this.updateExtend();
  29284. }
  29285. this.applyToMesh(mesh);
  29286. mesh.computeWorldMatrix(true);
  29287. }
  29288. }
  29289. Object.defineProperty(Geometry.prototype, "boundingBias", {
  29290. /**
  29291. * 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
  29292. * @returns The Bias Vector
  29293. */
  29294. get: function () {
  29295. return this._boundingBias;
  29296. },
  29297. set: function (value) {
  29298. if (this._boundingBias && this._boundingBias.equals(value)) {
  29299. return;
  29300. }
  29301. this._boundingBias = value.clone();
  29302. this.updateBoundingInfo(true, null);
  29303. },
  29304. enumerable: true,
  29305. configurable: true
  29306. });
  29307. Object.defineProperty(Geometry.prototype, "extend", {
  29308. get: function () {
  29309. return this._extend;
  29310. },
  29311. enumerable: true,
  29312. configurable: true
  29313. });
  29314. Geometry.prototype.getScene = function () {
  29315. return this._scene;
  29316. };
  29317. Geometry.prototype.getEngine = function () {
  29318. return this._engine;
  29319. };
  29320. Geometry.prototype.isReady = function () {
  29321. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  29322. };
  29323. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  29324. get: function () {
  29325. for (var index = 0; index < this._meshes.length; index++) {
  29326. if (!this._meshes[index].doNotSerialize) {
  29327. return false;
  29328. }
  29329. }
  29330. return true;
  29331. },
  29332. enumerable: true,
  29333. configurable: true
  29334. });
  29335. Geometry.prototype._rebuild = function () {
  29336. if (this._vertexArrayObjects) {
  29337. this._vertexArrayObjects = {};
  29338. }
  29339. // Index buffer
  29340. if (this._meshes.length !== 0 && this._indices) {
  29341. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29342. }
  29343. // Vertex buffers
  29344. for (var key in this._vertexBuffers) {
  29345. var vertexBuffer = this._vertexBuffers[key];
  29346. vertexBuffer._rebuild();
  29347. }
  29348. };
  29349. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  29350. vertexData.applyToGeometry(this, updatable);
  29351. this.notifyUpdate();
  29352. };
  29353. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  29354. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  29355. this.setVerticesBuffer(buffer);
  29356. };
  29357. Geometry.prototype.removeVerticesData = function (kind) {
  29358. if (this._vertexBuffers[kind]) {
  29359. this._vertexBuffers[kind].dispose();
  29360. delete this._vertexBuffers[kind];
  29361. }
  29362. };
  29363. Geometry.prototype.setVerticesBuffer = function (buffer) {
  29364. var kind = buffer.getKind();
  29365. if (this._vertexBuffers[kind]) {
  29366. this._vertexBuffers[kind].dispose();
  29367. }
  29368. this._vertexBuffers[kind] = buffer;
  29369. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29370. var data = buffer.getData();
  29371. var stride = buffer.getStrideSize();
  29372. this._totalVertices = data.length / stride;
  29373. this.updateExtend(data, stride);
  29374. this._resetPointsArrayCache();
  29375. var meshes = this._meshes;
  29376. var numOfMeshes = meshes.length;
  29377. for (var index = 0; index < numOfMeshes; index++) {
  29378. var mesh = meshes[index];
  29379. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29380. mesh._createGlobalSubMesh(false);
  29381. mesh.computeWorldMatrix(true);
  29382. }
  29383. }
  29384. this.notifyUpdate(kind);
  29385. if (this._vertexArrayObjects) {
  29386. this._disposeVertexArrayObjects();
  29387. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  29388. }
  29389. };
  29390. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  29391. var vertexBuffer = this.getVertexBuffer(kind);
  29392. if (!vertexBuffer) {
  29393. return;
  29394. }
  29395. vertexBuffer.updateDirectly(data, offset);
  29396. this.notifyUpdate(kind);
  29397. };
  29398. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  29399. var vertexBuffer = this.getVertexBuffer(kind);
  29400. if (!vertexBuffer) {
  29401. return;
  29402. }
  29403. vertexBuffer.update(data);
  29404. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29405. var stride = vertexBuffer.getStrideSize();
  29406. this._totalVertices = data.length / stride;
  29407. this.updateBoundingInfo(updateExtends, data);
  29408. }
  29409. this.notifyUpdate(kind);
  29410. };
  29411. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  29412. if (updateExtends) {
  29413. this.updateExtend(data);
  29414. }
  29415. var meshes = this._meshes;
  29416. var numOfMeshes = meshes.length;
  29417. this._resetPointsArrayCache();
  29418. for (var index = 0; index < numOfMeshes; index++) {
  29419. var mesh = meshes[index];
  29420. if (updateExtends) {
  29421. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29422. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29423. var subMesh = mesh.subMeshes[subIndex];
  29424. subMesh.refreshBoundingInfo();
  29425. }
  29426. }
  29427. }
  29428. };
  29429. Geometry.prototype._bind = function (effect, indexToBind) {
  29430. if (indexToBind === void 0) { indexToBind = undefined; }
  29431. if (indexToBind === undefined) {
  29432. indexToBind = this._indexBuffer;
  29433. }
  29434. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  29435. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  29436. return;
  29437. }
  29438. // Using VAO
  29439. if (!this._vertexArrayObjects[effect.key]) {
  29440. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  29441. }
  29442. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  29443. };
  29444. Geometry.prototype.getTotalVertices = function () {
  29445. if (!this.isReady()) {
  29446. return 0;
  29447. }
  29448. return this._totalVertices;
  29449. };
  29450. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  29451. var vertexBuffer = this.getVertexBuffer(kind);
  29452. if (!vertexBuffer) {
  29453. return null;
  29454. }
  29455. var orig = vertexBuffer.getData();
  29456. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  29457. return orig;
  29458. }
  29459. else {
  29460. var len = orig.length;
  29461. var copy = [];
  29462. for (var i = 0; i < len; i++) {
  29463. copy.push(orig[i]);
  29464. }
  29465. return copy;
  29466. }
  29467. };
  29468. Geometry.prototype.getVertexBuffer = function (kind) {
  29469. if (!this.isReady()) {
  29470. return null;
  29471. }
  29472. return this._vertexBuffers[kind];
  29473. };
  29474. Geometry.prototype.getVertexBuffers = function () {
  29475. if (!this.isReady()) {
  29476. return null;
  29477. }
  29478. return this._vertexBuffers;
  29479. };
  29480. Geometry.prototype.isVerticesDataPresent = function (kind) {
  29481. if (!this._vertexBuffers) {
  29482. if (this._delayInfo) {
  29483. return this._delayInfo.indexOf(kind) !== -1;
  29484. }
  29485. return false;
  29486. }
  29487. return this._vertexBuffers[kind] !== undefined;
  29488. };
  29489. Geometry.prototype.getVerticesDataKinds = function () {
  29490. var result = [];
  29491. var kind;
  29492. if (!this._vertexBuffers && this._delayInfo) {
  29493. for (kind in this._delayInfo) {
  29494. result.push(kind);
  29495. }
  29496. }
  29497. else {
  29498. for (kind in this._vertexBuffers) {
  29499. result.push(kind);
  29500. }
  29501. }
  29502. return result;
  29503. };
  29504. Geometry.prototype.updateIndices = function (indices, offset) {
  29505. if (!this._indexBuffer) {
  29506. return;
  29507. }
  29508. if (!this._indexBufferIsUpdatable) {
  29509. this.setIndices(indices, null, true);
  29510. }
  29511. else {
  29512. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  29513. }
  29514. };
  29515. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  29516. if (this._indexBuffer) {
  29517. this._engine._releaseBuffer(this._indexBuffer);
  29518. }
  29519. this._disposeVertexArrayObjects();
  29520. this._indices = indices;
  29521. this._indexBufferIsUpdatable = updatable;
  29522. if (this._meshes.length !== 0 && this._indices) {
  29523. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  29524. }
  29525. if (totalVertices != undefined) {
  29526. this._totalVertices = totalVertices;
  29527. }
  29528. var meshes = this._meshes;
  29529. var numOfMeshes = meshes.length;
  29530. for (var index = 0; index < numOfMeshes; index++) {
  29531. meshes[index]._createGlobalSubMesh(true);
  29532. }
  29533. this.notifyUpdate();
  29534. };
  29535. Geometry.prototype.getTotalIndices = function () {
  29536. if (!this.isReady()) {
  29537. return 0;
  29538. }
  29539. return this._indices.length;
  29540. };
  29541. Geometry.prototype.getIndices = function (copyWhenShared) {
  29542. if (!this.isReady()) {
  29543. return null;
  29544. }
  29545. var orig = this._indices;
  29546. if (!copyWhenShared || this._meshes.length === 1) {
  29547. return orig;
  29548. }
  29549. else {
  29550. var len = orig.length;
  29551. var copy = [];
  29552. for (var i = 0; i < len; i++) {
  29553. copy.push(orig[i]);
  29554. }
  29555. return copy;
  29556. }
  29557. };
  29558. Geometry.prototype.getIndexBuffer = function () {
  29559. if (!this.isReady()) {
  29560. return null;
  29561. }
  29562. return this._indexBuffer;
  29563. };
  29564. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  29565. if (!effect || !this._vertexArrayObjects) {
  29566. return;
  29567. }
  29568. if (this._vertexArrayObjects[effect.key]) {
  29569. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  29570. delete this._vertexArrayObjects[effect.key];
  29571. }
  29572. };
  29573. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  29574. var meshes = this._meshes;
  29575. var index = meshes.indexOf(mesh);
  29576. if (index === -1) {
  29577. return;
  29578. }
  29579. meshes.splice(index, 1);
  29580. mesh._geometry = null;
  29581. if (meshes.length === 0 && shouldDispose) {
  29582. this.dispose();
  29583. }
  29584. };
  29585. Geometry.prototype.applyToMesh = function (mesh) {
  29586. if (mesh._geometry === this) {
  29587. return;
  29588. }
  29589. var previousGeometry = mesh._geometry;
  29590. if (previousGeometry) {
  29591. previousGeometry.releaseForMesh(mesh);
  29592. }
  29593. var meshes = this._meshes;
  29594. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  29595. mesh._geometry = this;
  29596. this._scene.pushGeometry(this);
  29597. meshes.push(mesh);
  29598. if (this.isReady()) {
  29599. this._applyToMesh(mesh);
  29600. }
  29601. else {
  29602. mesh._boundingInfo = this._boundingInfo;
  29603. }
  29604. };
  29605. Geometry.prototype.updateExtend = function (data, stride) {
  29606. if (data === void 0) { data = null; }
  29607. if (!data) {
  29608. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  29609. }
  29610. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  29611. };
  29612. Geometry.prototype._applyToMesh = function (mesh) {
  29613. var numOfMeshes = this._meshes.length;
  29614. // vertexBuffers
  29615. for (var kind in this._vertexBuffers) {
  29616. if (numOfMeshes === 1) {
  29617. this._vertexBuffers[kind].create();
  29618. }
  29619. var buffer = this._vertexBuffers[kind].getBuffer();
  29620. if (buffer)
  29621. buffer.references = numOfMeshes;
  29622. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29623. if (!this._extend) {
  29624. this.updateExtend(this._vertexBuffers[kind].getData());
  29625. }
  29626. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29627. mesh._createGlobalSubMesh(false);
  29628. //bounding info was just created again, world matrix should be applied again.
  29629. mesh._updateBoundingInfo();
  29630. }
  29631. }
  29632. // indexBuffer
  29633. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  29634. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29635. }
  29636. if (this._indexBuffer) {
  29637. this._indexBuffer.references = numOfMeshes;
  29638. }
  29639. };
  29640. Geometry.prototype.notifyUpdate = function (kind) {
  29641. if (this.onGeometryUpdated) {
  29642. this.onGeometryUpdated(this, kind);
  29643. }
  29644. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  29645. var mesh = _a[_i];
  29646. mesh._markSubMeshesAsAttributesDirty();
  29647. }
  29648. };
  29649. Geometry.prototype.load = function (scene, onLoaded) {
  29650. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29651. return;
  29652. }
  29653. if (this.isReady()) {
  29654. if (onLoaded) {
  29655. onLoaded();
  29656. }
  29657. return;
  29658. }
  29659. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29660. this._queueLoad(scene, onLoaded);
  29661. };
  29662. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  29663. var _this = this;
  29664. scene._addPendingData(this);
  29665. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29666. _this._delayLoadingFunction(JSON.parse(data), _this);
  29667. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29668. _this._delayInfo = [];
  29669. scene._removePendingData(_this);
  29670. var meshes = _this._meshes;
  29671. var numOfMeshes = meshes.length;
  29672. for (var index = 0; index < numOfMeshes; index++) {
  29673. _this._applyToMesh(meshes[index]);
  29674. }
  29675. if (onLoaded) {
  29676. onLoaded();
  29677. }
  29678. }, function () { }, scene.database);
  29679. };
  29680. /**
  29681. * Invert the geometry to move from a right handed system to a left handed one.
  29682. */
  29683. Geometry.prototype.toLeftHanded = function () {
  29684. // Flip faces
  29685. var tIndices = this.getIndices(false);
  29686. if (tIndices != null && tIndices.length > 0) {
  29687. for (var i = 0; i < tIndices.length; i += 3) {
  29688. var tTemp = tIndices[i + 0];
  29689. tIndices[i + 0] = tIndices[i + 2];
  29690. tIndices[i + 2] = tTemp;
  29691. }
  29692. this.setIndices(tIndices);
  29693. }
  29694. // Negate position.z
  29695. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  29696. if (tPositions != null && tPositions.length > 0) {
  29697. for (var i = 0; i < tPositions.length; i += 3) {
  29698. tPositions[i + 2] = -tPositions[i + 2];
  29699. }
  29700. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  29701. }
  29702. // Negate normal.z
  29703. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  29704. if (tNormals != null && tNormals.length > 0) {
  29705. for (var i = 0; i < tNormals.length; i += 3) {
  29706. tNormals[i + 2] = -tNormals[i + 2];
  29707. }
  29708. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  29709. }
  29710. };
  29711. // Cache
  29712. Geometry.prototype._resetPointsArrayCache = function () {
  29713. this._positions = null;
  29714. };
  29715. Geometry.prototype._generatePointsArray = function () {
  29716. if (this._positions)
  29717. return true;
  29718. this._positions = [];
  29719. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29720. if (!data) {
  29721. return false;
  29722. }
  29723. for (var index = 0; index < data.length; index += 3) {
  29724. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  29725. }
  29726. return true;
  29727. };
  29728. Geometry.prototype.isDisposed = function () {
  29729. return this._isDisposed;
  29730. };
  29731. Geometry.prototype._disposeVertexArrayObjects = function () {
  29732. if (this._vertexArrayObjects) {
  29733. for (var kind in this._vertexArrayObjects) {
  29734. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  29735. }
  29736. this._vertexArrayObjects = {};
  29737. }
  29738. };
  29739. Geometry.prototype.dispose = function () {
  29740. var meshes = this._meshes;
  29741. var numOfMeshes = meshes.length;
  29742. var index;
  29743. for (index = 0; index < numOfMeshes; index++) {
  29744. this.releaseForMesh(meshes[index]);
  29745. }
  29746. this._meshes = [];
  29747. this._disposeVertexArrayObjects();
  29748. for (var kind in this._vertexBuffers) {
  29749. this._vertexBuffers[kind].dispose();
  29750. }
  29751. this._vertexBuffers = {};
  29752. this._totalVertices = 0;
  29753. if (this._indexBuffer) {
  29754. this._engine._releaseBuffer(this._indexBuffer);
  29755. }
  29756. this._indexBuffer = null;
  29757. this._indices = [];
  29758. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29759. this.delayLoadingFile = null;
  29760. this._delayLoadingFunction = null;
  29761. this._delayInfo = [];
  29762. this._boundingInfo = null;
  29763. this._scene.removeGeometry(this);
  29764. this._isDisposed = true;
  29765. };
  29766. Geometry.prototype.copy = function (id) {
  29767. var vertexData = new BABYLON.VertexData();
  29768. vertexData.indices = [];
  29769. var indices = this.getIndices();
  29770. for (var index = 0; index < indices.length; index++) {
  29771. vertexData.indices.push(indices[index]);
  29772. }
  29773. var updatable = false;
  29774. var stopChecking = false;
  29775. var kind;
  29776. for (kind in this._vertexBuffers) {
  29777. // using slice() to make a copy of the array and not just reference it
  29778. var data = this.getVerticesData(kind);
  29779. if (data instanceof Float32Array) {
  29780. vertexData.set(new Float32Array(data), kind);
  29781. }
  29782. else {
  29783. vertexData.set(data.slice(0), kind);
  29784. }
  29785. if (!stopChecking) {
  29786. updatable = this.getVertexBuffer(kind).isUpdatable();
  29787. stopChecking = !updatable;
  29788. }
  29789. }
  29790. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  29791. geometry.delayLoadState = this.delayLoadState;
  29792. geometry.delayLoadingFile = this.delayLoadingFile;
  29793. geometry._delayLoadingFunction = this._delayLoadingFunction;
  29794. for (kind in this._delayInfo) {
  29795. geometry._delayInfo = geometry._delayInfo || [];
  29796. geometry._delayInfo.push(kind);
  29797. }
  29798. // Bounding info
  29799. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29800. return geometry;
  29801. };
  29802. Geometry.prototype.serialize = function () {
  29803. var serializationObject = {};
  29804. serializationObject.id = this.id;
  29805. serializationObject.updatable = this._updatable;
  29806. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29807. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29808. }
  29809. return serializationObject;
  29810. };
  29811. Geometry.prototype.toNumberArray = function (origin) {
  29812. if (Array.isArray(origin)) {
  29813. return origin;
  29814. }
  29815. else {
  29816. return Array.prototype.slice.call(origin);
  29817. }
  29818. };
  29819. Geometry.prototype.serializeVerticeData = function () {
  29820. var serializationObject = this.serialize();
  29821. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29822. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  29823. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  29824. serializationObject.positions._updatable = true;
  29825. }
  29826. }
  29827. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29828. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  29829. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  29830. serializationObject.normals._updatable = true;
  29831. }
  29832. }
  29833. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29834. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  29835. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  29836. serializationObject.uvs._updatable = true;
  29837. }
  29838. }
  29839. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29840. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  29841. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  29842. serializationObject.uv2s._updatable = true;
  29843. }
  29844. }
  29845. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29846. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  29847. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  29848. serializationObject.uv3s._updatable = true;
  29849. }
  29850. }
  29851. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29852. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  29853. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  29854. serializationObject.uv4s._updatable = true;
  29855. }
  29856. }
  29857. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29858. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  29859. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  29860. serializationObject.uv5s._updatable = true;
  29861. }
  29862. }
  29863. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29864. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  29865. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  29866. serializationObject.uv6s._updatable = true;
  29867. }
  29868. }
  29869. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29870. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  29871. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  29872. serializationObject.colors._updatable = true;
  29873. }
  29874. }
  29875. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29876. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  29877. serializationObject.matricesIndices._isExpanded = true;
  29878. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  29879. serializationObject.matricesIndices._updatable = true;
  29880. }
  29881. }
  29882. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29883. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  29884. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  29885. serializationObject.matricesWeights._updatable = true;
  29886. }
  29887. }
  29888. serializationObject.indices = this.toNumberArray(this.getIndices());
  29889. return serializationObject;
  29890. };
  29891. // Statics
  29892. Geometry.ExtractFromMesh = function (mesh, id) {
  29893. var geometry = mesh._geometry;
  29894. if (!geometry) {
  29895. return null;
  29896. }
  29897. return geometry.copy(id);
  29898. };
  29899. /**
  29900. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  29901. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29902. * Be aware Math.random() could cause collisions, but:
  29903. * "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"
  29904. */
  29905. Geometry.RandomId = function () {
  29906. return BABYLON.Tools.RandomId();
  29907. };
  29908. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  29909. var scene = mesh.getScene();
  29910. // Geometry
  29911. var geometryId = parsedGeometry.geometryId;
  29912. if (geometryId) {
  29913. var geometry = scene.getGeometryByID(geometryId);
  29914. if (geometry) {
  29915. geometry.applyToMesh(mesh);
  29916. }
  29917. }
  29918. else if (parsedGeometry instanceof ArrayBuffer) {
  29919. var binaryInfo = mesh._binaryInfo;
  29920. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  29921. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  29922. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  29923. }
  29924. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  29925. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  29926. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  29927. }
  29928. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  29929. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  29930. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  29931. }
  29932. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  29933. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  29934. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  29935. }
  29936. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  29937. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  29938. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  29939. }
  29940. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  29941. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  29942. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  29943. }
  29944. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  29945. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  29946. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  29947. }
  29948. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  29949. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  29950. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  29951. }
  29952. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  29953. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  29954. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  29955. }
  29956. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  29957. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  29958. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  29959. }
  29960. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  29961. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  29962. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  29963. }
  29964. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  29965. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  29966. mesh.setIndices(indicesData);
  29967. }
  29968. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  29969. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  29970. mesh.subMeshes = [];
  29971. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  29972. var materialIndex = subMeshesData[(i * 5) + 0];
  29973. var verticesStart = subMeshesData[(i * 5) + 1];
  29974. var verticesCount = subMeshesData[(i * 5) + 2];
  29975. var indexStart = subMeshesData[(i * 5) + 3];
  29976. var indexCount = subMeshesData[(i * 5) + 4];
  29977. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  29978. }
  29979. }
  29980. }
  29981. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  29982. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  29983. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  29984. if (parsedGeometry.uvs) {
  29985. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  29986. }
  29987. if (parsedGeometry.uvs2) {
  29988. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  29989. }
  29990. if (parsedGeometry.uvs3) {
  29991. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  29992. }
  29993. if (parsedGeometry.uvs4) {
  29994. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  29995. }
  29996. if (parsedGeometry.uvs5) {
  29997. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  29998. }
  29999. if (parsedGeometry.uvs6) {
  30000. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  30001. }
  30002. if (parsedGeometry.colors) {
  30003. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  30004. }
  30005. if (parsedGeometry.matricesIndices) {
  30006. if (!parsedGeometry.matricesIndices._isExpanded) {
  30007. var floatIndices = [];
  30008. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  30009. var matricesIndex = parsedGeometry.matricesIndices[i];
  30010. floatIndices.push(matricesIndex & 0x000000FF);
  30011. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  30012. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  30013. floatIndices.push(matricesIndex >> 24);
  30014. }
  30015. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  30016. }
  30017. else {
  30018. delete parsedGeometry.matricesIndices._isExpanded;
  30019. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  30020. }
  30021. }
  30022. if (parsedGeometry.matricesIndicesExtra) {
  30023. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  30024. var floatIndices = [];
  30025. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  30026. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  30027. floatIndices.push(matricesIndex & 0x000000FF);
  30028. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  30029. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  30030. floatIndices.push(matricesIndex >> 24);
  30031. }
  30032. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  30033. }
  30034. else {
  30035. delete parsedGeometry.matricesIndices._isExpanded;
  30036. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  30037. }
  30038. }
  30039. if (parsedGeometry.matricesWeights) {
  30040. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  30041. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  30042. }
  30043. if (parsedGeometry.matricesWeightsExtra) {
  30044. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  30045. }
  30046. mesh.setIndices(parsedGeometry.indices);
  30047. }
  30048. // SubMeshes
  30049. if (parsedGeometry.subMeshes) {
  30050. mesh.subMeshes = [];
  30051. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  30052. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  30053. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  30054. }
  30055. }
  30056. // Flat shading
  30057. if (mesh._shouldGenerateFlatShading) {
  30058. mesh.convertToFlatShadedMesh();
  30059. delete mesh._shouldGenerateFlatShading;
  30060. }
  30061. // Update
  30062. mesh.computeWorldMatrix(true);
  30063. // Octree
  30064. if (scene['_selectionOctree']) {
  30065. scene['_selectionOctree'].addMesh(mesh);
  30066. }
  30067. };
  30068. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  30069. var epsilon = 1e-3;
  30070. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  30071. return;
  30072. }
  30073. var noInfluenceBoneIndex = 0.0;
  30074. if (parsedGeometry.skeletonId > -1) {
  30075. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  30076. noInfluenceBoneIndex = skeleton.bones.length;
  30077. }
  30078. else {
  30079. return;
  30080. }
  30081. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30082. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  30083. var matricesWeights = parsedGeometry.matricesWeights;
  30084. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  30085. var influencers = parsedGeometry.numBoneInfluencer;
  30086. var size = matricesWeights.length;
  30087. for (var i = 0; i < size; i += 4) {
  30088. var weight = 0.0;
  30089. var firstZeroWeight = -1;
  30090. for (var j = 0; j < 4; j++) {
  30091. var w = matricesWeights[i + j];
  30092. weight += w;
  30093. if (w < epsilon && firstZeroWeight < 0) {
  30094. firstZeroWeight = j;
  30095. }
  30096. }
  30097. if (matricesWeightsExtra) {
  30098. for (var j = 0; j < 4; j++) {
  30099. var w = matricesWeightsExtra[i + j];
  30100. weight += w;
  30101. if (w < epsilon && firstZeroWeight < 0) {
  30102. firstZeroWeight = j + 4;
  30103. }
  30104. }
  30105. }
  30106. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  30107. firstZeroWeight = influencers - 1;
  30108. }
  30109. if (weight > epsilon) {
  30110. var mweight = 1.0 / weight;
  30111. for (var j = 0; j < 4; j++) {
  30112. matricesWeights[i + j] *= mweight;
  30113. }
  30114. if (matricesWeightsExtra) {
  30115. for (var j = 0; j < 4; j++) {
  30116. matricesWeightsExtra[i + j] *= mweight;
  30117. }
  30118. }
  30119. }
  30120. else {
  30121. if (firstZeroWeight >= 4) {
  30122. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  30123. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  30124. }
  30125. else {
  30126. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  30127. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  30128. }
  30129. }
  30130. }
  30131. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  30132. if (parsedGeometry.matricesWeightsExtra) {
  30133. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  30134. }
  30135. };
  30136. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  30137. if (scene.getGeometryByID(parsedVertexData.id)) {
  30138. return null; // null since geometry could be something else than a box...
  30139. }
  30140. var geometry = new Geometry(parsedVertexData.id, scene, null, parsedVertexData.updatable);
  30141. if (BABYLON.Tags) {
  30142. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  30143. }
  30144. if (parsedVertexData.delayLoadingFile) {
  30145. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30146. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  30147. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  30148. geometry._delayInfo = [];
  30149. if (parsedVertexData.hasUVs) {
  30150. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  30151. }
  30152. if (parsedVertexData.hasUVs2) {
  30153. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  30154. }
  30155. if (parsedVertexData.hasUVs3) {
  30156. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  30157. }
  30158. if (parsedVertexData.hasUVs4) {
  30159. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  30160. }
  30161. if (parsedVertexData.hasUVs5) {
  30162. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  30163. }
  30164. if (parsedVertexData.hasUVs6) {
  30165. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  30166. }
  30167. if (parsedVertexData.hasColors) {
  30168. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  30169. }
  30170. if (parsedVertexData.hasMatricesIndices) {
  30171. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30172. }
  30173. if (parsedVertexData.hasMatricesWeights) {
  30174. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30175. }
  30176. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  30177. }
  30178. else {
  30179. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  30180. }
  30181. scene.pushGeometry(geometry, true);
  30182. return geometry;
  30183. };
  30184. return Geometry;
  30185. }());
  30186. BABYLON.Geometry = Geometry;
  30187. /////// Primitives //////////////////////////////////////////////
  30188. (function (Geometry) {
  30189. var Primitives;
  30190. (function (Primitives) {
  30191. /// Abstract class
  30192. var _Primitive = (function (_super) {
  30193. __extends(_Primitive, _super);
  30194. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  30195. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  30196. _this._canBeRegenerated = _canBeRegenerated;
  30197. _this._beingRegenerated = true;
  30198. _this.regenerate();
  30199. _this._beingRegenerated = false;
  30200. return _this;
  30201. }
  30202. _Primitive.prototype.canBeRegenerated = function () {
  30203. return this._canBeRegenerated;
  30204. };
  30205. _Primitive.prototype.regenerate = function () {
  30206. if (!this._canBeRegenerated) {
  30207. return;
  30208. }
  30209. this._beingRegenerated = true;
  30210. this.setAllVerticesData(this._regenerateVertexData(), false);
  30211. this._beingRegenerated = false;
  30212. };
  30213. _Primitive.prototype.asNewGeometry = function (id) {
  30214. return _super.prototype.copy.call(this, id);
  30215. };
  30216. // overrides
  30217. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  30218. if (!this._beingRegenerated) {
  30219. return;
  30220. }
  30221. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  30222. };
  30223. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  30224. if (!this._beingRegenerated) {
  30225. return;
  30226. }
  30227. _super.prototype.setVerticesData.call(this, kind, data, false);
  30228. };
  30229. // to override
  30230. // protected
  30231. _Primitive.prototype._regenerateVertexData = function () {
  30232. throw new Error("Abstract method");
  30233. };
  30234. _Primitive.prototype.copy = function (id) {
  30235. throw new Error("Must be overriden in sub-classes.");
  30236. };
  30237. _Primitive.prototype.serialize = function () {
  30238. var serializationObject = _super.prototype.serialize.call(this);
  30239. serializationObject.canBeRegenerated = this.canBeRegenerated();
  30240. return serializationObject;
  30241. };
  30242. return _Primitive;
  30243. }(Geometry));
  30244. Primitives._Primitive = _Primitive;
  30245. var Ribbon = (function (_super) {
  30246. __extends(Ribbon, _super);
  30247. // Members
  30248. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  30249. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30250. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30251. _this.pathArray = pathArray;
  30252. _this.closeArray = closeArray;
  30253. _this.closePath = closePath;
  30254. _this.offset = offset;
  30255. _this.side = side;
  30256. return _this;
  30257. }
  30258. Ribbon.prototype._regenerateVertexData = function () {
  30259. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  30260. };
  30261. Ribbon.prototype.copy = function (id) {
  30262. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  30263. };
  30264. return Ribbon;
  30265. }(_Primitive));
  30266. Primitives.Ribbon = Ribbon;
  30267. var Box = (function (_super) {
  30268. __extends(Box, _super);
  30269. // Members
  30270. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  30271. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30272. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30273. _this.size = size;
  30274. _this.side = side;
  30275. return _this;
  30276. }
  30277. Box.prototype._regenerateVertexData = function () {
  30278. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  30279. };
  30280. Box.prototype.copy = function (id) {
  30281. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  30282. };
  30283. Box.prototype.serialize = function () {
  30284. var serializationObject = _super.prototype.serialize.call(this);
  30285. serializationObject.size = this.size;
  30286. return serializationObject;
  30287. };
  30288. Box.Parse = function (parsedBox, scene) {
  30289. if (scene.getGeometryByID(parsedBox.id)) {
  30290. return null; // null since geometry could be something else than a box...
  30291. }
  30292. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  30293. if (BABYLON.Tags) {
  30294. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  30295. }
  30296. scene.pushGeometry(box, true);
  30297. return box;
  30298. };
  30299. return Box;
  30300. }(_Primitive));
  30301. Primitives.Box = Box;
  30302. var Sphere = (function (_super) {
  30303. __extends(Sphere, _super);
  30304. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  30305. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30306. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30307. _this.segments = segments;
  30308. _this.diameter = diameter;
  30309. _this.side = side;
  30310. return _this;
  30311. }
  30312. Sphere.prototype._regenerateVertexData = function () {
  30313. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  30314. };
  30315. Sphere.prototype.copy = function (id) {
  30316. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  30317. };
  30318. Sphere.prototype.serialize = function () {
  30319. var serializationObject = _super.prototype.serialize.call(this);
  30320. serializationObject.segments = this.segments;
  30321. serializationObject.diameter = this.diameter;
  30322. return serializationObject;
  30323. };
  30324. Sphere.Parse = function (parsedSphere, scene) {
  30325. if (scene.getGeometryByID(parsedSphere.id)) {
  30326. return null; // null since geometry could be something else than a sphere...
  30327. }
  30328. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  30329. if (BABYLON.Tags) {
  30330. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  30331. }
  30332. scene.pushGeometry(sphere, true);
  30333. return sphere;
  30334. };
  30335. return Sphere;
  30336. }(_Primitive));
  30337. Primitives.Sphere = Sphere;
  30338. var Disc = (function (_super) {
  30339. __extends(Disc, _super);
  30340. // Members
  30341. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  30342. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30343. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30344. _this.radius = radius;
  30345. _this.tessellation = tessellation;
  30346. _this.side = side;
  30347. return _this;
  30348. }
  30349. Disc.prototype._regenerateVertexData = function () {
  30350. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  30351. };
  30352. Disc.prototype.copy = function (id) {
  30353. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  30354. };
  30355. return Disc;
  30356. }(_Primitive));
  30357. Primitives.Disc = Disc;
  30358. var Cylinder = (function (_super) {
  30359. __extends(Cylinder, _super);
  30360. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  30361. if (subdivisions === void 0) { subdivisions = 1; }
  30362. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30363. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30364. _this.height = height;
  30365. _this.diameterTop = diameterTop;
  30366. _this.diameterBottom = diameterBottom;
  30367. _this.tessellation = tessellation;
  30368. _this.subdivisions = subdivisions;
  30369. _this.side = side;
  30370. return _this;
  30371. }
  30372. Cylinder.prototype._regenerateVertexData = function () {
  30373. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  30374. };
  30375. Cylinder.prototype.copy = function (id) {
  30376. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  30377. };
  30378. Cylinder.prototype.serialize = function () {
  30379. var serializationObject = _super.prototype.serialize.call(this);
  30380. serializationObject.height = this.height;
  30381. serializationObject.diameterTop = this.diameterTop;
  30382. serializationObject.diameterBottom = this.diameterBottom;
  30383. serializationObject.tessellation = this.tessellation;
  30384. return serializationObject;
  30385. };
  30386. Cylinder.Parse = function (parsedCylinder, scene) {
  30387. if (scene.getGeometryByID(parsedCylinder.id)) {
  30388. return null; // null since geometry could be something else than a cylinder...
  30389. }
  30390. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  30391. if (BABYLON.Tags) {
  30392. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  30393. }
  30394. scene.pushGeometry(cylinder, true);
  30395. return cylinder;
  30396. };
  30397. return Cylinder;
  30398. }(_Primitive));
  30399. Primitives.Cylinder = Cylinder;
  30400. var Torus = (function (_super) {
  30401. __extends(Torus, _super);
  30402. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  30403. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30404. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30405. _this.diameter = diameter;
  30406. _this.thickness = thickness;
  30407. _this.tessellation = tessellation;
  30408. _this.side = side;
  30409. return _this;
  30410. }
  30411. Torus.prototype._regenerateVertexData = function () {
  30412. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  30413. };
  30414. Torus.prototype.copy = function (id) {
  30415. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  30416. };
  30417. Torus.prototype.serialize = function () {
  30418. var serializationObject = _super.prototype.serialize.call(this);
  30419. serializationObject.diameter = this.diameter;
  30420. serializationObject.thickness = this.thickness;
  30421. serializationObject.tessellation = this.tessellation;
  30422. return serializationObject;
  30423. };
  30424. Torus.Parse = function (parsedTorus, scene) {
  30425. if (scene.getGeometryByID(parsedTorus.id)) {
  30426. return null; // null since geometry could be something else than a torus...
  30427. }
  30428. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  30429. if (BABYLON.Tags) {
  30430. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  30431. }
  30432. scene.pushGeometry(torus, true);
  30433. return torus;
  30434. };
  30435. return Torus;
  30436. }(_Primitive));
  30437. Primitives.Torus = Torus;
  30438. var Ground = (function (_super) {
  30439. __extends(Ground, _super);
  30440. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  30441. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30442. _this.width = width;
  30443. _this.height = height;
  30444. _this.subdivisions = subdivisions;
  30445. return _this;
  30446. }
  30447. Ground.prototype._regenerateVertexData = function () {
  30448. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  30449. };
  30450. Ground.prototype.copy = function (id) {
  30451. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  30452. };
  30453. Ground.prototype.serialize = function () {
  30454. var serializationObject = _super.prototype.serialize.call(this);
  30455. serializationObject.width = this.width;
  30456. serializationObject.height = this.height;
  30457. serializationObject.subdivisions = this.subdivisions;
  30458. return serializationObject;
  30459. };
  30460. Ground.Parse = function (parsedGround, scene) {
  30461. if (scene.getGeometryByID(parsedGround.id)) {
  30462. return null; // null since geometry could be something else than a ground...
  30463. }
  30464. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  30465. if (BABYLON.Tags) {
  30466. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  30467. }
  30468. scene.pushGeometry(ground, true);
  30469. return ground;
  30470. };
  30471. return Ground;
  30472. }(_Primitive));
  30473. Primitives.Ground = Ground;
  30474. var TiledGround = (function (_super) {
  30475. __extends(TiledGround, _super);
  30476. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  30477. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30478. _this.xmin = xmin;
  30479. _this.zmin = zmin;
  30480. _this.xmax = xmax;
  30481. _this.zmax = zmax;
  30482. _this.subdivisions = subdivisions;
  30483. _this.precision = precision;
  30484. return _this;
  30485. }
  30486. TiledGround.prototype._regenerateVertexData = function () {
  30487. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  30488. };
  30489. TiledGround.prototype.copy = function (id) {
  30490. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  30491. };
  30492. return TiledGround;
  30493. }(_Primitive));
  30494. Primitives.TiledGround = TiledGround;
  30495. var Plane = (function (_super) {
  30496. __extends(Plane, _super);
  30497. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  30498. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30499. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30500. _this.size = size;
  30501. _this.side = side;
  30502. return _this;
  30503. }
  30504. Plane.prototype._regenerateVertexData = function () {
  30505. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  30506. };
  30507. Plane.prototype.copy = function (id) {
  30508. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  30509. };
  30510. Plane.prototype.serialize = function () {
  30511. var serializationObject = _super.prototype.serialize.call(this);
  30512. serializationObject.size = this.size;
  30513. return serializationObject;
  30514. };
  30515. Plane.Parse = function (parsedPlane, scene) {
  30516. if (scene.getGeometryByID(parsedPlane.id)) {
  30517. return null; // null since geometry could be something else than a ground...
  30518. }
  30519. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  30520. if (BABYLON.Tags) {
  30521. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  30522. }
  30523. scene.pushGeometry(plane, true);
  30524. return plane;
  30525. };
  30526. return Plane;
  30527. }(_Primitive));
  30528. Primitives.Plane = Plane;
  30529. var TorusKnot = (function (_super) {
  30530. __extends(TorusKnot, _super);
  30531. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  30532. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30533. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30534. _this.radius = radius;
  30535. _this.tube = tube;
  30536. _this.radialSegments = radialSegments;
  30537. _this.tubularSegments = tubularSegments;
  30538. _this.p = p;
  30539. _this.q = q;
  30540. _this.side = side;
  30541. return _this;
  30542. }
  30543. TorusKnot.prototype._regenerateVertexData = function () {
  30544. 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 });
  30545. };
  30546. TorusKnot.prototype.copy = function (id) {
  30547. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  30548. };
  30549. TorusKnot.prototype.serialize = function () {
  30550. var serializationObject = _super.prototype.serialize.call(this);
  30551. serializationObject.radius = this.radius;
  30552. serializationObject.tube = this.tube;
  30553. serializationObject.radialSegments = this.radialSegments;
  30554. serializationObject.tubularSegments = this.tubularSegments;
  30555. serializationObject.p = this.p;
  30556. serializationObject.q = this.q;
  30557. return serializationObject;
  30558. };
  30559. ;
  30560. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  30561. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  30562. return null; // null since geometry could be something else than a ground...
  30563. }
  30564. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  30565. if (BABYLON.Tags) {
  30566. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  30567. }
  30568. scene.pushGeometry(torusKnot, true);
  30569. return torusKnot;
  30570. };
  30571. return TorusKnot;
  30572. }(_Primitive));
  30573. Primitives.TorusKnot = TorusKnot;
  30574. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  30575. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  30576. })(BABYLON || (BABYLON = {}));
  30577. //# sourceMappingURL=babylon.geometry.js.map
  30578. var BABYLON;
  30579. (function (BABYLON) {
  30580. var PostProcessManager = (function () {
  30581. function PostProcessManager(scene) {
  30582. this._vertexBuffers = {};
  30583. this._scene = scene;
  30584. }
  30585. PostProcessManager.prototype._prepareBuffers = function () {
  30586. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  30587. return;
  30588. }
  30589. // VBO
  30590. var vertices = [];
  30591. vertices.push(1, 1);
  30592. vertices.push(-1, 1);
  30593. vertices.push(-1, -1);
  30594. vertices.push(1, -1);
  30595. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  30596. this._buildIndexBuffer();
  30597. };
  30598. PostProcessManager.prototype._buildIndexBuffer = function () {
  30599. // Indices
  30600. var indices = [];
  30601. indices.push(0);
  30602. indices.push(1);
  30603. indices.push(2);
  30604. indices.push(0);
  30605. indices.push(2);
  30606. indices.push(3);
  30607. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  30608. };
  30609. PostProcessManager.prototype._rebuild = function () {
  30610. if (!this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  30611. return;
  30612. }
  30613. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  30614. this._buildIndexBuffer();
  30615. };
  30616. // Methods
  30617. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  30618. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  30619. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30620. return false;
  30621. }
  30622. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  30623. return true;
  30624. };
  30625. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  30626. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  30627. var engine = this._scene.getEngine();
  30628. for (var index = 0; index < postProcesses.length; index++) {
  30629. if (index < postProcesses.length - 1) {
  30630. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30631. }
  30632. else {
  30633. if (targetTexture) {
  30634. engine.bindFramebuffer(targetTexture, 0, null, null, forceFullscreenViewport);
  30635. }
  30636. else {
  30637. engine.restoreDefaultFramebuffer();
  30638. }
  30639. }
  30640. var pp = postProcesses[index];
  30641. var effect = pp.apply();
  30642. if (effect) {
  30643. pp.onBeforeRenderObservable.notifyObservers(effect);
  30644. // VBOs
  30645. this._prepareBuffers();
  30646. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30647. // Draw order
  30648. engine.draw(true, 0, 6);
  30649. pp.onAfterRenderObservable.notifyObservers(effect);
  30650. }
  30651. }
  30652. // Restore depth buffer
  30653. engine.setDepthBuffer(true);
  30654. engine.setDepthWrite(true);
  30655. };
  30656. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  30657. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  30658. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  30659. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30660. return;
  30661. }
  30662. var engine = this._scene.getEngine();
  30663. for (var index = 0, len = postProcesses.length; index < len; index++) {
  30664. if (index < len - 1) {
  30665. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30666. }
  30667. else {
  30668. if (targetTexture) {
  30669. engine.bindFramebuffer(targetTexture, faceIndex, null, null, forceFullscreenViewport);
  30670. }
  30671. else {
  30672. engine.restoreDefaultFramebuffer();
  30673. }
  30674. }
  30675. if (doNotPresent) {
  30676. break;
  30677. }
  30678. var pp = postProcesses[index];
  30679. var effect = pp.apply();
  30680. if (effect) {
  30681. pp.onBeforeRenderObservable.notifyObservers(effect);
  30682. // VBOs
  30683. this._prepareBuffers();
  30684. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30685. // Draw order
  30686. engine.draw(true, 0, 6);
  30687. pp.onAfterRenderObservable.notifyObservers(effect);
  30688. }
  30689. }
  30690. // Restore states
  30691. engine.setDepthBuffer(true);
  30692. engine.setDepthWrite(true);
  30693. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  30694. };
  30695. PostProcessManager.prototype.dispose = function () {
  30696. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  30697. if (buffer) {
  30698. buffer.dispose();
  30699. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  30700. }
  30701. if (this._indexBuffer) {
  30702. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  30703. this._indexBuffer = null;
  30704. }
  30705. };
  30706. return PostProcessManager;
  30707. }());
  30708. BABYLON.PostProcessManager = PostProcessManager;
  30709. })(BABYLON || (BABYLON = {}));
  30710. //# sourceMappingURL=babylon.postProcessManager.js.map
  30711. var BABYLON;
  30712. (function (BABYLON) {
  30713. /**
  30714. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  30715. */
  30716. var PerformanceMonitor = (function () {
  30717. /**
  30718. * constructor
  30719. * @param frameSampleSize The number of samples required to saturate the sliding window
  30720. */
  30721. function PerformanceMonitor(frameSampleSize) {
  30722. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  30723. this._enabled = true;
  30724. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  30725. }
  30726. /**
  30727. * Samples current frame
  30728. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  30729. */
  30730. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  30731. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  30732. if (!this._enabled)
  30733. return;
  30734. if (this._lastFrameTimeMs != null) {
  30735. var dt = timeMs - this._lastFrameTimeMs;
  30736. this._rollingFrameTime.add(dt);
  30737. }
  30738. this._lastFrameTimeMs = timeMs;
  30739. };
  30740. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  30741. /**
  30742. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30743. * @return Average frame time in milliseconds
  30744. */
  30745. get: function () {
  30746. return this._rollingFrameTime.average;
  30747. },
  30748. enumerable: true,
  30749. configurable: true
  30750. });
  30751. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  30752. /**
  30753. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30754. * @return Frame time variance in milliseconds squared
  30755. */
  30756. get: function () {
  30757. return this._rollingFrameTime.variance;
  30758. },
  30759. enumerable: true,
  30760. configurable: true
  30761. });
  30762. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  30763. /**
  30764. * Returns the frame time of the most recent frame
  30765. * @return Frame time in milliseconds
  30766. */
  30767. get: function () {
  30768. return this._rollingFrameTime.history(0);
  30769. },
  30770. enumerable: true,
  30771. configurable: true
  30772. });
  30773. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  30774. /**
  30775. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  30776. * @return Framerate in frames per second
  30777. */
  30778. get: function () {
  30779. return 1000.0 / this._rollingFrameTime.average;
  30780. },
  30781. enumerable: true,
  30782. configurable: true
  30783. });
  30784. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  30785. /**
  30786. * Returns the average framerate in frames per second using the most recent frame time
  30787. * @return Framerate in frames per second
  30788. */
  30789. get: function () {
  30790. return 1000.0 / this._rollingFrameTime.history(0);
  30791. },
  30792. enumerable: true,
  30793. configurable: true
  30794. });
  30795. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  30796. /**
  30797. * Returns true if enough samples have been taken to completely fill the sliding window
  30798. * @return true if saturated
  30799. */
  30800. get: function () {
  30801. return this._rollingFrameTime.isSaturated();
  30802. },
  30803. enumerable: true,
  30804. configurable: true
  30805. });
  30806. /**
  30807. * Enables contributions to the sliding window sample set
  30808. */
  30809. PerformanceMonitor.prototype.enable = function () {
  30810. this._enabled = true;
  30811. };
  30812. /**
  30813. * Disables contributions to the sliding window sample set
  30814. * Samples will not be interpolated over the disabled period
  30815. */
  30816. PerformanceMonitor.prototype.disable = function () {
  30817. this._enabled = false;
  30818. //clear last sample to avoid interpolating over the disabled period when next enabled
  30819. this._lastFrameTimeMs = null;
  30820. this._lastChangeTimeMs = null;
  30821. };
  30822. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  30823. /**
  30824. * Returns true if sampling is enabled
  30825. * @return true if enabled
  30826. */
  30827. get: function () {
  30828. return this._enabled;
  30829. },
  30830. enumerable: true,
  30831. configurable: true
  30832. });
  30833. /**
  30834. * Resets performance monitor
  30835. */
  30836. PerformanceMonitor.prototype.reset = function () {
  30837. //clear last sample to avoid interpolating over the disabled period when next enabled
  30838. this._lastFrameTimeMs = null;
  30839. this._lastChangeTimeMs = null;
  30840. //wipe record
  30841. this._rollingFrameTime.reset();
  30842. };
  30843. return PerformanceMonitor;
  30844. }());
  30845. BABYLON.PerformanceMonitor = PerformanceMonitor;
  30846. /**
  30847. * RollingAverage
  30848. *
  30849. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  30850. */
  30851. var RollingAverage = (function () {
  30852. /**
  30853. * constructor
  30854. * @param length The number of samples required to saturate the sliding window
  30855. */
  30856. function RollingAverage(length) {
  30857. this._samples = new Array(length);
  30858. this.reset();
  30859. }
  30860. /**
  30861. * Adds a sample to the sample set
  30862. * @param v The sample value
  30863. */
  30864. RollingAverage.prototype.add = function (v) {
  30865. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  30866. var delta;
  30867. //we need to check if we've already wrapped round
  30868. if (this.isSaturated()) {
  30869. //remove bottom of stack from mean
  30870. var bottomValue = this._samples[this._pos];
  30871. delta = bottomValue - this.average;
  30872. this.average -= delta / (this._sampleCount - 1);
  30873. this._m2 -= delta * (bottomValue - this.average);
  30874. }
  30875. else {
  30876. this._sampleCount++;
  30877. }
  30878. //add new value to mean
  30879. delta = v - this.average;
  30880. this.average += delta / (this._sampleCount);
  30881. this._m2 += delta * (v - this.average);
  30882. //set the new variance
  30883. this.variance = this._m2 / (this._sampleCount - 1);
  30884. this._samples[this._pos] = v;
  30885. this._pos++;
  30886. this._pos %= this._samples.length; //positive wrap around
  30887. };
  30888. /**
  30889. * Returns previously added values or null if outside of history or outside the sliding window domain
  30890. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  30891. * @return Value previously recorded with add() or null if outside of range
  30892. */
  30893. RollingAverage.prototype.history = function (i) {
  30894. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  30895. return null;
  30896. }
  30897. var i0 = this._wrapPosition(this._pos - 1.0);
  30898. return this._samples[this._wrapPosition(i0 - i)];
  30899. };
  30900. /**
  30901. * Returns true if enough samples have been taken to completely fill the sliding window
  30902. * @return true if sample-set saturated
  30903. */
  30904. RollingAverage.prototype.isSaturated = function () {
  30905. return this._sampleCount >= this._samples.length;
  30906. };
  30907. /**
  30908. * Resets the rolling average (equivalent to 0 samples taken so far)
  30909. */
  30910. RollingAverage.prototype.reset = function () {
  30911. this.average = 0;
  30912. this.variance = 0;
  30913. this._sampleCount = 0;
  30914. this._pos = 0;
  30915. this._m2 = 0;
  30916. };
  30917. /**
  30918. * Wraps a value around the sample range boundaries
  30919. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  30920. * @return Wrapped position in sample range
  30921. */
  30922. RollingAverage.prototype._wrapPosition = function (i) {
  30923. var max = this._samples.length;
  30924. return ((i % max) + max) % max;
  30925. };
  30926. return RollingAverage;
  30927. }());
  30928. BABYLON.RollingAverage = RollingAverage;
  30929. })(BABYLON || (BABYLON = {}));
  30930. //# sourceMappingURL=babylon.performanceMonitor.js.map
  30931. var BABYLON;
  30932. (function (BABYLON) {
  30933. /**
  30934. * This groups together the common properties used for image processing either in direct forward pass
  30935. * or through post processing effect depending on the use of the image processing pipeline in your scene
  30936. * or not.
  30937. */
  30938. var ImageProcessingConfiguration = (function () {
  30939. function ImageProcessingConfiguration() {
  30940. /**
  30941. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  30942. */
  30943. this.colorCurves = new BABYLON.ColorCurves();
  30944. this._colorCurvesEnabled = false;
  30945. this._colorGradingEnabled = false;
  30946. this._colorGradingWithGreenDepth = false;
  30947. this._colorGradingBGR = false;
  30948. this._exposure = 1.0;
  30949. this._toneMappingEnabled = false;
  30950. this._contrast = 1.0;
  30951. /**
  30952. * Vignette stretch size.
  30953. */
  30954. this.vignetteStretch = 0;
  30955. /**
  30956. * Vignette centre X Offset.
  30957. */
  30958. this.vignetteCentreX = 0;
  30959. /**
  30960. * Vignette centre Y Offset.
  30961. */
  30962. this.vignetteCentreY = 0;
  30963. /**
  30964. * Vignette weight or intensity of the vignette effect.
  30965. */
  30966. this.vignetteWeight = 1.5;
  30967. /**
  30968. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  30969. * if vignetteEnabled is set to true.
  30970. */
  30971. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  30972. /**
  30973. * Camera field of view used by the Vignette effect.
  30974. */
  30975. this.vignetteCameraFov = 0.5;
  30976. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  30977. this._vignetteEnabled = false;
  30978. this._applyByPostProcess = false;
  30979. /**
  30980. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  30981. * @type {BABYLON.Observable}
  30982. */
  30983. this.onUpdateParameters = new BABYLON.Observable();
  30984. }
  30985. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  30986. /**
  30987. * Gets wether the color curves effect is enabled.
  30988. */
  30989. get: function () {
  30990. return this._colorCurvesEnabled;
  30991. },
  30992. /**
  30993. * Sets wether the color curves effect is enabled.
  30994. */
  30995. set: function (value) {
  30996. if (this._colorCurvesEnabled === value) {
  30997. return;
  30998. }
  30999. this._colorCurvesEnabled = value;
  31000. this._updateParameters();
  31001. },
  31002. enumerable: true,
  31003. configurable: true
  31004. });
  31005. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  31006. /**
  31007. * Gets wether the color grading effect is enabled.
  31008. */
  31009. get: function () {
  31010. return this._colorGradingEnabled;
  31011. },
  31012. /**
  31013. * Sets wether the color grading effect is enabled.
  31014. */
  31015. set: function (value) {
  31016. if (this._colorGradingEnabled === value) {
  31017. return;
  31018. }
  31019. this._colorGradingEnabled = value;
  31020. this._updateParameters();
  31021. },
  31022. enumerable: true,
  31023. configurable: true
  31024. });
  31025. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  31026. /**
  31027. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  31028. */
  31029. get: function () {
  31030. return this._colorGradingWithGreenDepth;
  31031. },
  31032. /**
  31033. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  31034. */
  31035. set: function (value) {
  31036. if (this._colorGradingWithGreenDepth === value) {
  31037. return;
  31038. }
  31039. this._colorGradingWithGreenDepth = value;
  31040. this._updateParameters();
  31041. },
  31042. enumerable: true,
  31043. configurable: true
  31044. });
  31045. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  31046. /**
  31047. * Gets wether the color grading texture contains BGR values.
  31048. */
  31049. get: function () {
  31050. return this._colorGradingBGR;
  31051. },
  31052. /**
  31053. * Sets wether the color grading texture contains BGR values.
  31054. */
  31055. set: function (value) {
  31056. if (this._colorGradingBGR === value) {
  31057. return;
  31058. }
  31059. this._colorGradingBGR = value;
  31060. this._updateParameters();
  31061. },
  31062. enumerable: true,
  31063. configurable: true
  31064. });
  31065. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  31066. /**
  31067. * Gets the Exposure used in the effect.
  31068. */
  31069. get: function () {
  31070. return this._exposure;
  31071. },
  31072. /**
  31073. * Sets the Exposure used in the effect.
  31074. */
  31075. set: function (value) {
  31076. if (this._exposure === value) {
  31077. return;
  31078. }
  31079. this._exposure = value;
  31080. this._updateParameters();
  31081. },
  31082. enumerable: true,
  31083. configurable: true
  31084. });
  31085. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  31086. /**
  31087. * Gets wether the tone mapping effect is enabled.
  31088. */
  31089. get: function () {
  31090. return this._toneMappingEnabled;
  31091. },
  31092. /**
  31093. * Sets wether the tone mapping effect is enabled.
  31094. */
  31095. set: function (value) {
  31096. if (this._toneMappingEnabled === value) {
  31097. return;
  31098. }
  31099. this._toneMappingEnabled = value;
  31100. this._updateParameters();
  31101. },
  31102. enumerable: true,
  31103. configurable: true
  31104. });
  31105. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  31106. /**
  31107. * Gets the contrast used in the effect.
  31108. */
  31109. get: function () {
  31110. return this._contrast;
  31111. },
  31112. /**
  31113. * Sets the contrast used in the effect.
  31114. */
  31115. set: function (value) {
  31116. if (this._contrast === value) {
  31117. return;
  31118. }
  31119. this._contrast = value;
  31120. this._updateParameters();
  31121. },
  31122. enumerable: true,
  31123. configurable: true
  31124. });
  31125. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  31126. /**
  31127. * Gets the vignette blend mode allowing different kind of effect.
  31128. */
  31129. get: function () {
  31130. return this._vignetteBlendMode;
  31131. },
  31132. /**
  31133. * Sets the vignette blend mode allowing different kind of effect.
  31134. */
  31135. set: function (value) {
  31136. if (this._vignetteBlendMode === value) {
  31137. return;
  31138. }
  31139. this._vignetteBlendMode = value;
  31140. this._updateParameters();
  31141. },
  31142. enumerable: true,
  31143. configurable: true
  31144. });
  31145. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  31146. /**
  31147. * Gets wether the vignette effect is enabled.
  31148. */
  31149. get: function () {
  31150. return this._vignetteEnabled;
  31151. },
  31152. /**
  31153. * Sets wether the vignette effect is enabled.
  31154. */
  31155. set: function (value) {
  31156. if (this._vignetteEnabled === value) {
  31157. return;
  31158. }
  31159. this._vignetteEnabled = value;
  31160. this._updateParameters();
  31161. },
  31162. enumerable: true,
  31163. configurable: true
  31164. });
  31165. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  31166. /**
  31167. * Gets wether the image processing is applied through a post process or not.
  31168. */
  31169. get: function () {
  31170. return this._applyByPostProcess;
  31171. },
  31172. /**
  31173. * Sets wether the image processing is applied through a post process or not.
  31174. */
  31175. set: function (value) {
  31176. if (this._applyByPostProcess === value) {
  31177. return;
  31178. }
  31179. this._applyByPostProcess = value;
  31180. this._updateParameters();
  31181. },
  31182. enumerable: true,
  31183. configurable: true
  31184. });
  31185. /**
  31186. * Method called each time the image processing information changes requires to recompile the effect.
  31187. */
  31188. ImageProcessingConfiguration.prototype._updateParameters = function () {
  31189. this.onUpdateParameters.notifyObservers(this);
  31190. };
  31191. ImageProcessingConfiguration.prototype.getClassName = function () {
  31192. return "ImageProcessingConfiguration";
  31193. };
  31194. /**
  31195. * Prepare the list of uniforms associated with the Image Processing effects.
  31196. * @param uniformsList The list of uniforms used in the effect
  31197. * @param defines the list of defines currently in use
  31198. */
  31199. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  31200. if (defines.EXPOSURE) {
  31201. uniforms.push("exposureLinear");
  31202. }
  31203. if (defines.CONTRAST) {
  31204. uniforms.push("contrast");
  31205. }
  31206. if (defines.COLORGRADING) {
  31207. uniforms.push("colorTransformSettings");
  31208. }
  31209. if (defines.VIGNETTE) {
  31210. uniforms.push("vInverseScreenSize");
  31211. uniforms.push("vignetteSettings1");
  31212. uniforms.push("vignetteSettings2");
  31213. }
  31214. if (defines.COLORCURVES) {
  31215. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  31216. }
  31217. };
  31218. /**
  31219. * Prepare the list of samplers associated with the Image Processing effects.
  31220. * @param uniformsList The list of uniforms used in the effect
  31221. * @param defines the list of defines currently in use
  31222. */
  31223. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  31224. if (defines.COLORGRADING) {
  31225. samplersList.push("txColorTransform");
  31226. }
  31227. };
  31228. /**
  31229. * Prepare the list of defines associated to the shader.
  31230. * @param defines the list of defines to complete
  31231. */
  31232. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  31233. if (forPostProcess === void 0) { forPostProcess = false; }
  31234. if (forPostProcess !== this.applyByPostProcess) {
  31235. defines.VIGNETTE = false;
  31236. defines.TONEMAPPING = false;
  31237. defines.CONTRAST = false;
  31238. defines.EXPOSURE = false;
  31239. defines.COLORCURVES = false;
  31240. defines.COLORGRADING = false;
  31241. defines.IMAGEPROCESSING = false;
  31242. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  31243. return;
  31244. }
  31245. defines.VIGNETTE = this.vignetteEnabled;
  31246. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  31247. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  31248. defines.TONEMAPPING = this.toneMappingEnabled;
  31249. defines.CONTRAST = (this.contrast !== 1.0);
  31250. defines.EXPOSURE = (this.exposure !== 1.0);
  31251. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  31252. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  31253. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  31254. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  31255. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  31256. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  31257. };
  31258. /**
  31259. * Returns true if all the image processing information are ready.
  31260. */
  31261. ImageProcessingConfiguration.prototype.isReady = function () {
  31262. // Color Grading texure can not be none blocking.
  31263. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  31264. };
  31265. /**
  31266. * Binds the image processing to the shader.
  31267. * @param effect The effect to bind to
  31268. */
  31269. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  31270. if (aspectRatio === void 0) { aspectRatio = 1; }
  31271. // Color Curves
  31272. if (this._colorCurvesEnabled) {
  31273. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  31274. }
  31275. // Vignette
  31276. if (this._vignetteEnabled) {
  31277. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  31278. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  31279. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  31280. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  31281. var vignetteScaleX = vignetteScaleY * aspectRatio;
  31282. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  31283. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  31284. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  31285. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  31286. var vignettePower = -2.0 * this.vignetteWeight;
  31287. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  31288. }
  31289. // Exposure
  31290. effect.setFloat("exposureLinear", this.exposure);
  31291. // Contrast
  31292. effect.setFloat("contrast", this.contrast);
  31293. // Color transform settings
  31294. if (this.colorGradingTexture) {
  31295. effect.setTexture("txColorTransform", this.colorGradingTexture);
  31296. var textureSize = this.colorGradingTexture.getSize().height;
  31297. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  31298. 0.5 / textureSize, // textureOffset
  31299. textureSize, // textureSize
  31300. this.colorGradingTexture.level // weight
  31301. );
  31302. }
  31303. };
  31304. /**
  31305. * Clones the current image processing instance.
  31306. * @return The cloned image processing
  31307. */
  31308. ImageProcessingConfiguration.prototype.clone = function () {
  31309. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  31310. };
  31311. /**
  31312. * Serializes the current image processing instance to a json representation.
  31313. * @return a JSON representation
  31314. */
  31315. ImageProcessingConfiguration.prototype.serialize = function () {
  31316. return BABYLON.SerializationHelper.Serialize(this);
  31317. };
  31318. /**
  31319. * Parses the image processing from a json representation.
  31320. * @param source the JSON source to parse
  31321. * @return The parsed image processing
  31322. */
  31323. ImageProcessingConfiguration.Parse = function (source) {
  31324. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  31325. };
  31326. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  31327. /**
  31328. * Used to apply the vignette as a mix with the pixel color.
  31329. */
  31330. get: function () {
  31331. return this._VIGNETTEMODE_MULTIPLY;
  31332. },
  31333. enumerable: true,
  31334. configurable: true
  31335. });
  31336. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  31337. /**
  31338. * Used to apply the vignette as a replacement of the pixel color.
  31339. */
  31340. get: function () {
  31341. return this._VIGNETTEMODE_OPAQUE;
  31342. },
  31343. enumerable: true,
  31344. configurable: true
  31345. });
  31346. // Static constants associated to the image processing.
  31347. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  31348. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  31349. __decorate([
  31350. BABYLON.serializeAsColorCurves()
  31351. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  31352. __decorate([
  31353. BABYLON.serialize()
  31354. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  31355. __decorate([
  31356. BABYLON.serializeAsTexture()
  31357. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  31358. __decorate([
  31359. BABYLON.serialize()
  31360. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  31361. __decorate([
  31362. BABYLON.serialize()
  31363. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  31364. __decorate([
  31365. BABYLON.serialize()
  31366. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  31367. __decorate([
  31368. BABYLON.serialize()
  31369. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  31370. __decorate([
  31371. BABYLON.serialize()
  31372. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  31373. __decorate([
  31374. BABYLON.serialize()
  31375. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  31376. __decorate([
  31377. BABYLON.serialize()
  31378. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  31379. __decorate([
  31380. BABYLON.serialize()
  31381. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  31382. __decorate([
  31383. BABYLON.serialize()
  31384. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  31385. __decorate([
  31386. BABYLON.serialize()
  31387. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  31388. __decorate([
  31389. BABYLON.serializeAsColor4()
  31390. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  31391. __decorate([
  31392. BABYLON.serialize()
  31393. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  31394. __decorate([
  31395. BABYLON.serialize()
  31396. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  31397. __decorate([
  31398. BABYLON.serialize()
  31399. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  31400. __decorate([
  31401. BABYLON.serialize()
  31402. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  31403. return ImageProcessingConfiguration;
  31404. }());
  31405. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  31406. })(BABYLON || (BABYLON = {}));
  31407. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  31408. var BABYLON;
  31409. (function (BABYLON) {
  31410. /**
  31411. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  31412. * It can help converting any input color in a desired output one. This can then be used to create effects
  31413. * from sepia, black and white to sixties or futuristic rendering...
  31414. *
  31415. * The only supported format is currently 3dl.
  31416. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  31417. */
  31418. var ColorGradingTexture = (function (_super) {
  31419. __extends(ColorGradingTexture, _super);
  31420. /**
  31421. * Instantiates a ColorGradingTexture from the following parameters.
  31422. *
  31423. * @param url The location of the color gradind data (currently only supporting 3dl)
  31424. * @param scene The scene the texture will be used in
  31425. */
  31426. function ColorGradingTexture(url, scene) {
  31427. var _this = _super.call(this, scene) || this;
  31428. if (!url) {
  31429. return _this;
  31430. }
  31431. _this._textureMatrix = BABYLON.Matrix.Identity();
  31432. _this.name = url;
  31433. _this.url = url;
  31434. _this.hasAlpha = false;
  31435. _this.isCube = false;
  31436. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31437. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31438. _this.anisotropicFilteringLevel = 1;
  31439. _this._texture = _this._getFromCache(url, true);
  31440. if (!_this._texture) {
  31441. if (!scene.useDelayedTextureLoading) {
  31442. _this.loadTexture();
  31443. }
  31444. else {
  31445. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31446. }
  31447. }
  31448. return _this;
  31449. }
  31450. /**
  31451. * Returns the texture matrix used in most of the material.
  31452. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  31453. */
  31454. ColorGradingTexture.prototype.getTextureMatrix = function () {
  31455. return this._textureMatrix;
  31456. };
  31457. /**
  31458. * Occurs when the file being loaded is a .3dl LUT file.
  31459. */
  31460. ColorGradingTexture.prototype.load3dlTexture = function () {
  31461. var _this = this;
  31462. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31463. this._texture = texture;
  31464. var callback = function (text) {
  31465. var data;
  31466. var tempData;
  31467. var line;
  31468. var lines = text.split('\n');
  31469. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  31470. var maxColor = 0;
  31471. for (var i = 0; i < lines.length; i++) {
  31472. line = lines[i];
  31473. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  31474. continue;
  31475. if (line.indexOf('#') === 0)
  31476. continue;
  31477. var words = line.split(" ");
  31478. if (size === 0) {
  31479. // Number of space + one
  31480. size = words.length;
  31481. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  31482. tempData = new Float32Array(size * size * size * 4);
  31483. continue;
  31484. }
  31485. if (size != 0) {
  31486. var r = Math.max(parseInt(words[0]), 0);
  31487. var g = Math.max(parseInt(words[1]), 0);
  31488. var b = Math.max(parseInt(words[2]), 0);
  31489. maxColor = Math.max(r, maxColor);
  31490. maxColor = Math.max(g, maxColor);
  31491. maxColor = Math.max(b, maxColor);
  31492. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  31493. tempData[pixelStorageIndex + 0] = r;
  31494. tempData[pixelStorageIndex + 1] = g;
  31495. tempData[pixelStorageIndex + 2] = b;
  31496. pixelIndexSlice++;
  31497. if (pixelIndexSlice % size == 0) {
  31498. pixelIndexH++;
  31499. pixelIndexSlice = 0;
  31500. if (pixelIndexH % size == 0) {
  31501. pixelIndexW++;
  31502. pixelIndexH = 0;
  31503. }
  31504. }
  31505. }
  31506. }
  31507. for (var i = 0; i < tempData.length; i++) {
  31508. if (i > 0 && (i + 1) % 4 === 0) {
  31509. data[i] = 255;
  31510. }
  31511. else {
  31512. var value = tempData[i];
  31513. data[i] = (value / maxColor * 255);
  31514. }
  31515. }
  31516. texture.updateSize(size * size, size);
  31517. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  31518. };
  31519. BABYLON.Tools.LoadFile(this.url, callback);
  31520. return this._texture;
  31521. };
  31522. /**
  31523. * Starts the loading process of the texture.
  31524. */
  31525. ColorGradingTexture.prototype.loadTexture = function () {
  31526. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  31527. this.load3dlTexture();
  31528. }
  31529. };
  31530. /**
  31531. * Clones the color gradind texture.
  31532. */
  31533. ColorGradingTexture.prototype.clone = function () {
  31534. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  31535. // Base texture
  31536. newTexture.level = this.level;
  31537. return newTexture;
  31538. };
  31539. /**
  31540. * Called during delayed load for textures.
  31541. */
  31542. ColorGradingTexture.prototype.delayLoad = function () {
  31543. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31544. return;
  31545. }
  31546. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31547. this._texture = this._getFromCache(this.url, true);
  31548. if (!this._texture) {
  31549. this.loadTexture();
  31550. }
  31551. };
  31552. /**
  31553. * Parses a color grading texture serialized by Babylon.
  31554. * @param parsedTexture The texture information being parsedTexture
  31555. * @param scene The scene to load the texture in
  31556. * @param rootUrl The root url of the data assets to load
  31557. * @return A color gradind texture
  31558. */
  31559. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  31560. var texture = null;
  31561. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  31562. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  31563. texture.name = parsedTexture.name;
  31564. texture.level = parsedTexture.level;
  31565. }
  31566. return texture;
  31567. };
  31568. /**
  31569. * Serializes the LUT texture to json format.
  31570. */
  31571. ColorGradingTexture.prototype.serialize = function () {
  31572. if (!this.name) {
  31573. return null;
  31574. }
  31575. var serializationObject = {};
  31576. serializationObject.name = this.name;
  31577. serializationObject.level = this.level;
  31578. serializationObject.customType = "BABYLON.ColorGradingTexture";
  31579. return serializationObject;
  31580. };
  31581. /**
  31582. * Empty line regex stored for GC.
  31583. */
  31584. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  31585. return ColorGradingTexture;
  31586. }(BABYLON.BaseTexture));
  31587. BABYLON.ColorGradingTexture = ColorGradingTexture;
  31588. })(BABYLON || (BABYLON = {}));
  31589. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  31590. var BABYLON;
  31591. (function (BABYLON) {
  31592. /**
  31593. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  31594. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  31595. * 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;
  31596. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  31597. */
  31598. var ColorCurves = (function () {
  31599. function ColorCurves() {
  31600. this._dirty = true;
  31601. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  31602. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  31603. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  31604. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  31605. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  31606. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  31607. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  31608. this._globalHue = 30;
  31609. this._globalDensity = 0;
  31610. this._globalSaturation = 0;
  31611. this._globalExposure = 0;
  31612. this._highlightsHue = 30;
  31613. this._highlightsDensity = 0;
  31614. this._highlightsSaturation = 0;
  31615. this._highlightsExposure = 0;
  31616. this._midtonesHue = 30;
  31617. this._midtonesDensity = 0;
  31618. this._midtonesSaturation = 0;
  31619. this._midtonesExposure = 0;
  31620. this._shadowsHue = 30;
  31621. this._shadowsDensity = 0;
  31622. this._shadowsSaturation = 0;
  31623. this._shadowsExposure = 0;
  31624. }
  31625. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  31626. /**
  31627. * Gets the global Hue value.
  31628. * 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).
  31629. */
  31630. get: function () {
  31631. return this._globalHue;
  31632. },
  31633. /**
  31634. * Sets the global Hue value.
  31635. * 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).
  31636. */
  31637. set: function (value) {
  31638. this._globalHue = value;
  31639. this._dirty = true;
  31640. },
  31641. enumerable: true,
  31642. configurable: true
  31643. });
  31644. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  31645. /**
  31646. * Gets the global Density value.
  31647. * 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.
  31648. * Values less than zero provide a filter of opposite hue.
  31649. */
  31650. get: function () {
  31651. return this._globalDensity;
  31652. },
  31653. /**
  31654. * Sets the global Density value.
  31655. * 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.
  31656. * Values less than zero provide a filter of opposite hue.
  31657. */
  31658. set: function (value) {
  31659. this._globalDensity = value;
  31660. this._dirty = true;
  31661. },
  31662. enumerable: true,
  31663. configurable: true
  31664. });
  31665. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  31666. /**
  31667. * Gets the global Saturation value.
  31668. * 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.
  31669. */
  31670. get: function () {
  31671. return this._globalSaturation;
  31672. },
  31673. /**
  31674. * Sets the global Saturation value.
  31675. * 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.
  31676. */
  31677. set: function (value) {
  31678. this._globalSaturation = value;
  31679. this._dirty = true;
  31680. },
  31681. enumerable: true,
  31682. configurable: true
  31683. });
  31684. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  31685. /**
  31686. * Gets the highlights Hue value.
  31687. * 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).
  31688. */
  31689. get: function () {
  31690. return this._highlightsHue;
  31691. },
  31692. /**
  31693. * Sets the highlights Hue value.
  31694. * 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).
  31695. */
  31696. set: function (value) {
  31697. this._highlightsHue = value;
  31698. this._dirty = true;
  31699. },
  31700. enumerable: true,
  31701. configurable: true
  31702. });
  31703. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  31704. /**
  31705. * Gets the highlights Density value.
  31706. * 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.
  31707. * Values less than zero provide a filter of opposite hue.
  31708. */
  31709. get: function () {
  31710. return this._highlightsDensity;
  31711. },
  31712. /**
  31713. * Sets the highlights Density value.
  31714. * 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.
  31715. * Values less than zero provide a filter of opposite hue.
  31716. */
  31717. set: function (value) {
  31718. this._highlightsDensity = value;
  31719. this._dirty = true;
  31720. },
  31721. enumerable: true,
  31722. configurable: true
  31723. });
  31724. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  31725. /**
  31726. * Gets the highlights Saturation value.
  31727. * 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.
  31728. */
  31729. get: function () {
  31730. return this._highlightsSaturation;
  31731. },
  31732. /**
  31733. * Sets the highlights Saturation value.
  31734. * 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.
  31735. */
  31736. set: function (value) {
  31737. this._highlightsSaturation = value;
  31738. this._dirty = true;
  31739. },
  31740. enumerable: true,
  31741. configurable: true
  31742. });
  31743. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  31744. /**
  31745. * Gets the highlights Exposure value.
  31746. * 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.
  31747. */
  31748. get: function () {
  31749. return this._highlightsExposure;
  31750. },
  31751. /**
  31752. * Sets the highlights Exposure value.
  31753. * 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.
  31754. */
  31755. set: function (value) {
  31756. this._highlightsExposure = value;
  31757. this._dirty = true;
  31758. },
  31759. enumerable: true,
  31760. configurable: true
  31761. });
  31762. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  31763. /**
  31764. * Gets the midtones Hue value.
  31765. * 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).
  31766. */
  31767. get: function () {
  31768. return this._midtonesHue;
  31769. },
  31770. /**
  31771. * Sets the midtones Hue value.
  31772. * 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).
  31773. */
  31774. set: function (value) {
  31775. this._midtonesHue = value;
  31776. this._dirty = true;
  31777. },
  31778. enumerable: true,
  31779. configurable: true
  31780. });
  31781. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  31782. /**
  31783. * Gets the midtones Density value.
  31784. * 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.
  31785. * Values less than zero provide a filter of opposite hue.
  31786. */
  31787. get: function () {
  31788. return this._midtonesDensity;
  31789. },
  31790. /**
  31791. * Sets the midtones Density value.
  31792. * 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.
  31793. * Values less than zero provide a filter of opposite hue.
  31794. */
  31795. set: function (value) {
  31796. this._midtonesDensity = value;
  31797. this._dirty = true;
  31798. },
  31799. enumerable: true,
  31800. configurable: true
  31801. });
  31802. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  31803. /**
  31804. * Gets the midtones Saturation value.
  31805. * 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.
  31806. */
  31807. get: function () {
  31808. return this._midtonesSaturation;
  31809. },
  31810. /**
  31811. * Sets the midtones Saturation value.
  31812. * 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.
  31813. */
  31814. set: function (value) {
  31815. this._midtonesSaturation = value;
  31816. this._dirty = true;
  31817. },
  31818. enumerable: true,
  31819. configurable: true
  31820. });
  31821. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  31822. /**
  31823. * Gets the midtones Exposure value.
  31824. * 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.
  31825. */
  31826. get: function () {
  31827. return this._midtonesExposure;
  31828. },
  31829. /**
  31830. * Sets the midtones Exposure value.
  31831. * 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.
  31832. */
  31833. set: function (value) {
  31834. this._midtonesExposure = value;
  31835. this._dirty = true;
  31836. },
  31837. enumerable: true,
  31838. configurable: true
  31839. });
  31840. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  31841. /**
  31842. * Gets the shadows Hue value.
  31843. * 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).
  31844. */
  31845. get: function () {
  31846. return this._shadowsHue;
  31847. },
  31848. /**
  31849. * Sets the shadows Hue value.
  31850. * 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).
  31851. */
  31852. set: function (value) {
  31853. this._shadowsHue = value;
  31854. this._dirty = true;
  31855. },
  31856. enumerable: true,
  31857. configurable: true
  31858. });
  31859. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  31860. /**
  31861. * Gets the shadows Density value.
  31862. * 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.
  31863. * Values less than zero provide a filter of opposite hue.
  31864. */
  31865. get: function () {
  31866. return this._shadowsDensity;
  31867. },
  31868. /**
  31869. * Sets the shadows Density value.
  31870. * 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.
  31871. * Values less than zero provide a filter of opposite hue.
  31872. */
  31873. set: function (value) {
  31874. this._shadowsDensity = value;
  31875. this._dirty = true;
  31876. },
  31877. enumerable: true,
  31878. configurable: true
  31879. });
  31880. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  31881. /**
  31882. * Gets the shadows Saturation value.
  31883. * 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.
  31884. */
  31885. get: function () {
  31886. return this._shadowsSaturation;
  31887. },
  31888. /**
  31889. * Sets the shadows Saturation value.
  31890. * 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.
  31891. */
  31892. set: function (value) {
  31893. this._shadowsSaturation = value;
  31894. this._dirty = true;
  31895. },
  31896. enumerable: true,
  31897. configurable: true
  31898. });
  31899. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  31900. /**
  31901. * Gets the shadows Exposure value.
  31902. * 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.
  31903. */
  31904. get: function () {
  31905. return this._shadowsExposure;
  31906. },
  31907. /**
  31908. * Sets the shadows Exposure value.
  31909. * 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.
  31910. */
  31911. set: function (value) {
  31912. this._shadowsExposure = value;
  31913. this._dirty = true;
  31914. },
  31915. enumerable: true,
  31916. configurable: true
  31917. });
  31918. ColorCurves.prototype.getClassName = function () {
  31919. return "ColorCurves";
  31920. };
  31921. /**
  31922. * Binds the color curves to the shader.
  31923. * @param colorCurves The color curve to bind
  31924. * @param effect The effect to bind to
  31925. */
  31926. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  31927. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  31928. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  31929. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  31930. if (colorCurves._dirty) {
  31931. colorCurves._dirty = false;
  31932. // Fill in global info.
  31933. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  31934. // Compute highlights info.
  31935. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  31936. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  31937. // Compute midtones info.
  31938. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  31939. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  31940. // Compute shadows info.
  31941. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  31942. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  31943. // Compute deltas (neutral is midtones).
  31944. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  31945. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  31946. }
  31947. if (effect) {
  31948. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  31949. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  31950. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  31951. }
  31952. };
  31953. /**
  31954. * Prepare the list of uniforms associated with the ColorCurves effects.
  31955. * @param uniformsList The list of uniforms used in the effect
  31956. */
  31957. ColorCurves.PrepareUniforms = function (uniformsList) {
  31958. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  31959. };
  31960. /**
  31961. * Returns color grading data based on a hue, density, saturation and exposure value.
  31962. * @param filterHue The hue of the color filter.
  31963. * @param filterDensity The density of the color filter.
  31964. * @param saturation The saturation.
  31965. * @param exposure The exposure.
  31966. * @param result The result data container.
  31967. */
  31968. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  31969. if (hue == null) {
  31970. return;
  31971. }
  31972. hue = ColorCurves.clamp(hue, 0, 360);
  31973. density = ColorCurves.clamp(density, -100, 100);
  31974. saturation = ColorCurves.clamp(saturation, -100, 100);
  31975. exposure = ColorCurves.clamp(exposure, -100, 100);
  31976. // Remap the slider/config filter density with non-linear mapping and also scale by half
  31977. // so that the maximum filter density is only 50% control. This provides fine control
  31978. // for small values and reasonable range.
  31979. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  31980. density *= 0.5;
  31981. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  31982. if (density < 0) {
  31983. density *= -1;
  31984. hue = (hue + 180) % 360;
  31985. }
  31986. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  31987. result.scaleToRef(2, result);
  31988. result.a = 1 + 0.01 * saturation;
  31989. };
  31990. /**
  31991. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  31992. * @param value The input slider value in range [-100,100].
  31993. * @returns Adjusted value.
  31994. */
  31995. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  31996. value /= 100;
  31997. var x = Math.abs(value);
  31998. x = Math.pow(x, 2);
  31999. if (value < 0) {
  32000. x *= -1;
  32001. }
  32002. x *= 100;
  32003. return x;
  32004. };
  32005. /**
  32006. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  32007. * @param hue The hue (H) input.
  32008. * @param saturation The saturation (S) input.
  32009. * @param brightness The brightness (B) input.
  32010. * @result An RGBA color represented as Vector4.
  32011. */
  32012. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  32013. var h = ColorCurves.clamp(hue, 0, 360);
  32014. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  32015. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  32016. if (s === 0) {
  32017. result.r = v;
  32018. result.g = v;
  32019. result.b = v;
  32020. }
  32021. else {
  32022. // sector 0 to 5
  32023. h /= 60;
  32024. var i = Math.floor(h);
  32025. // fractional part of h
  32026. var f = h - i;
  32027. var p = v * (1 - s);
  32028. var q = v * (1 - s * f);
  32029. var t = v * (1 - s * (1 - f));
  32030. switch (i) {
  32031. case 0:
  32032. result.r = v;
  32033. result.g = t;
  32034. result.b = p;
  32035. break;
  32036. case 1:
  32037. result.r = q;
  32038. result.g = v;
  32039. result.b = p;
  32040. break;
  32041. case 2:
  32042. result.r = p;
  32043. result.g = v;
  32044. result.b = t;
  32045. break;
  32046. case 3:
  32047. result.r = p;
  32048. result.g = q;
  32049. result.b = v;
  32050. break;
  32051. case 4:
  32052. result.r = t;
  32053. result.g = p;
  32054. result.b = v;
  32055. break;
  32056. default:// case 5:
  32057. result.r = v;
  32058. result.g = p;
  32059. result.b = q;
  32060. break;
  32061. }
  32062. }
  32063. result.a = 1;
  32064. };
  32065. /**
  32066. * Returns a value clamped between min and max
  32067. * @param value The value to clamp
  32068. * @param min The minimum of value
  32069. * @param max The maximum of value
  32070. * @returns The clamped value.
  32071. */
  32072. ColorCurves.clamp = function (value, min, max) {
  32073. return Math.min(Math.max(value, min), max);
  32074. };
  32075. /**
  32076. * Clones the current color curve instance.
  32077. * @return The cloned curves
  32078. */
  32079. ColorCurves.prototype.clone = function () {
  32080. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  32081. };
  32082. /**
  32083. * Serializes the current color curve instance to a json representation.
  32084. * @return a JSON representation
  32085. */
  32086. ColorCurves.prototype.serialize = function () {
  32087. return BABYLON.SerializationHelper.Serialize(this);
  32088. };
  32089. /**
  32090. * Parses the color curve from a json representation.
  32091. * @param source the JSON source to parse
  32092. * @return The parsed curves
  32093. */
  32094. ColorCurves.Parse = function (source) {
  32095. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  32096. };
  32097. __decorate([
  32098. BABYLON.serialize()
  32099. ], ColorCurves.prototype, "_globalHue", void 0);
  32100. __decorate([
  32101. BABYLON.serialize()
  32102. ], ColorCurves.prototype, "_globalDensity", void 0);
  32103. __decorate([
  32104. BABYLON.serialize()
  32105. ], ColorCurves.prototype, "_globalSaturation", void 0);
  32106. __decorate([
  32107. BABYLON.serialize()
  32108. ], ColorCurves.prototype, "_globalExposure", void 0);
  32109. __decorate([
  32110. BABYLON.serialize()
  32111. ], ColorCurves.prototype, "_highlightsHue", void 0);
  32112. __decorate([
  32113. BABYLON.serialize()
  32114. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  32115. __decorate([
  32116. BABYLON.serialize()
  32117. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  32118. __decorate([
  32119. BABYLON.serialize()
  32120. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  32121. __decorate([
  32122. BABYLON.serialize()
  32123. ], ColorCurves.prototype, "_midtonesHue", void 0);
  32124. __decorate([
  32125. BABYLON.serialize()
  32126. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  32127. __decorate([
  32128. BABYLON.serialize()
  32129. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  32130. __decorate([
  32131. BABYLON.serialize()
  32132. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  32133. return ColorCurves;
  32134. }());
  32135. BABYLON.ColorCurves = ColorCurves;
  32136. })(BABYLON || (BABYLON = {}));
  32137. //# sourceMappingURL=babylon.colorCurves.js.map
  32138. var BABYLON;
  32139. (function (BABYLON) {
  32140. var StandardMaterialDefines = (function (_super) {
  32141. __extends(StandardMaterialDefines, _super);
  32142. function StandardMaterialDefines() {
  32143. var _this = _super.call(this) || this;
  32144. _this.MAINUV1 = false;
  32145. _this.MAINUV2 = false;
  32146. _this.DIFFUSE = false;
  32147. _this.DIFFUSEDIRECTUV = 0;
  32148. _this.AMBIENT = false;
  32149. _this.AMBIENTDIRECTUV = 0;
  32150. _this.OPACITY = false;
  32151. _this.OPACITYDIRECTUV = 0;
  32152. _this.OPACITYRGB = false;
  32153. _this.REFLECTION = false;
  32154. _this.EMISSIVE = false;
  32155. _this.EMISSIVEDIRECTUV = 0;
  32156. _this.SPECULAR = false;
  32157. _this.SPECULARDIRECTUV = 0;
  32158. _this.BUMP = false;
  32159. _this.BUMPDIRECTUV = 0;
  32160. _this.PARALLAX = false;
  32161. _this.PARALLAXOCCLUSION = false;
  32162. _this.SPECULAROVERALPHA = false;
  32163. _this.CLIPPLANE = false;
  32164. _this.ALPHATEST = false;
  32165. _this.DEPTHPREPASS = false;
  32166. _this.ALPHAFROMDIFFUSE = false;
  32167. _this.POINTSIZE = false;
  32168. _this.FOG = false;
  32169. _this.SPECULARTERM = false;
  32170. _this.DIFFUSEFRESNEL = false;
  32171. _this.OPACITYFRESNEL = false;
  32172. _this.REFLECTIONFRESNEL = false;
  32173. _this.REFRACTIONFRESNEL = false;
  32174. _this.EMISSIVEFRESNEL = false;
  32175. _this.FRESNEL = false;
  32176. _this.NORMAL = false;
  32177. _this.UV1 = false;
  32178. _this.UV2 = false;
  32179. _this.VERTEXCOLOR = false;
  32180. _this.VERTEXALPHA = false;
  32181. _this.NUM_BONE_INFLUENCERS = 0;
  32182. _this.BonesPerMesh = 0;
  32183. _this.INSTANCES = false;
  32184. _this.GLOSSINESS = false;
  32185. _this.ROUGHNESS = false;
  32186. _this.EMISSIVEASILLUMINATION = false;
  32187. _this.LINKEMISSIVEWITHDIFFUSE = false;
  32188. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  32189. _this.LIGHTMAP = false;
  32190. _this.LIGHTMAPDIRECTUV = 0;
  32191. _this.USELIGHTMAPASSHADOWMAP = false;
  32192. _this.REFLECTIONMAP_3D = false;
  32193. _this.REFLECTIONMAP_SPHERICAL = false;
  32194. _this.REFLECTIONMAP_PLANAR = false;
  32195. _this.REFLECTIONMAP_CUBIC = false;
  32196. _this.REFLECTIONMAP_PROJECTION = false;
  32197. _this.REFLECTIONMAP_SKYBOX = false;
  32198. _this.REFLECTIONMAP_EXPLICIT = false;
  32199. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  32200. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  32201. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  32202. _this.INVERTCUBICMAP = false;
  32203. _this.LOGARITHMICDEPTH = false;
  32204. _this.REFRACTION = false;
  32205. _this.REFRACTIONMAP_3D = false;
  32206. _this.REFLECTIONOVERALPHA = false;
  32207. _this.TWOSIDEDLIGHTING = false;
  32208. _this.SHADOWFLOAT = false;
  32209. _this.MORPHTARGETS = false;
  32210. _this.MORPHTARGETS_NORMAL = false;
  32211. _this.MORPHTARGETS_TANGENT = false;
  32212. _this.NUM_MORPH_INFLUENCERS = 0;
  32213. _this.IMAGEPROCESSING = false;
  32214. _this.VIGNETTE = false;
  32215. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  32216. _this.VIGNETTEBLENDMODEOPAQUE = false;
  32217. _this.TONEMAPPING = false;
  32218. _this.CONTRAST = false;
  32219. _this.COLORCURVES = false;
  32220. _this.COLORGRADING = false;
  32221. _this.SAMPLER3DGREENDEPTH = false;
  32222. _this.SAMPLER3DBGRMAP = false;
  32223. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  32224. _this.EXPOSURE = false;
  32225. _this.rebuild();
  32226. return _this;
  32227. }
  32228. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  32229. var modes = [
  32230. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  32231. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  32232. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  32233. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  32234. ];
  32235. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  32236. var mode = modes_1[_i];
  32237. this[mode] = (mode === modeToEnable);
  32238. }
  32239. };
  32240. return StandardMaterialDefines;
  32241. }(BABYLON.MaterialDefines));
  32242. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  32243. var StandardMaterial = (function (_super) {
  32244. __extends(StandardMaterial, _super);
  32245. function StandardMaterial(name, scene) {
  32246. var _this = _super.call(this, name, scene) || this;
  32247. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  32248. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  32249. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  32250. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  32251. _this.specularPower = 64;
  32252. _this._useAlphaFromDiffuseTexture = false;
  32253. _this._useEmissiveAsIllumination = false;
  32254. _this._linkEmissiveWithDiffuse = false;
  32255. _this._useSpecularOverAlpha = false;
  32256. _this._useReflectionOverAlpha = false;
  32257. _this._disableLighting = false;
  32258. _this._useParallax = false;
  32259. _this._useParallaxOcclusion = false;
  32260. _this.parallaxScaleBias = 0.05;
  32261. _this._roughness = 0;
  32262. _this.indexOfRefraction = 0.98;
  32263. _this.invertRefractionY = true;
  32264. _this._useLightmapAsShadowmap = false;
  32265. _this._useReflectionFresnelFromSpecular = false;
  32266. _this._useGlossinessFromSpecularMapAlpha = false;
  32267. _this._maxSimultaneousLights = 4;
  32268. /**
  32269. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  32270. */
  32271. _this._invertNormalMapX = false;
  32272. /**
  32273. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  32274. */
  32275. _this._invertNormalMapY = false;
  32276. /**
  32277. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  32278. */
  32279. _this._twoSidedLighting = false;
  32280. _this._renderTargets = new BABYLON.SmartArray(16);
  32281. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  32282. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  32283. // Setup the default processing configuration to the scene.
  32284. _this._attachImageProcessingConfiguration(null);
  32285. _this.getRenderTargetTextures = function () {
  32286. _this._renderTargets.reset();
  32287. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  32288. _this._renderTargets.push(_this._reflectionTexture);
  32289. }
  32290. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  32291. _this._renderTargets.push(_this._refractionTexture);
  32292. }
  32293. return _this._renderTargets;
  32294. };
  32295. return _this;
  32296. }
  32297. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  32298. /**
  32299. * Gets the image processing configuration used either in this material.
  32300. */
  32301. get: function () {
  32302. return this._imageProcessingConfiguration;
  32303. },
  32304. /**
  32305. * Sets the Default image processing configuration used either in the this material.
  32306. *
  32307. * If sets to null, the scene one is in use.
  32308. */
  32309. set: function (value) {
  32310. this._attachImageProcessingConfiguration(value);
  32311. // Ensure the effect will be rebuilt.
  32312. this._markAllSubMeshesAsTexturesDirty();
  32313. },
  32314. enumerable: true,
  32315. configurable: true
  32316. });
  32317. /**
  32318. * Attaches a new image processing configuration to the Standard Material.
  32319. * @param configuration
  32320. */
  32321. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  32322. var _this = this;
  32323. if (configuration === this._imageProcessingConfiguration) {
  32324. return;
  32325. }
  32326. // Detaches observer.
  32327. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  32328. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  32329. }
  32330. // Pick the scene configuration if needed.
  32331. if (!configuration) {
  32332. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  32333. }
  32334. else {
  32335. this._imageProcessingConfiguration = configuration;
  32336. }
  32337. // Attaches observer.
  32338. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  32339. _this._markAllSubMeshesAsImageProcessingDirty();
  32340. });
  32341. };
  32342. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  32343. /**
  32344. * Gets wether the color curves effect is enabled.
  32345. */
  32346. get: function () {
  32347. return this.imageProcessingConfiguration.colorCurvesEnabled;
  32348. },
  32349. /**
  32350. * Sets wether the color curves effect is enabled.
  32351. */
  32352. set: function (value) {
  32353. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  32354. },
  32355. enumerable: true,
  32356. configurable: true
  32357. });
  32358. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  32359. /**
  32360. * Gets wether the color grading effect is enabled.
  32361. */
  32362. get: function () {
  32363. return this.imageProcessingConfiguration.colorGradingEnabled;
  32364. },
  32365. /**
  32366. * Gets wether the color grading effect is enabled.
  32367. */
  32368. set: function (value) {
  32369. this.imageProcessingConfiguration.colorGradingEnabled = value;
  32370. },
  32371. enumerable: true,
  32372. configurable: true
  32373. });
  32374. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  32375. /**
  32376. * Gets wether tonemapping is enabled or not.
  32377. */
  32378. get: function () {
  32379. return this._imageProcessingConfiguration.toneMappingEnabled;
  32380. },
  32381. /**
  32382. * Sets wether tonemapping is enabled or not
  32383. */
  32384. set: function (value) {
  32385. this._imageProcessingConfiguration.toneMappingEnabled = value;
  32386. },
  32387. enumerable: true,
  32388. configurable: true
  32389. });
  32390. ;
  32391. ;
  32392. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  32393. /**
  32394. * The camera exposure used on this material.
  32395. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  32396. * This corresponds to a photographic exposure.
  32397. */
  32398. get: function () {
  32399. return this._imageProcessingConfiguration.exposure;
  32400. },
  32401. /**
  32402. * The camera exposure used on this material.
  32403. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  32404. * This corresponds to a photographic exposure.
  32405. */
  32406. set: function (value) {
  32407. this._imageProcessingConfiguration.exposure = value;
  32408. },
  32409. enumerable: true,
  32410. configurable: true
  32411. });
  32412. ;
  32413. ;
  32414. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  32415. /**
  32416. * Gets The camera contrast used on this material.
  32417. */
  32418. get: function () {
  32419. return this._imageProcessingConfiguration.contrast;
  32420. },
  32421. /**
  32422. * Sets The camera contrast used on this material.
  32423. */
  32424. set: function (value) {
  32425. this._imageProcessingConfiguration.contrast = value;
  32426. },
  32427. enumerable: true,
  32428. configurable: true
  32429. });
  32430. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  32431. /**
  32432. * Gets the Color Grading 2D Lookup Texture.
  32433. */
  32434. get: function () {
  32435. return this._imageProcessingConfiguration.colorGradingTexture;
  32436. },
  32437. /**
  32438. * Sets the Color Grading 2D Lookup Texture.
  32439. */
  32440. set: function (value) {
  32441. this._imageProcessingConfiguration.colorGradingTexture = value;
  32442. },
  32443. enumerable: true,
  32444. configurable: true
  32445. });
  32446. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  32447. /**
  32448. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32449. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32450. * 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;
  32451. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32452. */
  32453. get: function () {
  32454. return this._imageProcessingConfiguration.colorCurves;
  32455. },
  32456. /**
  32457. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32458. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32459. * 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;
  32460. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32461. */
  32462. set: function (value) {
  32463. this._imageProcessingConfiguration.colorCurves = value;
  32464. },
  32465. enumerable: true,
  32466. configurable: true
  32467. });
  32468. StandardMaterial.prototype.getClassName = function () {
  32469. return "StandardMaterial";
  32470. };
  32471. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  32472. get: function () {
  32473. return this._useLogarithmicDepth;
  32474. },
  32475. set: function (value) {
  32476. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  32477. this._markAllSubMeshesAsMiscDirty();
  32478. },
  32479. enumerable: true,
  32480. configurable: true
  32481. });
  32482. StandardMaterial.prototype.needAlphaBlending = function () {
  32483. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  32484. };
  32485. StandardMaterial.prototype.needAlphaTesting = function () {
  32486. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  32487. };
  32488. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  32489. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  32490. };
  32491. StandardMaterial.prototype.getAlphaTestTexture = function () {
  32492. return this._diffuseTexture;
  32493. };
  32494. /**
  32495. * Child classes can use it to update shaders
  32496. */
  32497. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  32498. if (this.isFrozen) {
  32499. if (this._wasPreviouslyReady && subMesh.effect) {
  32500. return true;
  32501. }
  32502. }
  32503. if (!subMesh._materialDefines) {
  32504. subMesh._materialDefines = new StandardMaterialDefines();
  32505. }
  32506. var scene = this.getScene();
  32507. var defines = subMesh._materialDefines;
  32508. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  32509. if (defines._renderId === scene.getRenderId()) {
  32510. return true;
  32511. }
  32512. }
  32513. var engine = scene.getEngine();
  32514. // Lights
  32515. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  32516. // Textures
  32517. if (defines._areTexturesDirty) {
  32518. defines._needUVs = false;
  32519. defines.MAINUV1 = false;
  32520. defines.MAINUV2 = false;
  32521. if (scene.texturesEnabled) {
  32522. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  32523. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  32524. return false;
  32525. }
  32526. else {
  32527. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  32528. }
  32529. }
  32530. else {
  32531. defines.DIFFUSE = false;
  32532. }
  32533. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  32534. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  32535. return false;
  32536. }
  32537. else {
  32538. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  32539. }
  32540. }
  32541. else {
  32542. defines.AMBIENT = false;
  32543. }
  32544. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  32545. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  32546. return false;
  32547. }
  32548. else {
  32549. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  32550. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  32551. }
  32552. }
  32553. else {
  32554. defines.OPACITY = false;
  32555. }
  32556. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  32557. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  32558. return false;
  32559. }
  32560. else {
  32561. defines._needNormals = true;
  32562. defines.REFLECTION = true;
  32563. defines.ROUGHNESS = (this._roughness > 0);
  32564. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  32565. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  32566. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  32567. switch (this._reflectionTexture.coordinatesMode) {
  32568. case BABYLON.Texture.CUBIC_MODE:
  32569. case BABYLON.Texture.INVCUBIC_MODE:
  32570. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  32571. break;
  32572. case BABYLON.Texture.EXPLICIT_MODE:
  32573. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  32574. break;
  32575. case BABYLON.Texture.PLANAR_MODE:
  32576. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  32577. break;
  32578. case BABYLON.Texture.PROJECTION_MODE:
  32579. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  32580. break;
  32581. case BABYLON.Texture.SKYBOX_MODE:
  32582. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  32583. break;
  32584. case BABYLON.Texture.SPHERICAL_MODE:
  32585. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  32586. break;
  32587. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  32588. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  32589. break;
  32590. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  32591. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  32592. break;
  32593. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  32594. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  32595. break;
  32596. }
  32597. }
  32598. }
  32599. else {
  32600. defines.REFLECTION = false;
  32601. }
  32602. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  32603. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  32604. return false;
  32605. }
  32606. else {
  32607. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  32608. }
  32609. }
  32610. else {
  32611. defines.EMISSIVE = false;
  32612. }
  32613. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  32614. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  32615. return false;
  32616. }
  32617. else {
  32618. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  32619. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  32620. }
  32621. }
  32622. else {
  32623. defines.LIGHTMAP = false;
  32624. }
  32625. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  32626. if (!this._specularTexture.isReadyOrNotBlocking()) {
  32627. return false;
  32628. }
  32629. else {
  32630. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  32631. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  32632. }
  32633. }
  32634. else {
  32635. defines.SPECULAR = false;
  32636. }
  32637. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  32638. // Bump texure can not be not blocking.
  32639. if (!this._bumpTexture.isReady()) {
  32640. return false;
  32641. }
  32642. else {
  32643. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  32644. defines.PARALLAX = this._useParallax;
  32645. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  32646. }
  32647. }
  32648. else {
  32649. defines.BUMP = false;
  32650. }
  32651. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  32652. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  32653. return false;
  32654. }
  32655. else {
  32656. defines._needUVs = true;
  32657. defines.REFRACTION = true;
  32658. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  32659. }
  32660. }
  32661. else {
  32662. defines.REFRACTION = false;
  32663. }
  32664. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  32665. }
  32666. else {
  32667. defines.DIFFUSE = false;
  32668. defines.AMBIENT = false;
  32669. defines.OPACITY = false;
  32670. defines.REFLECTION = false;
  32671. defines.EMISSIVE = false;
  32672. defines.LIGHTMAP = false;
  32673. defines.BUMP = false;
  32674. defines.REFRACTION = false;
  32675. }
  32676. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  32677. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  32678. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  32679. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  32680. }
  32681. if (defines._areImageProcessingDirty) {
  32682. if (!this._imageProcessingConfiguration.isReady()) {
  32683. return false;
  32684. }
  32685. this._imageProcessingConfiguration.prepareDefines(defines);
  32686. }
  32687. if (defines._areFresnelDirty) {
  32688. if (StandardMaterial.FresnelEnabled) {
  32689. // Fresnel
  32690. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  32691. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  32692. this._reflectionFresnelParameters) {
  32693. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  32694. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  32695. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  32696. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  32697. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  32698. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  32699. defines._needNormals = true;
  32700. defines.FRESNEL = true;
  32701. }
  32702. }
  32703. else {
  32704. defines.FRESNEL = false;
  32705. }
  32706. }
  32707. // Misc.
  32708. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  32709. // Attribs
  32710. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  32711. // Values that need to be evaluated on every frame
  32712. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  32713. // Get correct effect
  32714. if (defines.isDirty) {
  32715. defines.markAsProcessed();
  32716. scene.resetCachedMaterial();
  32717. // Fallbacks
  32718. var fallbacks = new BABYLON.EffectFallbacks();
  32719. if (defines.REFLECTION) {
  32720. fallbacks.addFallback(0, "REFLECTION");
  32721. }
  32722. if (defines.SPECULAR) {
  32723. fallbacks.addFallback(0, "SPECULAR");
  32724. }
  32725. if (defines.BUMP) {
  32726. fallbacks.addFallback(0, "BUMP");
  32727. }
  32728. if (defines.PARALLAX) {
  32729. fallbacks.addFallback(1, "PARALLAX");
  32730. }
  32731. if (defines.PARALLAXOCCLUSION) {
  32732. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  32733. }
  32734. if (defines.SPECULAROVERALPHA) {
  32735. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  32736. }
  32737. if (defines.FOG) {
  32738. fallbacks.addFallback(1, "FOG");
  32739. }
  32740. if (defines.POINTSIZE) {
  32741. fallbacks.addFallback(0, "POINTSIZE");
  32742. }
  32743. if (defines.LOGARITHMICDEPTH) {
  32744. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  32745. }
  32746. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  32747. if (defines.SPECULARTERM) {
  32748. fallbacks.addFallback(0, "SPECULARTERM");
  32749. }
  32750. if (defines.DIFFUSEFRESNEL) {
  32751. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  32752. }
  32753. if (defines.OPACITYFRESNEL) {
  32754. fallbacks.addFallback(2, "OPACITYFRESNEL");
  32755. }
  32756. if (defines.REFLECTIONFRESNEL) {
  32757. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  32758. }
  32759. if (defines.EMISSIVEFRESNEL) {
  32760. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  32761. }
  32762. if (defines.FRESNEL) {
  32763. fallbacks.addFallback(4, "FRESNEL");
  32764. }
  32765. //Attributes
  32766. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32767. if (defines.NORMAL) {
  32768. attribs.push(BABYLON.VertexBuffer.NormalKind);
  32769. }
  32770. if (defines.UV1) {
  32771. attribs.push(BABYLON.VertexBuffer.UVKind);
  32772. }
  32773. if (defines.UV2) {
  32774. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32775. }
  32776. if (defines.VERTEXCOLOR) {
  32777. attribs.push(BABYLON.VertexBuffer.ColorKind);
  32778. }
  32779. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  32780. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  32781. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  32782. var shaderName = "default";
  32783. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  32784. "vFogInfos", "vFogColor", "pointSize",
  32785. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  32786. "mBones",
  32787. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  32788. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  32789. "logarithmicDepthConstant", "vTangentSpaceParams"
  32790. ];
  32791. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  32792. var uniformBuffers = ["Material", "Scene"];
  32793. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  32794. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  32795. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  32796. uniformsNames: uniforms,
  32797. uniformBuffersNames: uniformBuffers,
  32798. samplers: samplers,
  32799. defines: defines,
  32800. maxSimultaneousLights: this._maxSimultaneousLights
  32801. });
  32802. if (this.customShaderNameResolve) {
  32803. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  32804. }
  32805. var join = defines.toString();
  32806. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  32807. attributes: attribs,
  32808. uniformsNames: uniforms,
  32809. uniformBuffersNames: uniformBuffers,
  32810. samplers: samplers,
  32811. defines: join,
  32812. fallbacks: fallbacks,
  32813. onCompiled: this.onCompiled,
  32814. onError: this.onError,
  32815. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  32816. }, engine), defines);
  32817. this.buildUniformLayout();
  32818. }
  32819. if (!subMesh.effect.isReady()) {
  32820. return false;
  32821. }
  32822. defines._renderId = scene.getRenderId();
  32823. this._wasPreviouslyReady = true;
  32824. return true;
  32825. };
  32826. StandardMaterial.prototype.buildUniformLayout = function () {
  32827. // Order is important !
  32828. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  32829. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  32830. this._uniformBuffer.addUniform("opacityParts", 4);
  32831. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  32832. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  32833. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  32834. this._uniformBuffer.addUniform("refractionRightColor", 4);
  32835. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  32836. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  32837. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  32838. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  32839. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  32840. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  32841. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  32842. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  32843. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  32844. this._uniformBuffer.addUniform("vBumpInfos", 3);
  32845. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  32846. this._uniformBuffer.addUniform("ambientMatrix", 16);
  32847. this._uniformBuffer.addUniform("opacityMatrix", 16);
  32848. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  32849. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  32850. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  32851. this._uniformBuffer.addUniform("specularMatrix", 16);
  32852. this._uniformBuffer.addUniform("bumpMatrix", 16);
  32853. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  32854. this._uniformBuffer.addUniform("refractionMatrix", 16);
  32855. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  32856. this._uniformBuffer.addUniform("vSpecularColor", 4);
  32857. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  32858. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  32859. this._uniformBuffer.addUniform("pointSize", 1);
  32860. this._uniformBuffer.create();
  32861. };
  32862. StandardMaterial.prototype.unbind = function () {
  32863. if (this._activeEffect) {
  32864. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  32865. this._activeEffect.setTexture("reflection2DSampler", null);
  32866. }
  32867. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  32868. this._activeEffect.setTexture("refraction2DSampler", null);
  32869. }
  32870. }
  32871. _super.prototype.unbind.call(this);
  32872. };
  32873. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  32874. var scene = this.getScene();
  32875. var defines = subMesh._materialDefines;
  32876. if (!defines) {
  32877. return;
  32878. }
  32879. var effect = subMesh.effect;
  32880. this._activeEffect = effect;
  32881. // Matrices
  32882. this.bindOnlyWorldMatrix(world);
  32883. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  32884. // Bones
  32885. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  32886. if (mustRebind) {
  32887. this._uniformBuffer.bindToEffect(effect, "Material");
  32888. this.bindViewProjection(effect);
  32889. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  32890. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  32891. // Fresnel
  32892. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  32893. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  32894. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  32895. }
  32896. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  32897. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  32898. }
  32899. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  32900. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  32901. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  32902. }
  32903. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  32904. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  32905. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  32906. }
  32907. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  32908. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  32909. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  32910. }
  32911. }
  32912. // Textures
  32913. if (scene.texturesEnabled) {
  32914. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  32915. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  32916. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  32917. }
  32918. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  32919. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  32920. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  32921. }
  32922. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  32923. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  32924. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  32925. }
  32926. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  32927. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  32928. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  32929. }
  32930. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  32931. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  32932. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  32933. }
  32934. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  32935. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  32936. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  32937. }
  32938. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  32939. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  32940. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  32941. }
  32942. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  32943. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  32944. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  32945. if (scene._mirroredCameraPosition) {
  32946. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  32947. }
  32948. else {
  32949. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  32950. }
  32951. }
  32952. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  32953. var depth = 1.0;
  32954. if (!this._refractionTexture.isCube) {
  32955. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  32956. if (this._refractionTexture.depth) {
  32957. depth = this._refractionTexture.depth;
  32958. }
  32959. }
  32960. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  32961. }
  32962. }
  32963. // Point size
  32964. if (this.pointsCloud) {
  32965. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  32966. }
  32967. if (defines.SPECULARTERM) {
  32968. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  32969. }
  32970. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  32971. // Diffuse
  32972. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  32973. }
  32974. // Textures
  32975. if (scene.texturesEnabled) {
  32976. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  32977. effect.setTexture("diffuseSampler", this._diffuseTexture);
  32978. }
  32979. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  32980. effect.setTexture("ambientSampler", this._ambientTexture);
  32981. }
  32982. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  32983. effect.setTexture("opacitySampler", this._opacityTexture);
  32984. }
  32985. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  32986. if (this._reflectionTexture.isCube) {
  32987. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  32988. }
  32989. else {
  32990. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  32991. }
  32992. }
  32993. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  32994. effect.setTexture("emissiveSampler", this._emissiveTexture);
  32995. }
  32996. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  32997. effect.setTexture("lightmapSampler", this._lightmapTexture);
  32998. }
  32999. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33000. effect.setTexture("specularSampler", this._specularTexture);
  33001. }
  33002. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  33003. effect.setTexture("bumpSampler", this._bumpTexture);
  33004. }
  33005. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  33006. var depth = 1.0;
  33007. if (this._refractionTexture.isCube) {
  33008. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  33009. }
  33010. else {
  33011. effect.setTexture("refraction2DSampler", this._refractionTexture);
  33012. }
  33013. }
  33014. }
  33015. // Clip plane
  33016. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  33017. // Colors
  33018. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  33019. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  33020. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  33021. }
  33022. if (mustRebind || !this.isFrozen) {
  33023. // Lights
  33024. if (scene.lightsEnabled && !this._disableLighting) {
  33025. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  33026. }
  33027. // View
  33028. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  33029. this.bindView(effect);
  33030. }
  33031. // Fog
  33032. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  33033. // Morph targets
  33034. if (defines.NUM_MORPH_INFLUENCERS) {
  33035. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  33036. }
  33037. // Log. depth
  33038. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  33039. // image processing
  33040. this._imageProcessingConfiguration.bind(this._activeEffect);
  33041. }
  33042. this._uniformBuffer.update();
  33043. this._afterBind(mesh, this._activeEffect);
  33044. };
  33045. StandardMaterial.prototype.getAnimatables = function () {
  33046. var results = [];
  33047. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  33048. results.push(this._diffuseTexture);
  33049. }
  33050. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  33051. results.push(this._ambientTexture);
  33052. }
  33053. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  33054. results.push(this._opacityTexture);
  33055. }
  33056. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  33057. results.push(this._reflectionTexture);
  33058. }
  33059. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  33060. results.push(this._emissiveTexture);
  33061. }
  33062. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  33063. results.push(this._specularTexture);
  33064. }
  33065. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  33066. results.push(this._bumpTexture);
  33067. }
  33068. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  33069. results.push(this._lightmapTexture);
  33070. }
  33071. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  33072. results.push(this._refractionTexture);
  33073. }
  33074. return results;
  33075. };
  33076. StandardMaterial.prototype.getActiveTextures = function () {
  33077. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33078. if (this._diffuseTexture) {
  33079. activeTextures.push(this._diffuseTexture);
  33080. }
  33081. if (this._ambientTexture) {
  33082. activeTextures.push(this._ambientTexture);
  33083. }
  33084. if (this._opacityTexture) {
  33085. activeTextures.push(this._opacityTexture);
  33086. }
  33087. if (this._reflectionTexture) {
  33088. activeTextures.push(this._reflectionTexture);
  33089. }
  33090. if (this._emissiveTexture) {
  33091. activeTextures.push(this._emissiveTexture);
  33092. }
  33093. if (this._specularTexture) {
  33094. activeTextures.push(this._specularTexture);
  33095. }
  33096. if (this._bumpTexture) {
  33097. activeTextures.push(this._bumpTexture);
  33098. }
  33099. if (this._lightmapTexture) {
  33100. activeTextures.push(this._lightmapTexture);
  33101. }
  33102. if (this._refractionTexture) {
  33103. activeTextures.push(this._refractionTexture);
  33104. }
  33105. return activeTextures;
  33106. };
  33107. StandardMaterial.prototype.hasTexture = function (texture) {
  33108. if (_super.prototype.hasTexture.call(this, texture)) {
  33109. return true;
  33110. }
  33111. if (this._diffuseTexture === texture) {
  33112. return true;
  33113. }
  33114. if (this._ambientTexture === texture) {
  33115. return true;
  33116. }
  33117. if (this._opacityTexture === texture) {
  33118. return true;
  33119. }
  33120. if (this._reflectionTexture === texture) {
  33121. return true;
  33122. }
  33123. if (this._emissiveTexture === texture) {
  33124. return true;
  33125. }
  33126. if (this._specularTexture === texture) {
  33127. return true;
  33128. }
  33129. if (this._bumpTexture === texture) {
  33130. return true;
  33131. }
  33132. if (this._lightmapTexture === texture) {
  33133. return true;
  33134. }
  33135. if (this._refractionTexture === texture) {
  33136. return true;
  33137. }
  33138. return false;
  33139. };
  33140. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  33141. if (forceDisposeTextures) {
  33142. if (this._diffuseTexture) {
  33143. this._diffuseTexture.dispose();
  33144. }
  33145. if (this._ambientTexture) {
  33146. this._ambientTexture.dispose();
  33147. }
  33148. if (this._opacityTexture) {
  33149. this._opacityTexture.dispose();
  33150. }
  33151. if (this._reflectionTexture) {
  33152. this._reflectionTexture.dispose();
  33153. }
  33154. if (this._emissiveTexture) {
  33155. this._emissiveTexture.dispose();
  33156. }
  33157. if (this._specularTexture) {
  33158. this._specularTexture.dispose();
  33159. }
  33160. if (this._bumpTexture) {
  33161. this._bumpTexture.dispose();
  33162. }
  33163. if (this._lightmapTexture) {
  33164. this._lightmapTexture.dispose();
  33165. }
  33166. if (this._refractionTexture) {
  33167. this._refractionTexture.dispose();
  33168. }
  33169. }
  33170. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  33171. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  33172. }
  33173. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  33174. };
  33175. StandardMaterial.prototype.clone = function (name) {
  33176. var _this = this;
  33177. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  33178. result.name = name;
  33179. result.id = name;
  33180. return result;
  33181. };
  33182. StandardMaterial.prototype.serialize = function () {
  33183. return BABYLON.SerializationHelper.Serialize(this);
  33184. };
  33185. // Statics
  33186. StandardMaterial.Parse = function (source, scene, rootUrl) {
  33187. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  33188. };
  33189. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  33190. get: function () {
  33191. return StandardMaterial._DiffuseTextureEnabled;
  33192. },
  33193. set: function (value) {
  33194. if (StandardMaterial._DiffuseTextureEnabled === value) {
  33195. return;
  33196. }
  33197. StandardMaterial._DiffuseTextureEnabled = value;
  33198. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33199. },
  33200. enumerable: true,
  33201. configurable: true
  33202. });
  33203. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  33204. get: function () {
  33205. return StandardMaterial._AmbientTextureEnabled;
  33206. },
  33207. set: function (value) {
  33208. if (StandardMaterial._AmbientTextureEnabled === value) {
  33209. return;
  33210. }
  33211. StandardMaterial._AmbientTextureEnabled = value;
  33212. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33213. },
  33214. enumerable: true,
  33215. configurable: true
  33216. });
  33217. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  33218. get: function () {
  33219. return StandardMaterial._OpacityTextureEnabled;
  33220. },
  33221. set: function (value) {
  33222. if (StandardMaterial._OpacityTextureEnabled === value) {
  33223. return;
  33224. }
  33225. StandardMaterial._OpacityTextureEnabled = value;
  33226. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33227. },
  33228. enumerable: true,
  33229. configurable: true
  33230. });
  33231. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  33232. get: function () {
  33233. return StandardMaterial._ReflectionTextureEnabled;
  33234. },
  33235. set: function (value) {
  33236. if (StandardMaterial._ReflectionTextureEnabled === value) {
  33237. return;
  33238. }
  33239. StandardMaterial._ReflectionTextureEnabled = value;
  33240. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33241. },
  33242. enumerable: true,
  33243. configurable: true
  33244. });
  33245. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  33246. get: function () {
  33247. return StandardMaterial._EmissiveTextureEnabled;
  33248. },
  33249. set: function (value) {
  33250. if (StandardMaterial._EmissiveTextureEnabled === value) {
  33251. return;
  33252. }
  33253. StandardMaterial._EmissiveTextureEnabled = value;
  33254. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33255. },
  33256. enumerable: true,
  33257. configurable: true
  33258. });
  33259. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  33260. get: function () {
  33261. return StandardMaterial._SpecularTextureEnabled;
  33262. },
  33263. set: function (value) {
  33264. if (StandardMaterial._SpecularTextureEnabled === value) {
  33265. return;
  33266. }
  33267. StandardMaterial._SpecularTextureEnabled = value;
  33268. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33269. },
  33270. enumerable: true,
  33271. configurable: true
  33272. });
  33273. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  33274. get: function () {
  33275. return StandardMaterial._BumpTextureEnabled;
  33276. },
  33277. set: function (value) {
  33278. if (StandardMaterial._BumpTextureEnabled === value) {
  33279. return;
  33280. }
  33281. StandardMaterial._BumpTextureEnabled = value;
  33282. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33283. },
  33284. enumerable: true,
  33285. configurable: true
  33286. });
  33287. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  33288. get: function () {
  33289. return StandardMaterial._LightmapTextureEnabled;
  33290. },
  33291. set: function (value) {
  33292. if (StandardMaterial._LightmapTextureEnabled === value) {
  33293. return;
  33294. }
  33295. StandardMaterial._LightmapTextureEnabled = value;
  33296. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33297. },
  33298. enumerable: true,
  33299. configurable: true
  33300. });
  33301. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  33302. get: function () {
  33303. return StandardMaterial._RefractionTextureEnabled;
  33304. },
  33305. set: function (value) {
  33306. if (StandardMaterial._RefractionTextureEnabled === value) {
  33307. return;
  33308. }
  33309. StandardMaterial._RefractionTextureEnabled = value;
  33310. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33311. },
  33312. enumerable: true,
  33313. configurable: true
  33314. });
  33315. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  33316. get: function () {
  33317. return StandardMaterial._ColorGradingTextureEnabled;
  33318. },
  33319. set: function (value) {
  33320. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  33321. return;
  33322. }
  33323. StandardMaterial._ColorGradingTextureEnabled = value;
  33324. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33325. },
  33326. enumerable: true,
  33327. configurable: true
  33328. });
  33329. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  33330. get: function () {
  33331. return StandardMaterial._FresnelEnabled;
  33332. },
  33333. set: function (value) {
  33334. if (StandardMaterial._FresnelEnabled === value) {
  33335. return;
  33336. }
  33337. StandardMaterial._FresnelEnabled = value;
  33338. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  33339. },
  33340. enumerable: true,
  33341. configurable: true
  33342. });
  33343. // Flags used to enable or disable a type of texture for all Standard Materials
  33344. StandardMaterial._DiffuseTextureEnabled = true;
  33345. StandardMaterial._AmbientTextureEnabled = true;
  33346. StandardMaterial._OpacityTextureEnabled = true;
  33347. StandardMaterial._ReflectionTextureEnabled = true;
  33348. StandardMaterial._EmissiveTextureEnabled = true;
  33349. StandardMaterial._SpecularTextureEnabled = true;
  33350. StandardMaterial._BumpTextureEnabled = true;
  33351. StandardMaterial._LightmapTextureEnabled = true;
  33352. StandardMaterial._RefractionTextureEnabled = true;
  33353. StandardMaterial._ColorGradingTextureEnabled = true;
  33354. StandardMaterial._FresnelEnabled = true;
  33355. __decorate([
  33356. BABYLON.serializeAsTexture("diffuseTexture")
  33357. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  33358. __decorate([
  33359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33360. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  33361. __decorate([
  33362. BABYLON.serializeAsTexture("ambientTexture")
  33363. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  33364. __decorate([
  33365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33366. ], StandardMaterial.prototype, "ambientTexture", void 0);
  33367. __decorate([
  33368. BABYLON.serializeAsTexture("opacityTexture")
  33369. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  33370. __decorate([
  33371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33372. ], StandardMaterial.prototype, "opacityTexture", void 0);
  33373. __decorate([
  33374. BABYLON.serializeAsTexture("reflectionTexture")
  33375. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  33376. __decorate([
  33377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33378. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  33379. __decorate([
  33380. BABYLON.serializeAsTexture("emissiveTexture")
  33381. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  33382. __decorate([
  33383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33384. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  33385. __decorate([
  33386. BABYLON.serializeAsTexture("specularTexture")
  33387. ], StandardMaterial.prototype, "_specularTexture", void 0);
  33388. __decorate([
  33389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33390. ], StandardMaterial.prototype, "specularTexture", void 0);
  33391. __decorate([
  33392. BABYLON.serializeAsTexture("bumpTexture")
  33393. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  33394. __decorate([
  33395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33396. ], StandardMaterial.prototype, "bumpTexture", void 0);
  33397. __decorate([
  33398. BABYLON.serializeAsTexture("lightmapTexture")
  33399. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  33400. __decorate([
  33401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33402. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  33403. __decorate([
  33404. BABYLON.serializeAsTexture("refractionTexture")
  33405. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  33406. __decorate([
  33407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33408. ], StandardMaterial.prototype, "refractionTexture", void 0);
  33409. __decorate([
  33410. BABYLON.serializeAsColor3("ambient")
  33411. ], StandardMaterial.prototype, "ambientColor", void 0);
  33412. __decorate([
  33413. BABYLON.serializeAsColor3("diffuse")
  33414. ], StandardMaterial.prototype, "diffuseColor", void 0);
  33415. __decorate([
  33416. BABYLON.serializeAsColor3("specular")
  33417. ], StandardMaterial.prototype, "specularColor", void 0);
  33418. __decorate([
  33419. BABYLON.serializeAsColor3("emissive")
  33420. ], StandardMaterial.prototype, "emissiveColor", void 0);
  33421. __decorate([
  33422. BABYLON.serialize()
  33423. ], StandardMaterial.prototype, "specularPower", void 0);
  33424. __decorate([
  33425. BABYLON.serialize("useAlphaFromDiffuseTexture")
  33426. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  33427. __decorate([
  33428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33429. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  33430. __decorate([
  33431. BABYLON.serialize("useEmissiveAsIllumination")
  33432. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  33433. __decorate([
  33434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33435. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  33436. __decorate([
  33437. BABYLON.serialize("linkEmissiveWithDiffuse")
  33438. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  33439. __decorate([
  33440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33441. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  33442. __decorate([
  33443. BABYLON.serialize("useSpecularOverAlpha")
  33444. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  33445. __decorate([
  33446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33447. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  33448. __decorate([
  33449. BABYLON.serialize("useReflectionOverAlpha")
  33450. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  33451. __decorate([
  33452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33453. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  33454. __decorate([
  33455. BABYLON.serialize("disableLighting")
  33456. ], StandardMaterial.prototype, "_disableLighting", void 0);
  33457. __decorate([
  33458. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33459. ], StandardMaterial.prototype, "disableLighting", void 0);
  33460. __decorate([
  33461. BABYLON.serialize("useParallax")
  33462. ], StandardMaterial.prototype, "_useParallax", void 0);
  33463. __decorate([
  33464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33465. ], StandardMaterial.prototype, "useParallax", void 0);
  33466. __decorate([
  33467. BABYLON.serialize("useParallaxOcclusion")
  33468. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  33469. __decorate([
  33470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33471. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  33472. __decorate([
  33473. BABYLON.serialize()
  33474. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  33475. __decorate([
  33476. BABYLON.serialize("roughness")
  33477. ], StandardMaterial.prototype, "_roughness", void 0);
  33478. __decorate([
  33479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33480. ], StandardMaterial.prototype, "roughness", void 0);
  33481. __decorate([
  33482. BABYLON.serialize()
  33483. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  33484. __decorate([
  33485. BABYLON.serialize()
  33486. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  33487. __decorate([
  33488. BABYLON.serialize("useLightmapAsShadowmap")
  33489. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  33490. __decorate([
  33491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33492. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  33493. __decorate([
  33494. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  33495. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  33496. __decorate([
  33497. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  33498. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  33499. __decorate([
  33500. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  33501. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  33502. __decorate([
  33503. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  33504. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  33505. __decorate([
  33506. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  33507. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  33508. __decorate([
  33509. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  33510. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  33511. __decorate([
  33512. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  33513. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  33514. __decorate([
  33515. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  33516. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  33517. __decorate([
  33518. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  33519. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  33520. __decorate([
  33521. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  33522. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  33523. __decorate([
  33524. BABYLON.serialize("useReflectionFresnelFromSpecular")
  33525. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  33526. __decorate([
  33527. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  33528. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  33529. __decorate([
  33530. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  33531. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  33532. __decorate([
  33533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33534. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  33535. __decorate([
  33536. BABYLON.serialize("maxSimultaneousLights")
  33537. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  33538. __decorate([
  33539. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33540. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  33541. __decorate([
  33542. BABYLON.serialize("invertNormalMapX")
  33543. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  33544. __decorate([
  33545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33546. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  33547. __decorate([
  33548. BABYLON.serialize("invertNormalMapY")
  33549. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  33550. __decorate([
  33551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33552. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  33553. __decorate([
  33554. BABYLON.serialize("twoSidedLighting")
  33555. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  33556. __decorate([
  33557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33558. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  33559. __decorate([
  33560. BABYLON.serialize()
  33561. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  33562. return StandardMaterial;
  33563. }(BABYLON.PushMaterial));
  33564. BABYLON.StandardMaterial = StandardMaterial;
  33565. })(BABYLON || (BABYLON = {}));
  33566. //# sourceMappingURL=babylon.standardMaterial.js.map
  33567. var BABYLON;
  33568. (function (BABYLON) {
  33569. var PBRMaterialDefines = (function (_super) {
  33570. __extends(PBRMaterialDefines, _super);
  33571. function PBRMaterialDefines() {
  33572. var _this = _super.call(this) || this;
  33573. _this.PBR = true;
  33574. _this.MAINUV1 = false;
  33575. _this.MAINUV2 = false;
  33576. _this.UV1 = false;
  33577. _this.UV2 = false;
  33578. _this.ALBEDO = false;
  33579. _this.ALBEDODIRECTUV = 0;
  33580. _this.VERTEXCOLOR = false;
  33581. _this.AMBIENT = false;
  33582. _this.AMBIENTDIRECTUV = 0;
  33583. _this.AMBIENTINGRAYSCALE = false;
  33584. _this.OPACITY = false;
  33585. _this.VERTEXALPHA = false;
  33586. _this.OPACITYDIRECTUV = 0;
  33587. _this.OPACITYRGB = false;
  33588. _this.ALPHATEST = false;
  33589. _this.DEPTHPREPASS = false;
  33590. _this.ALPHABLEND = false;
  33591. _this.ALPHAFROMALBEDO = false;
  33592. _this.ALPHATESTVALUE = 0.5;
  33593. _this.SPECULAROVERALPHA = false;
  33594. _this.RADIANCEOVERALPHA = false;
  33595. _this.ALPHAFRESNEL = false;
  33596. _this.PREMULTIPLYALPHA = false;
  33597. _this.EMISSIVE = false;
  33598. _this.EMISSIVEDIRECTUV = 0;
  33599. _this.REFLECTIVITY = false;
  33600. _this.REFLECTIVITYDIRECTUV = 0;
  33601. _this.SPECULARTERM = false;
  33602. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  33603. _this.MICROSURFACEAUTOMATIC = false;
  33604. _this.LODBASEDMICROSFURACE = false;
  33605. _this.MICROSURFACEMAP = false;
  33606. _this.MICROSURFACEMAPDIRECTUV = 0;
  33607. _this.METALLICWORKFLOW = false;
  33608. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  33609. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  33610. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  33611. _this.AOSTOREINMETALMAPRED = false;
  33612. _this.ENVIRONMENTBRDF = false;
  33613. _this.NORMAL = false;
  33614. _this.TANGENT = false;
  33615. _this.BUMP = false;
  33616. _this.BUMPDIRECTUV = 0;
  33617. _this.PARALLAX = false;
  33618. _this.PARALLAXOCCLUSION = false;
  33619. _this.NORMALXYSCALE = true;
  33620. _this.LIGHTMAP = false;
  33621. _this.LIGHTMAPDIRECTUV = 0;
  33622. _this.USELIGHTMAPASSHADOWMAP = false;
  33623. _this.REFLECTION = false;
  33624. _this.REFLECTIONMAP_3D = false;
  33625. _this.REFLECTIONMAP_SPHERICAL = false;
  33626. _this.REFLECTIONMAP_PLANAR = false;
  33627. _this.REFLECTIONMAP_CUBIC = false;
  33628. _this.REFLECTIONMAP_PROJECTION = false;
  33629. _this.REFLECTIONMAP_SKYBOX = false;
  33630. _this.REFLECTIONMAP_EXPLICIT = false;
  33631. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  33632. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  33633. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  33634. _this.INVERTCUBICMAP = false;
  33635. _this.USESPHERICALFROMREFLECTIONMAP = false;
  33636. _this.USESPHERICALINFRAGMENT = false;
  33637. _this.REFLECTIONMAP_OPPOSITEZ = false;
  33638. _this.LODINREFLECTIONALPHA = false;
  33639. _this.GAMMAREFLECTION = false;
  33640. _this.REFRACTION = false;
  33641. _this.REFRACTIONMAP_3D = false;
  33642. _this.REFRACTIONMAP_OPPOSITEZ = false;
  33643. _this.LODINREFRACTIONALPHA = false;
  33644. _this.GAMMAREFRACTION = false;
  33645. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  33646. _this.INSTANCES = false;
  33647. _this.NUM_BONE_INFLUENCERS = 0;
  33648. _this.BonesPerMesh = 0;
  33649. _this.MORPHTARGETS = false;
  33650. _this.MORPHTARGETS_NORMAL = false;
  33651. _this.MORPHTARGETS_TANGENT = false;
  33652. _this.NUM_MORPH_INFLUENCERS = 0;
  33653. _this.IMAGEPROCESSING = false;
  33654. _this.VIGNETTE = false;
  33655. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  33656. _this.VIGNETTEBLENDMODEOPAQUE = false;
  33657. _this.TONEMAPPING = false;
  33658. _this.CONTRAST = false;
  33659. _this.COLORCURVES = false;
  33660. _this.COLORGRADING = false;
  33661. _this.SAMPLER3DGREENDEPTH = false;
  33662. _this.SAMPLER3DBGRMAP = false;
  33663. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  33664. _this.EXPOSURE = false;
  33665. _this.USEPHYSICALLIGHTFALLOFF = false;
  33666. _this.TWOSIDEDLIGHTING = false;
  33667. _this.SHADOWFLOAT = false;
  33668. _this.CLIPPLANE = false;
  33669. _this.POINTSIZE = false;
  33670. _this.FOG = false;
  33671. _this.LOGARITHMICDEPTH = false;
  33672. _this.FORCENORMALFORWARD = false;
  33673. _this.rebuild();
  33674. return _this;
  33675. }
  33676. PBRMaterialDefines.prototype.reset = function () {
  33677. _super.prototype.reset.call(this);
  33678. this.ALPHATESTVALUE = 0.5;
  33679. this.PBR = true;
  33680. };
  33681. return PBRMaterialDefines;
  33682. }(BABYLON.MaterialDefines));
  33683. /**
  33684. * The Physically based material base class of BJS.
  33685. *
  33686. * This offers the main features of a standard PBR material.
  33687. * For more information, please refer to the documentation :
  33688. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  33689. */
  33690. var PBRBaseMaterial = (function (_super) {
  33691. __extends(PBRBaseMaterial, _super);
  33692. /**
  33693. * Instantiates a new PBRMaterial instance.
  33694. *
  33695. * @param name The material name
  33696. * @param scene The scene the material will be use in.
  33697. */
  33698. function PBRBaseMaterial(name, scene) {
  33699. var _this = _super.call(this, name, scene) || this;
  33700. /**
  33701. * Intensity of the direct lights e.g. the four lights available in your scene.
  33702. * This impacts both the direct diffuse and specular highlights.
  33703. */
  33704. _this._directIntensity = 1.0;
  33705. /**
  33706. * Intensity of the emissive part of the material.
  33707. * This helps controlling the emissive effect without modifying the emissive color.
  33708. */
  33709. _this._emissiveIntensity = 1.0;
  33710. /**
  33711. * Intensity of the environment e.g. how much the environment will light the object
  33712. * either through harmonics for rough material or through the refelction for shiny ones.
  33713. */
  33714. _this._environmentIntensity = 1.0;
  33715. /**
  33716. * This is a special control allowing the reduction of the specular highlights coming from the
  33717. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  33718. */
  33719. _this._specularIntensity = 1.0;
  33720. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  33721. /**
  33722. * Debug Control allowing disabling the bump map on this material.
  33723. */
  33724. _this._disableBumpMap = false;
  33725. /**
  33726. * AKA Occlusion Texture Intensity in other nomenclature.
  33727. */
  33728. _this._ambientTextureStrength = 1.0;
  33729. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  33730. /**
  33731. * AKA Diffuse Color in other nomenclature.
  33732. */
  33733. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  33734. /**
  33735. * AKA Specular Color in other nomenclature.
  33736. */
  33737. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  33738. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  33739. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  33740. /**
  33741. * AKA Glossiness in other nomenclature.
  33742. */
  33743. _this._microSurface = 0.9;
  33744. /**
  33745. * source material index of refraction (IOR)' / 'destination material IOR.
  33746. */
  33747. _this._indexOfRefraction = 0.66;
  33748. /**
  33749. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  33750. */
  33751. _this._invertRefractionY = false;
  33752. /**
  33753. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  33754. * Materials half opaque for instance using refraction could benefit from this control.
  33755. */
  33756. _this._linkRefractionWithTransparency = false;
  33757. _this._useLightmapAsShadowmap = false;
  33758. /**
  33759. * Specifies that the alpha is coming form the albedo channel alpha channel.
  33760. */
  33761. _this._useAlphaFromAlbedoTexture = false;
  33762. /**
  33763. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  33764. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  33765. */
  33766. _this._useSpecularOverAlpha = true;
  33767. /**
  33768. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  33769. */
  33770. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  33771. /**
  33772. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  33773. */
  33774. _this._useRoughnessFromMetallicTextureAlpha = true;
  33775. /**
  33776. * Specifies if the metallic texture contains the roughness information in its green channel.
  33777. */
  33778. _this._useRoughnessFromMetallicTextureGreen = false;
  33779. /**
  33780. * Specifies if the metallic texture contains the metallness information in its blue channel.
  33781. */
  33782. _this._useMetallnessFromMetallicTextureBlue = false;
  33783. /**
  33784. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  33785. */
  33786. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  33787. /**
  33788. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  33789. */
  33790. _this._useAmbientInGrayScale = false;
  33791. /**
  33792. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  33793. * The material will try to infer what glossiness each pixel should be.
  33794. */
  33795. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  33796. /**
  33797. * BJS is using an harcoded light falloff based on a manually sets up range.
  33798. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  33799. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  33800. */
  33801. _this._usePhysicalLightFalloff = true;
  33802. /**
  33803. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  33804. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  33805. */
  33806. _this._useRadianceOverAlpha = true;
  33807. /**
  33808. * Allows using the bump map in parallax mode.
  33809. */
  33810. _this._useParallax = false;
  33811. /**
  33812. * Allows using the bump map in parallax occlusion mode.
  33813. */
  33814. _this._useParallaxOcclusion = false;
  33815. /**
  33816. * Controls the scale bias of the parallax mode.
  33817. */
  33818. _this._parallaxScaleBias = 0.05;
  33819. /**
  33820. * If sets to true, disables all the lights affecting the material.
  33821. */
  33822. _this._disableLighting = false;
  33823. /**
  33824. * Number of Simultaneous lights allowed on the material.
  33825. */
  33826. _this._maxSimultaneousLights = 4;
  33827. /**
  33828. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  33829. */
  33830. _this._invertNormalMapX = false;
  33831. /**
  33832. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  33833. */
  33834. _this._invertNormalMapY = false;
  33835. /**
  33836. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33837. */
  33838. _this._twoSidedLighting = false;
  33839. /**
  33840. * Defines the alpha limits in alpha test mode.
  33841. */
  33842. _this._alphaCutOff = 0.4;
  33843. /**
  33844. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  33845. */
  33846. _this._forceAlphaTest = false;
  33847. /**
  33848. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  33849. * in your scene composition.
  33850. */
  33851. _this._preMultiplyAlpha = false;
  33852. /**
  33853. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  33854. * And/Or occlude the blended part.
  33855. */
  33856. _this._useAlphaFresnel = false;
  33857. /**
  33858. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  33859. * from cos thetav and roughness:
  33860. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  33861. */
  33862. _this._environmentBRDFTexture = null;
  33863. /**
  33864. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  33865. */
  33866. _this._forceIrradianceInFragment = false;
  33867. /**
  33868. * Force normal to face away from face.
  33869. * (Temporary internal fix to remove before 3.1)
  33870. */
  33871. _this._forceNormalForward = false;
  33872. _this._renderTargets = new BABYLON.SmartArray(16);
  33873. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  33874. // Setup the default processing configuration to the scene.
  33875. _this._attachImageProcessingConfiguration(null);
  33876. _this.getRenderTargetTextures = function () {
  33877. _this._renderTargets.reset();
  33878. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  33879. _this._renderTargets.push(_this._reflectionTexture);
  33880. }
  33881. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  33882. _this._renderTargets.push(_this._refractionTexture);
  33883. }
  33884. return _this._renderTargets;
  33885. };
  33886. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  33887. return _this;
  33888. }
  33889. /**
  33890. * Attaches a new image processing configuration to the PBR Material.
  33891. * @param configuration
  33892. */
  33893. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  33894. var _this = this;
  33895. if (configuration === this._imageProcessingConfiguration) {
  33896. return;
  33897. }
  33898. // Detaches observer.
  33899. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  33900. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  33901. }
  33902. // Pick the scene configuration if needed.
  33903. if (!configuration) {
  33904. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  33905. }
  33906. else {
  33907. this._imageProcessingConfiguration = configuration;
  33908. }
  33909. // Attaches observer.
  33910. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  33911. _this._markAllSubMeshesAsImageProcessingDirty();
  33912. });
  33913. };
  33914. PBRBaseMaterial.prototype.getClassName = function () {
  33915. return "PBRBaseMaterial";
  33916. };
  33917. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  33918. get: function () {
  33919. return this._useLogarithmicDepth;
  33920. },
  33921. set: function (value) {
  33922. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  33923. },
  33924. enumerable: true,
  33925. configurable: true
  33926. });
  33927. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  33928. if (this._linkRefractionWithTransparency) {
  33929. return false;
  33930. }
  33931. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  33932. };
  33933. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  33934. if (this._forceAlphaTest) {
  33935. return true;
  33936. }
  33937. if (this._linkRefractionWithTransparency) {
  33938. return false;
  33939. }
  33940. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  33941. };
  33942. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  33943. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  33944. };
  33945. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  33946. return this._albedoTexture;
  33947. };
  33948. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  33949. var _this = this;
  33950. if (this.isFrozen) {
  33951. if (this._wasPreviouslyReady) {
  33952. return true;
  33953. }
  33954. }
  33955. if (!subMesh._materialDefines) {
  33956. subMesh._materialDefines = new PBRMaterialDefines();
  33957. }
  33958. var scene = this.getScene();
  33959. var defines = subMesh._materialDefines;
  33960. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  33961. if (defines._renderId === scene.getRenderId()) {
  33962. return true;
  33963. }
  33964. }
  33965. var engine = scene.getEngine();
  33966. // Lights
  33967. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  33968. defines._needNormals = true;
  33969. // Textures
  33970. if (defines._areTexturesDirty) {
  33971. defines._needUVs = false;
  33972. if (scene.texturesEnabled) {
  33973. if (scene.getEngine().getCaps().textureLOD) {
  33974. defines.LODBASEDMICROSFURACE = true;
  33975. }
  33976. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  33977. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  33978. return false;
  33979. }
  33980. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  33981. }
  33982. else {
  33983. defines.ALBEDO = false;
  33984. }
  33985. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  33986. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  33987. return false;
  33988. }
  33989. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  33990. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  33991. }
  33992. else {
  33993. defines.AMBIENT = false;
  33994. }
  33995. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  33996. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  33997. return false;
  33998. }
  33999. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  34000. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  34001. }
  34002. else {
  34003. defines.OPACITY = false;
  34004. }
  34005. var reflectionTexture = this._getReflectionTexture();
  34006. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  34007. if (!reflectionTexture.isReadyOrNotBlocking()) {
  34008. return false;
  34009. }
  34010. defines.REFLECTION = true;
  34011. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  34012. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  34013. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  34014. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  34015. defines.INVERTCUBICMAP = true;
  34016. }
  34017. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  34018. switch (reflectionTexture.coordinatesMode) {
  34019. case BABYLON.Texture.CUBIC_MODE:
  34020. case BABYLON.Texture.INVCUBIC_MODE:
  34021. defines.REFLECTIONMAP_CUBIC = true;
  34022. break;
  34023. case BABYLON.Texture.EXPLICIT_MODE:
  34024. defines.REFLECTIONMAP_EXPLICIT = true;
  34025. break;
  34026. case BABYLON.Texture.PLANAR_MODE:
  34027. defines.REFLECTIONMAP_PLANAR = true;
  34028. break;
  34029. case BABYLON.Texture.PROJECTION_MODE:
  34030. defines.REFLECTIONMAP_PROJECTION = true;
  34031. break;
  34032. case BABYLON.Texture.SKYBOX_MODE:
  34033. defines.REFLECTIONMAP_SKYBOX = true;
  34034. break;
  34035. case BABYLON.Texture.SPHERICAL_MODE:
  34036. defines.REFLECTIONMAP_SPHERICAL = true;
  34037. break;
  34038. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  34039. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  34040. break;
  34041. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  34042. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  34043. break;
  34044. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  34045. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  34046. break;
  34047. }
  34048. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  34049. if (reflectionTexture.sphericalPolynomial) {
  34050. defines.USESPHERICALFROMREFLECTIONMAP = true;
  34051. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  34052. defines.USESPHERICALINFRAGMENT = true;
  34053. }
  34054. }
  34055. }
  34056. }
  34057. else {
  34058. defines.REFLECTION = false;
  34059. defines.REFLECTIONMAP_3D = false;
  34060. defines.REFLECTIONMAP_SPHERICAL = false;
  34061. defines.REFLECTIONMAP_PLANAR = false;
  34062. defines.REFLECTIONMAP_CUBIC = false;
  34063. defines.REFLECTIONMAP_PROJECTION = false;
  34064. defines.REFLECTIONMAP_SKYBOX = false;
  34065. defines.REFLECTIONMAP_EXPLICIT = false;
  34066. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34067. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34068. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34069. defines.INVERTCUBICMAP = false;
  34070. defines.USESPHERICALFROMREFLECTIONMAP = false;
  34071. defines.USESPHERICALINFRAGMENT = false;
  34072. defines.REFLECTIONMAP_OPPOSITEZ = false;
  34073. defines.LODINREFLECTIONALPHA = false;
  34074. defines.GAMMAREFLECTION = false;
  34075. }
  34076. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  34077. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  34078. return false;
  34079. }
  34080. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  34081. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  34082. }
  34083. else {
  34084. defines.LIGHTMAP = false;
  34085. }
  34086. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  34087. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  34088. return false;
  34089. }
  34090. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  34091. }
  34092. else {
  34093. defines.EMISSIVE = false;
  34094. }
  34095. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  34096. if (this._metallicTexture) {
  34097. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  34098. return false;
  34099. }
  34100. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  34101. defines.METALLICWORKFLOW = true;
  34102. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  34103. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  34104. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  34105. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  34106. }
  34107. else if (this._reflectivityTexture) {
  34108. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  34109. return false;
  34110. }
  34111. defines.METALLICWORKFLOW = false;
  34112. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  34113. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  34114. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  34115. }
  34116. else {
  34117. defines.METALLICWORKFLOW = false;
  34118. defines.REFLECTIVITY = false;
  34119. }
  34120. if (this._microSurfaceTexture) {
  34121. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  34122. return false;
  34123. }
  34124. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  34125. }
  34126. else {
  34127. defines.MICROSURFACEMAP = false;
  34128. }
  34129. }
  34130. else {
  34131. defines.REFLECTIVITY = false;
  34132. defines.MICROSURFACEMAP = false;
  34133. }
  34134. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  34135. // Bump texure can not be none blocking.
  34136. if (!this._bumpTexture.isReady()) {
  34137. return false;
  34138. }
  34139. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  34140. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  34141. defines.PARALLAX = true;
  34142. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  34143. }
  34144. else {
  34145. defines.PARALLAX = false;
  34146. }
  34147. }
  34148. else {
  34149. defines.BUMP = false;
  34150. }
  34151. var refractionTexture = this._getRefractionTexture();
  34152. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  34153. if (!refractionTexture.isReadyOrNotBlocking()) {
  34154. return false;
  34155. }
  34156. defines.REFRACTION = true;
  34157. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  34158. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  34159. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  34160. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  34161. if (this._linkRefractionWithTransparency) {
  34162. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  34163. }
  34164. }
  34165. else {
  34166. defines.REFRACTION = false;
  34167. }
  34168. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  34169. // This is blocking.
  34170. if (!this._environmentBRDFTexture.isReady()) {
  34171. return false;
  34172. }
  34173. defines.ENVIRONMENTBRDF = true;
  34174. }
  34175. if (this._shouldUseAlphaFromAlbedoTexture()) {
  34176. defines.ALPHAFROMALBEDO = true;
  34177. }
  34178. }
  34179. if (this._useSpecularOverAlpha) {
  34180. defines.SPECULAROVERALPHA = true;
  34181. }
  34182. if (this._usePhysicalLightFalloff) {
  34183. defines.USEPHYSICALLIGHTFALLOFF = true;
  34184. }
  34185. if (this._useRadianceOverAlpha) {
  34186. defines.RADIANCEOVERALPHA = true;
  34187. }
  34188. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  34189. defines.METALLICWORKFLOW = true;
  34190. }
  34191. if (!this.backFaceCulling && this._twoSidedLighting) {
  34192. defines.TWOSIDEDLIGHTING = true;
  34193. }
  34194. defines.ALPHATESTVALUE = this._alphaCutOff;
  34195. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  34196. defines.ALPHABLEND = this.needAlphaBlending();
  34197. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  34198. }
  34199. if (defines._areImageProcessingDirty) {
  34200. if (!this._imageProcessingConfiguration.isReady()) {
  34201. return false;
  34202. }
  34203. this._imageProcessingConfiguration.prepareDefines(defines);
  34204. }
  34205. defines.FORCENORMALFORWARD = this._forceNormalForward;
  34206. // Misc.
  34207. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  34208. // Values that need to be evaluated on every frame
  34209. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  34210. // Attribs
  34211. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  34212. if (mesh) {
  34213. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34214. mesh.createNormals(true);
  34215. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  34216. }
  34217. }
  34218. }
  34219. // Get correct effect
  34220. if (defines.isDirty) {
  34221. defines.markAsProcessed();
  34222. scene.resetCachedMaterial();
  34223. // Fallbacks
  34224. var fallbacks = new BABYLON.EffectFallbacks();
  34225. if (defines.ENVIRONMENTBRDF) {
  34226. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  34227. }
  34228. if (defines.REFLECTION) {
  34229. fallbacks.addFallback(0, "REFLECTION");
  34230. }
  34231. if (defines.REFRACTION) {
  34232. fallbacks.addFallback(0, "REFRACTION");
  34233. }
  34234. if (defines.REFLECTIVITY) {
  34235. fallbacks.addFallback(0, "REFLECTIVITY");
  34236. }
  34237. if (defines.BUMP) {
  34238. fallbacks.addFallback(0, "BUMP");
  34239. }
  34240. if (defines.PARALLAX) {
  34241. fallbacks.addFallback(1, "PARALLAX");
  34242. }
  34243. if (defines.PARALLAXOCCLUSION) {
  34244. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  34245. }
  34246. if (defines.SPECULAROVERALPHA) {
  34247. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  34248. }
  34249. if (defines.FOG) {
  34250. fallbacks.addFallback(1, "FOG");
  34251. }
  34252. if (defines.POINTSIZE) {
  34253. fallbacks.addFallback(0, "POINTSIZE");
  34254. }
  34255. if (defines.LOGARITHMICDEPTH) {
  34256. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  34257. }
  34258. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  34259. if (defines.SPECULARTERM) {
  34260. fallbacks.addFallback(0, "SPECULARTERM");
  34261. }
  34262. if (defines.NUM_BONE_INFLUENCERS > 0) {
  34263. fallbacks.addCPUSkinningFallback(0, mesh);
  34264. }
  34265. //Attributes
  34266. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34267. if (defines.NORMAL) {
  34268. attribs.push(BABYLON.VertexBuffer.NormalKind);
  34269. }
  34270. if (defines.TANGENT) {
  34271. attribs.push(BABYLON.VertexBuffer.TangentKind);
  34272. }
  34273. if (defines.UV1) {
  34274. attribs.push(BABYLON.VertexBuffer.UVKind);
  34275. }
  34276. if (defines.UV2) {
  34277. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34278. }
  34279. if (defines.VERTEXCOLOR) {
  34280. attribs.push(BABYLON.VertexBuffer.ColorKind);
  34281. }
  34282. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  34283. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  34284. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  34285. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  34286. "vFogInfos", "vFogColor", "pointSize",
  34287. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  34288. "mBones",
  34289. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  34290. "vLightingIntensity",
  34291. "logarithmicDepthConstant",
  34292. "vSphericalX", "vSphericalY", "vSphericalZ",
  34293. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  34294. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  34295. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  34296. "vTangentSpaceParams"
  34297. ];
  34298. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  34299. "bumpSampler", "lightmapSampler", "opacitySampler",
  34300. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  34301. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  34302. "microSurfaceSampler", "environmentBrdfSampler"];
  34303. var uniformBuffers = ["Material", "Scene"];
  34304. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  34305. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  34306. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  34307. uniformsNames: uniforms,
  34308. uniformBuffersNames: uniformBuffers,
  34309. samplers: samplers,
  34310. defines: defines,
  34311. maxSimultaneousLights: this._maxSimultaneousLights
  34312. });
  34313. var onCompiled = function (effect) {
  34314. if (_this.onCompiled) {
  34315. _this.onCompiled(effect);
  34316. }
  34317. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  34318. };
  34319. var join = defines.toString();
  34320. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  34321. attributes: attribs,
  34322. uniformsNames: uniforms,
  34323. uniformBuffersNames: uniformBuffers,
  34324. samplers: samplers,
  34325. defines: join,
  34326. fallbacks: fallbacks,
  34327. onCompiled: onCompiled,
  34328. onError: this.onError,
  34329. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  34330. }, engine), defines);
  34331. this.buildUniformLayout();
  34332. }
  34333. if (!subMesh.effect.isReady()) {
  34334. return false;
  34335. }
  34336. defines._renderId = scene.getRenderId();
  34337. this._wasPreviouslyReady = true;
  34338. return true;
  34339. };
  34340. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  34341. // Order is important !
  34342. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  34343. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  34344. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  34345. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  34346. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  34347. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  34348. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  34349. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  34350. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  34351. this._uniformBuffer.addUniform("vBumpInfos", 3);
  34352. this._uniformBuffer.addUniform("albedoMatrix", 16);
  34353. this._uniformBuffer.addUniform("ambientMatrix", 16);
  34354. this._uniformBuffer.addUniform("opacityMatrix", 16);
  34355. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  34356. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  34357. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  34358. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  34359. this._uniformBuffer.addUniform("bumpMatrix", 16);
  34360. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  34361. this._uniformBuffer.addUniform("refractionMatrix", 16);
  34362. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  34363. this._uniformBuffer.addUniform("vReflectionColor", 3);
  34364. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  34365. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  34366. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  34367. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  34368. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  34369. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  34370. this._uniformBuffer.addUniform("pointSize", 1);
  34371. this._uniformBuffer.create();
  34372. };
  34373. PBRBaseMaterial.prototype.unbind = function () {
  34374. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  34375. this._uniformBuffer.setTexture("reflectionSampler", null);
  34376. }
  34377. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  34378. this._uniformBuffer.setTexture("refractionSampler", null);
  34379. }
  34380. _super.prototype.unbind.call(this);
  34381. };
  34382. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34383. this._activeEffect.setMatrix("world", world);
  34384. };
  34385. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34386. var scene = this.getScene();
  34387. var defines = subMesh._materialDefines;
  34388. if (!defines) {
  34389. return;
  34390. }
  34391. var effect = subMesh.effect;
  34392. this._activeEffect = effect;
  34393. // Matrices
  34394. this.bindOnlyWorldMatrix(world);
  34395. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  34396. // Bones
  34397. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  34398. if (mustRebind) {
  34399. this._uniformBuffer.bindToEffect(effect, "Material");
  34400. this.bindViewProjection(effect);
  34401. var reflectionTexture = this._getReflectionTexture();
  34402. var refractionTexture = this._getRefractionTexture();
  34403. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  34404. // Texture uniforms
  34405. if (scene.texturesEnabled) {
  34406. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  34407. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  34408. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  34409. }
  34410. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  34411. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  34412. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  34413. }
  34414. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  34415. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  34416. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  34417. }
  34418. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  34419. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  34420. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  34421. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  34422. var polynomials = reflectionTexture.sphericalPolynomial;
  34423. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  34424. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  34425. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  34426. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  34427. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  34428. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  34429. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  34430. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  34431. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  34432. }
  34433. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  34434. }
  34435. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  34436. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  34437. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  34438. }
  34439. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  34440. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  34441. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  34442. }
  34443. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  34444. if (this._metallicTexture) {
  34445. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  34446. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  34447. }
  34448. else if (this._reflectivityTexture) {
  34449. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  34450. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  34451. }
  34452. if (this._microSurfaceTexture) {
  34453. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  34454. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  34455. }
  34456. }
  34457. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  34458. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  34459. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  34460. if (scene._mirroredCameraPosition) {
  34461. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  34462. }
  34463. else {
  34464. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  34465. }
  34466. }
  34467. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  34468. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  34469. var depth = 1.0;
  34470. if (!refractionTexture.isCube) {
  34471. if (refractionTexture.depth) {
  34472. depth = refractionTexture.depth;
  34473. }
  34474. }
  34475. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  34476. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  34477. }
  34478. }
  34479. // Point size
  34480. if (this.pointsCloud) {
  34481. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  34482. }
  34483. // Colors
  34484. if (defines.METALLICWORKFLOW) {
  34485. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  34486. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  34487. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  34488. }
  34489. else {
  34490. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  34491. }
  34492. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  34493. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  34494. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  34495. // Misc
  34496. this._lightingInfos.x = this._directIntensity;
  34497. this._lightingInfos.y = this._emissiveIntensity;
  34498. this._lightingInfos.z = this._environmentIntensity;
  34499. this._lightingInfos.w = this._specularIntensity;
  34500. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  34501. }
  34502. // Textures
  34503. if (scene.texturesEnabled) {
  34504. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  34505. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  34506. }
  34507. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  34508. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  34509. }
  34510. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  34511. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  34512. }
  34513. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  34514. if (defines.LODBASEDMICROSFURACE) {
  34515. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  34516. }
  34517. else {
  34518. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  34519. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  34520. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  34521. }
  34522. }
  34523. if (defines.ENVIRONMENTBRDF) {
  34524. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  34525. }
  34526. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  34527. if (defines.LODBASEDMICROSFURACE) {
  34528. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  34529. }
  34530. else {
  34531. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  34532. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  34533. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  34534. }
  34535. }
  34536. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  34537. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  34538. }
  34539. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  34540. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  34541. }
  34542. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  34543. if (this._metallicTexture) {
  34544. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  34545. }
  34546. else if (this._reflectivityTexture) {
  34547. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  34548. }
  34549. if (this._microSurfaceTexture) {
  34550. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  34551. }
  34552. }
  34553. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  34554. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  34555. }
  34556. }
  34557. // Clip plane
  34558. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  34559. // Colors
  34560. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  34561. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  34562. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  34563. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  34564. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  34565. }
  34566. if (mustRebind || !this.isFrozen) {
  34567. // Lights
  34568. if (scene.lightsEnabled && !this._disableLighting) {
  34569. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  34570. }
  34571. // View
  34572. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  34573. this.bindView(effect);
  34574. }
  34575. // Fog
  34576. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  34577. // Morph targets
  34578. if (defines.NUM_MORPH_INFLUENCERS) {
  34579. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  34580. }
  34581. // image processing
  34582. this._imageProcessingConfiguration.bind(this._activeEffect);
  34583. // Log. depth
  34584. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  34585. }
  34586. this._uniformBuffer.update();
  34587. this._afterBind(mesh);
  34588. scene = null;
  34589. };
  34590. PBRBaseMaterial.prototype.getAnimatables = function () {
  34591. var results = [];
  34592. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  34593. results.push(this._albedoTexture);
  34594. }
  34595. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  34596. results.push(this._ambientTexture);
  34597. }
  34598. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  34599. results.push(this._opacityTexture);
  34600. }
  34601. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  34602. results.push(this._reflectionTexture);
  34603. }
  34604. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  34605. results.push(this._emissiveTexture);
  34606. }
  34607. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  34608. results.push(this._metallicTexture);
  34609. }
  34610. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  34611. results.push(this._reflectivityTexture);
  34612. }
  34613. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  34614. results.push(this._bumpTexture);
  34615. }
  34616. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  34617. results.push(this._lightmapTexture);
  34618. }
  34619. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  34620. results.push(this._refractionTexture);
  34621. }
  34622. return results;
  34623. };
  34624. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  34625. if (this._reflectionTexture) {
  34626. return this._reflectionTexture;
  34627. }
  34628. return this.getScene().environmentTexture;
  34629. };
  34630. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  34631. if (this._refractionTexture) {
  34632. return this._refractionTexture;
  34633. }
  34634. if (this._linkRefractionWithTransparency) {
  34635. return this.getScene().environmentTexture;
  34636. }
  34637. return null;
  34638. };
  34639. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34640. if (forceDisposeTextures) {
  34641. if (this._albedoTexture) {
  34642. this._albedoTexture.dispose();
  34643. }
  34644. if (this._ambientTexture) {
  34645. this._ambientTexture.dispose();
  34646. }
  34647. if (this._opacityTexture) {
  34648. this._opacityTexture.dispose();
  34649. }
  34650. if (this._reflectionTexture) {
  34651. this._reflectionTexture.dispose();
  34652. }
  34653. if (this._environmentBRDFTexture) {
  34654. this._environmentBRDFTexture.dispose();
  34655. }
  34656. if (this._emissiveTexture) {
  34657. this._emissiveTexture.dispose();
  34658. }
  34659. if (this._metallicTexture) {
  34660. this._metallicTexture.dispose();
  34661. }
  34662. if (this._reflectivityTexture) {
  34663. this._reflectivityTexture.dispose();
  34664. }
  34665. if (this._bumpTexture) {
  34666. this._bumpTexture.dispose();
  34667. }
  34668. if (this._lightmapTexture) {
  34669. this._lightmapTexture.dispose();
  34670. }
  34671. if (this._refractionTexture) {
  34672. this._refractionTexture.dispose();
  34673. }
  34674. }
  34675. this._renderTargets.dispose();
  34676. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34677. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34678. }
  34679. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  34680. };
  34681. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  34682. __decorate([
  34683. BABYLON.serializeAsImageProcessingConfiguration()
  34684. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  34685. __decorate([
  34686. BABYLON.serialize()
  34687. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  34688. return PBRBaseMaterial;
  34689. }(BABYLON.PushMaterial));
  34690. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  34691. })(BABYLON || (BABYLON = {}));
  34692. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  34693. var BABYLON;
  34694. (function (BABYLON) {
  34695. var Internals;
  34696. (function (Internals) {
  34697. /**
  34698. * The Physically based simple base material of BJS.
  34699. *
  34700. * This enables better naming and convention enforcements on top of the pbrMaterial.
  34701. * It is used as the base class for both the specGloss and metalRough conventions.
  34702. */
  34703. var PBRBaseSimpleMaterial = (function (_super) {
  34704. __extends(PBRBaseSimpleMaterial, _super);
  34705. /**
  34706. * Instantiates a new PBRMaterial instance.
  34707. *
  34708. * @param name The material name
  34709. * @param scene The scene the material will be use in.
  34710. */
  34711. function PBRBaseSimpleMaterial(name, scene) {
  34712. var _this = _super.call(this, name, scene) || this;
  34713. /**
  34714. * Number of Simultaneous lights allowed on the material.
  34715. */
  34716. _this.maxSimultaneousLights = 4;
  34717. /**
  34718. * If sets to true, disables all the lights affecting the material.
  34719. */
  34720. _this.disableLighting = false;
  34721. /**
  34722. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34723. */
  34724. _this.invertNormalMapX = false;
  34725. /**
  34726. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34727. */
  34728. _this.invertNormalMapY = false;
  34729. /**
  34730. * Emissivie color used to self-illuminate the model.
  34731. */
  34732. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  34733. /**
  34734. * Occlusion Channel Strenght.
  34735. */
  34736. _this.occlusionStrength = 1.0;
  34737. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  34738. _this._useAmbientInGrayScale = true;
  34739. return _this;
  34740. }
  34741. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  34742. /**
  34743. * Gets the current transparency mode.
  34744. */
  34745. get: function () {
  34746. return this._transparencyMode;
  34747. },
  34748. /**
  34749. * Sets the transparency mode of the material.
  34750. */
  34751. set: function (value) {
  34752. if (this._transparencyMode === value) {
  34753. return;
  34754. }
  34755. this._transparencyMode = value;
  34756. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  34757. this._forceAlphaTest = true;
  34758. }
  34759. else {
  34760. this._forceAlphaTest = false;
  34761. }
  34762. this._markAllSubMeshesAsTexturesDirty();
  34763. },
  34764. enumerable: true,
  34765. configurable: true
  34766. });
  34767. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  34768. /**
  34769. * Gets the current double sided mode.
  34770. */
  34771. get: function () {
  34772. return this._twoSidedLighting;
  34773. },
  34774. /**
  34775. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34776. */
  34777. set: function (value) {
  34778. if (this._twoSidedLighting === value) {
  34779. return;
  34780. }
  34781. this._twoSidedLighting = value;
  34782. this.backFaceCulling = !value;
  34783. this._markAllSubMeshesAsTexturesDirty();
  34784. },
  34785. enumerable: true,
  34786. configurable: true
  34787. });
  34788. /**
  34789. * Specifies wether or not the alpha value of the albedo texture should be used.
  34790. */
  34791. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  34792. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  34793. };
  34794. /**
  34795. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  34796. */
  34797. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  34798. if (this._linkRefractionWithTransparency) {
  34799. return false;
  34800. }
  34801. return (this.alpha < 1.0) ||
  34802. (this._shouldUseAlphaFromAlbedoTexture() &&
  34803. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  34804. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  34805. };
  34806. /**
  34807. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  34808. */
  34809. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  34810. if (this._linkRefractionWithTransparency) {
  34811. return false;
  34812. }
  34813. return this._shouldUseAlphaFromAlbedoTexture() &&
  34814. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  34815. };
  34816. /**
  34817. * Return the active textures of the material.
  34818. */
  34819. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  34820. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34821. if (this.environmentTexture) {
  34822. activeTextures.push(this.environmentTexture);
  34823. }
  34824. if (this.normalTexture) {
  34825. activeTextures.push(this.normalTexture);
  34826. }
  34827. if (this.emissiveTexture) {
  34828. activeTextures.push(this.emissiveTexture);
  34829. }
  34830. if (this.occlusionTexture) {
  34831. activeTextures.push(this.occlusionTexture);
  34832. }
  34833. return activeTextures;
  34834. };
  34835. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  34836. return "PBRBaseSimpleMaterial";
  34837. };
  34838. __decorate([
  34839. BABYLON.serialize(),
  34840. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34841. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  34842. __decorate([
  34843. BABYLON.serialize(),
  34844. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34845. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  34846. __decorate([
  34847. BABYLON.serializeAsTexture(),
  34848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  34849. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  34850. __decorate([
  34851. BABYLON.serialize(),
  34852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34853. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  34854. __decorate([
  34855. BABYLON.serialize(),
  34856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34857. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  34858. __decorate([
  34859. BABYLON.serializeAsTexture(),
  34860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  34861. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  34862. __decorate([
  34863. BABYLON.serializeAsColor3("emissive"),
  34864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34865. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  34866. __decorate([
  34867. BABYLON.serializeAsTexture(),
  34868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34869. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  34870. __decorate([
  34871. BABYLON.serialize(),
  34872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  34873. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  34874. __decorate([
  34875. BABYLON.serializeAsTexture(),
  34876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  34877. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  34878. __decorate([
  34879. BABYLON.serialize(),
  34880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  34881. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  34882. __decorate([
  34883. BABYLON.serialize()
  34884. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  34885. __decorate([
  34886. BABYLON.serialize()
  34887. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  34888. return PBRBaseSimpleMaterial;
  34889. }(BABYLON.PBRBaseMaterial));
  34890. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  34891. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34892. })(BABYLON || (BABYLON = {}));
  34893. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  34894. var BABYLON;
  34895. (function (BABYLON) {
  34896. /**
  34897. * The Physically based material of BJS.
  34898. *
  34899. * This offers the main features of a standard PBR material.
  34900. * For more information, please refer to the documentation :
  34901. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  34902. */
  34903. var PBRMaterial = (function (_super) {
  34904. __extends(PBRMaterial, _super);
  34905. /**
  34906. * Instantiates a new PBRMaterial instance.
  34907. *
  34908. * @param name The material name
  34909. * @param scene The scene the material will be use in.
  34910. */
  34911. function PBRMaterial(name, scene) {
  34912. var _this = _super.call(this, name, scene) || this;
  34913. /**
  34914. * Intensity of the direct lights e.g. the four lights available in your scene.
  34915. * This impacts both the direct diffuse and specular highlights.
  34916. */
  34917. _this.directIntensity = 1.0;
  34918. /**
  34919. * Intensity of the emissive part of the material.
  34920. * This helps controlling the emissive effect without modifying the emissive color.
  34921. */
  34922. _this.emissiveIntensity = 1.0;
  34923. /**
  34924. * Intensity of the environment e.g. how much the environment will light the object
  34925. * either through harmonics for rough material or through the refelction for shiny ones.
  34926. */
  34927. _this.environmentIntensity = 1.0;
  34928. /**
  34929. * This is a special control allowing the reduction of the specular highlights coming from the
  34930. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  34931. */
  34932. _this.specularIntensity = 1.0;
  34933. /**
  34934. * Debug Control allowing disabling the bump map on this material.
  34935. */
  34936. _this.disableBumpMap = false;
  34937. /**
  34938. * AKA Occlusion Texture Intensity in other nomenclature.
  34939. */
  34940. _this.ambientTextureStrength = 1.0;
  34941. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  34942. /**
  34943. * AKA Diffuse Color in other nomenclature.
  34944. */
  34945. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  34946. /**
  34947. * AKA Specular Color in other nomenclature.
  34948. */
  34949. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  34950. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  34951. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  34952. /**
  34953. * AKA Glossiness in other nomenclature.
  34954. */
  34955. _this.microSurface = 1.0;
  34956. /**
  34957. * source material index of refraction (IOR)' / 'destination material IOR.
  34958. */
  34959. _this.indexOfRefraction = 0.66;
  34960. /**
  34961. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  34962. */
  34963. _this.invertRefractionY = false;
  34964. /**
  34965. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  34966. * Materials half opaque for instance using refraction could benefit from this control.
  34967. */
  34968. _this.linkRefractionWithTransparency = false;
  34969. _this.useLightmapAsShadowmap = false;
  34970. /**
  34971. * Specifies that the alpha is coming form the albedo channel alpha channel.
  34972. */
  34973. _this.useAlphaFromAlbedoTexture = false;
  34974. /**
  34975. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  34976. */
  34977. _this.forceAlphaTest = false;
  34978. /**
  34979. * Defines the alpha limits in alpha test mode.
  34980. */
  34981. _this.alphaCutOff = 0.4;
  34982. /**
  34983. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  34984. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  34985. */
  34986. _this.useSpecularOverAlpha = true;
  34987. /**
  34988. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  34989. */
  34990. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  34991. /**
  34992. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  34993. */
  34994. _this.useRoughnessFromMetallicTextureAlpha = true;
  34995. /**
  34996. * Specifies if the metallic texture contains the roughness information in its green channel.
  34997. */
  34998. _this.useRoughnessFromMetallicTextureGreen = false;
  34999. /**
  35000. * Specifies if the metallic texture contains the metallness information in its blue channel.
  35001. */
  35002. _this.useMetallnessFromMetallicTextureBlue = false;
  35003. /**
  35004. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  35005. */
  35006. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  35007. /**
  35008. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  35009. */
  35010. _this.useAmbientInGrayScale = false;
  35011. /**
  35012. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  35013. * The material will try to infer what glossiness each pixel should be.
  35014. */
  35015. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  35016. /**
  35017. * BJS is using an harcoded light falloff based on a manually sets up range.
  35018. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  35019. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  35020. */
  35021. _this.usePhysicalLightFalloff = true;
  35022. /**
  35023. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  35024. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  35025. */
  35026. _this.useRadianceOverAlpha = true;
  35027. /**
  35028. * Allows using the bump map in parallax mode.
  35029. */
  35030. _this.useParallax = false;
  35031. /**
  35032. * Allows using the bump map in parallax occlusion mode.
  35033. */
  35034. _this.useParallaxOcclusion = false;
  35035. /**
  35036. * Controls the scale bias of the parallax mode.
  35037. */
  35038. _this.parallaxScaleBias = 0.05;
  35039. /**
  35040. * If sets to true, disables all the lights affecting the material.
  35041. */
  35042. _this.disableLighting = false;
  35043. /**
  35044. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  35045. */
  35046. _this.forceIrradianceInFragment = false;
  35047. /**
  35048. * Number of Simultaneous lights allowed on the material.
  35049. */
  35050. _this.maxSimultaneousLights = 4;
  35051. /**
  35052. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35053. */
  35054. _this.invertNormalMapX = false;
  35055. /**
  35056. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35057. */
  35058. _this.invertNormalMapY = false;
  35059. /**
  35060. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35061. */
  35062. _this.twoSidedLighting = false;
  35063. /**
  35064. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  35065. * in your scene composition.
  35066. */
  35067. _this.preMultiplyAlpha = false;
  35068. /**
  35069. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35070. * And/Or occlude the blended part.
  35071. */
  35072. _this.useAlphaFresnel = false;
  35073. /**
  35074. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35075. * And/Or occlude the blended part.
  35076. */
  35077. _this.environmentBRDFTexture = null;
  35078. /**
  35079. * Force normal to face away from face.
  35080. * (Temporary internal fix to remove before 3.1)
  35081. */
  35082. _this.forceNormalForward = false;
  35083. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  35084. return _this;
  35085. }
  35086. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  35087. /**
  35088. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  35089. */
  35090. get: function () {
  35091. return this._PBRMATERIAL_OPAQUE;
  35092. },
  35093. enumerable: true,
  35094. configurable: true
  35095. });
  35096. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  35097. /**
  35098. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  35099. */
  35100. get: function () {
  35101. return this._PBRMATERIAL_ALPHATEST;
  35102. },
  35103. enumerable: true,
  35104. configurable: true
  35105. });
  35106. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  35107. /**
  35108. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  35109. */
  35110. get: function () {
  35111. return this._PBRMATERIAL_ALPHABLEND;
  35112. },
  35113. enumerable: true,
  35114. configurable: true
  35115. });
  35116. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  35117. /**
  35118. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  35119. * They are also discarded below the alpha cutoff threshold to improve performances.
  35120. */
  35121. get: function () {
  35122. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  35123. },
  35124. enumerable: true,
  35125. configurable: true
  35126. });
  35127. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  35128. /**
  35129. * Gets the image processing configuration used either in this material.
  35130. */
  35131. get: function () {
  35132. return this._imageProcessingConfiguration;
  35133. },
  35134. /**
  35135. * Sets the Default image processing configuration used either in the this material.
  35136. *
  35137. * If sets to null, the scene one is in use.
  35138. */
  35139. set: function (value) {
  35140. this._attachImageProcessingConfiguration(value);
  35141. // Ensure the effect will be rebuilt.
  35142. this._markAllSubMeshesAsTexturesDirty();
  35143. },
  35144. enumerable: true,
  35145. configurable: true
  35146. });
  35147. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  35148. /**
  35149. * Gets wether the color curves effect is enabled.
  35150. */
  35151. get: function () {
  35152. return this.imageProcessingConfiguration.colorCurvesEnabled;
  35153. },
  35154. /**
  35155. * Sets wether the color curves effect is enabled.
  35156. */
  35157. set: function (value) {
  35158. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  35159. },
  35160. enumerable: true,
  35161. configurable: true
  35162. });
  35163. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  35164. /**
  35165. * Gets wether the color grading effect is enabled.
  35166. */
  35167. get: function () {
  35168. return this.imageProcessingConfiguration.colorGradingEnabled;
  35169. },
  35170. /**
  35171. * Gets wether the color grading effect is enabled.
  35172. */
  35173. set: function (value) {
  35174. this.imageProcessingConfiguration.colorGradingEnabled = value;
  35175. },
  35176. enumerable: true,
  35177. configurable: true
  35178. });
  35179. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  35180. /**
  35181. * Gets wether tonemapping is enabled or not.
  35182. */
  35183. get: function () {
  35184. return this._imageProcessingConfiguration.toneMappingEnabled;
  35185. },
  35186. /**
  35187. * Sets wether tonemapping is enabled or not
  35188. */
  35189. set: function (value) {
  35190. this._imageProcessingConfiguration.toneMappingEnabled = value;
  35191. },
  35192. enumerable: true,
  35193. configurable: true
  35194. });
  35195. ;
  35196. ;
  35197. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  35198. /**
  35199. * The camera exposure used on this material.
  35200. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35201. * This corresponds to a photographic exposure.
  35202. */
  35203. get: function () {
  35204. return this._imageProcessingConfiguration.exposure;
  35205. },
  35206. /**
  35207. * The camera exposure used on this material.
  35208. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35209. * This corresponds to a photographic exposure.
  35210. */
  35211. set: function (value) {
  35212. this._imageProcessingConfiguration.exposure = value;
  35213. },
  35214. enumerable: true,
  35215. configurable: true
  35216. });
  35217. ;
  35218. ;
  35219. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  35220. /**
  35221. * Gets The camera contrast used on this material.
  35222. */
  35223. get: function () {
  35224. return this._imageProcessingConfiguration.contrast;
  35225. },
  35226. /**
  35227. * Sets The camera contrast used on this material.
  35228. */
  35229. set: function (value) {
  35230. this._imageProcessingConfiguration.contrast = value;
  35231. },
  35232. enumerable: true,
  35233. configurable: true
  35234. });
  35235. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  35236. /**
  35237. * Gets the Color Grading 2D Lookup Texture.
  35238. */
  35239. get: function () {
  35240. return this._imageProcessingConfiguration.colorGradingTexture;
  35241. },
  35242. /**
  35243. * Sets the Color Grading 2D Lookup Texture.
  35244. */
  35245. set: function (value) {
  35246. this._imageProcessingConfiguration.colorGradingTexture = value;
  35247. },
  35248. enumerable: true,
  35249. configurable: true
  35250. });
  35251. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  35252. /**
  35253. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35254. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35255. * 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;
  35256. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35257. */
  35258. get: function () {
  35259. return this._imageProcessingConfiguration.colorCurves;
  35260. },
  35261. /**
  35262. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35263. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35264. * 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;
  35265. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35266. */
  35267. set: function (value) {
  35268. this._imageProcessingConfiguration.colorCurves = value;
  35269. },
  35270. enumerable: true,
  35271. configurable: true
  35272. });
  35273. PBRMaterial.prototype.getClassName = function () {
  35274. return "PBRMaterial";
  35275. };
  35276. PBRMaterial.prototype.getActiveTextures = function () {
  35277. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35278. if (this._albedoTexture) {
  35279. activeTextures.push(this._albedoTexture);
  35280. }
  35281. if (this._ambientTexture) {
  35282. activeTextures.push(this._ambientTexture);
  35283. }
  35284. if (this._opacityTexture) {
  35285. activeTextures.push(this._opacityTexture);
  35286. }
  35287. if (this._reflectionTexture) {
  35288. activeTextures.push(this._reflectionTexture);
  35289. }
  35290. if (this._emissiveTexture) {
  35291. activeTextures.push(this._emissiveTexture);
  35292. }
  35293. if (this._reflectivityTexture) {
  35294. activeTextures.push(this._reflectivityTexture);
  35295. }
  35296. if (this._metallicTexture) {
  35297. activeTextures.push(this._metallicTexture);
  35298. }
  35299. if (this._microSurfaceTexture) {
  35300. activeTextures.push(this._microSurfaceTexture);
  35301. }
  35302. if (this._bumpTexture) {
  35303. activeTextures.push(this._bumpTexture);
  35304. }
  35305. if (this._lightmapTexture) {
  35306. activeTextures.push(this._lightmapTexture);
  35307. }
  35308. if (this._refractionTexture) {
  35309. activeTextures.push(this._refractionTexture);
  35310. }
  35311. return activeTextures;
  35312. };
  35313. PBRMaterial.prototype.hasTexture = function (texture) {
  35314. if (_super.prototype.hasTexture.call(this, texture)) {
  35315. return true;
  35316. }
  35317. if (this._albedoTexture === texture) {
  35318. return true;
  35319. }
  35320. if (this._ambientTexture === texture) {
  35321. return true;
  35322. }
  35323. if (this._opacityTexture === texture) {
  35324. return true;
  35325. }
  35326. if (this._reflectionTexture === texture) {
  35327. return true;
  35328. }
  35329. if (this._reflectivityTexture === texture) {
  35330. return true;
  35331. }
  35332. if (this._metallicTexture === texture) {
  35333. return true;
  35334. }
  35335. if (this._microSurfaceTexture === texture) {
  35336. return true;
  35337. }
  35338. if (this._bumpTexture === texture) {
  35339. return true;
  35340. }
  35341. if (this._lightmapTexture === texture) {
  35342. return true;
  35343. }
  35344. if (this._refractionTexture === texture) {
  35345. return true;
  35346. }
  35347. return false;
  35348. };
  35349. PBRMaterial.prototype.clone = function (name) {
  35350. var _this = this;
  35351. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  35352. clone.id = name;
  35353. clone.name = name;
  35354. return clone;
  35355. };
  35356. PBRMaterial.prototype.serialize = function () {
  35357. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  35358. serializationObject.customType = "BABYLON.PBRMaterial";
  35359. return serializationObject;
  35360. };
  35361. // Statics
  35362. PBRMaterial.Parse = function (source, scene, rootUrl) {
  35363. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  35364. };
  35365. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  35366. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  35367. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  35368. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  35369. __decorate([
  35370. BABYLON.serialize(),
  35371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35372. ], PBRMaterial.prototype, "directIntensity", void 0);
  35373. __decorate([
  35374. BABYLON.serialize(),
  35375. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35376. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  35377. __decorate([
  35378. BABYLON.serialize(),
  35379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35380. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  35381. __decorate([
  35382. BABYLON.serialize(),
  35383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35384. ], PBRMaterial.prototype, "specularIntensity", void 0);
  35385. __decorate([
  35386. BABYLON.serialize(),
  35387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35388. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  35389. __decorate([
  35390. BABYLON.serializeAsTexture(),
  35391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35392. ], PBRMaterial.prototype, "albedoTexture", void 0);
  35393. __decorate([
  35394. BABYLON.serializeAsTexture(),
  35395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35396. ], PBRMaterial.prototype, "ambientTexture", void 0);
  35397. __decorate([
  35398. BABYLON.serialize(),
  35399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35400. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  35401. __decorate([
  35402. BABYLON.serializeAsTexture(),
  35403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35404. ], PBRMaterial.prototype, "opacityTexture", void 0);
  35405. __decorate([
  35406. BABYLON.serializeAsTexture(),
  35407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35408. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  35409. __decorate([
  35410. BABYLON.serializeAsTexture(),
  35411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35412. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  35413. __decorate([
  35414. BABYLON.serializeAsTexture(),
  35415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35416. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  35417. __decorate([
  35418. BABYLON.serializeAsTexture(),
  35419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35420. ], PBRMaterial.prototype, "metallicTexture", void 0);
  35421. __decorate([
  35422. BABYLON.serialize(),
  35423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35424. ], PBRMaterial.prototype, "metallic", void 0);
  35425. __decorate([
  35426. BABYLON.serialize(),
  35427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35428. ], PBRMaterial.prototype, "roughness", void 0);
  35429. __decorate([
  35430. BABYLON.serializeAsTexture(),
  35431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35432. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  35433. __decorate([
  35434. BABYLON.serializeAsTexture(),
  35435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35436. ], PBRMaterial.prototype, "bumpTexture", void 0);
  35437. __decorate([
  35438. BABYLON.serializeAsTexture(),
  35439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  35440. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  35441. __decorate([
  35442. BABYLON.serializeAsTexture(),
  35443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35444. ], PBRMaterial.prototype, "refractionTexture", void 0);
  35445. __decorate([
  35446. BABYLON.serializeAsColor3("ambient"),
  35447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35448. ], PBRMaterial.prototype, "ambientColor", void 0);
  35449. __decorate([
  35450. BABYLON.serializeAsColor3("albedo"),
  35451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35452. ], PBRMaterial.prototype, "albedoColor", void 0);
  35453. __decorate([
  35454. BABYLON.serializeAsColor3("reflectivity"),
  35455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35456. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  35457. __decorate([
  35458. BABYLON.serializeAsColor3("reflection"),
  35459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35460. ], PBRMaterial.prototype, "reflectionColor", void 0);
  35461. __decorate([
  35462. BABYLON.serializeAsColor3("emissive"),
  35463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35464. ], PBRMaterial.prototype, "emissiveColor", void 0);
  35465. __decorate([
  35466. BABYLON.serialize(),
  35467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35468. ], PBRMaterial.prototype, "microSurface", void 0);
  35469. __decorate([
  35470. BABYLON.serialize(),
  35471. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35472. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  35473. __decorate([
  35474. BABYLON.serialize(),
  35475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35476. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  35477. __decorate([
  35478. BABYLON.serialize(),
  35479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35480. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  35481. __decorate([
  35482. BABYLON.serialize(),
  35483. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35484. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  35485. __decorate([
  35486. BABYLON.serialize(),
  35487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35488. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  35489. __decorate([
  35490. BABYLON.serialize(),
  35491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35492. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  35493. __decorate([
  35494. BABYLON.serialize(),
  35495. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35496. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  35497. __decorate([
  35498. BABYLON.serialize(),
  35499. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35500. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  35501. __decorate([
  35502. BABYLON.serialize(),
  35503. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35504. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  35505. __decorate([
  35506. BABYLON.serialize(),
  35507. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35508. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  35509. __decorate([
  35510. BABYLON.serialize(),
  35511. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35512. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  35513. __decorate([
  35514. BABYLON.serialize(),
  35515. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35516. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  35517. __decorate([
  35518. BABYLON.serialize(),
  35519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35520. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  35521. __decorate([
  35522. BABYLON.serialize(),
  35523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35524. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  35525. __decorate([
  35526. BABYLON.serialize(),
  35527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35528. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  35529. __decorate([
  35530. BABYLON.serialize(),
  35531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35532. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  35533. __decorate([
  35534. BABYLON.serialize(),
  35535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35536. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  35537. __decorate([
  35538. BABYLON.serialize(),
  35539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35540. ], PBRMaterial.prototype, "useParallax", void 0);
  35541. __decorate([
  35542. BABYLON.serialize(),
  35543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35544. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  35545. __decorate([
  35546. BABYLON.serialize(),
  35547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35548. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  35549. __decorate([
  35550. BABYLON.serialize(),
  35551. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35552. ], PBRMaterial.prototype, "disableLighting", void 0);
  35553. __decorate([
  35554. BABYLON.serialize(),
  35555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35556. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  35557. __decorate([
  35558. BABYLON.serialize(),
  35559. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35560. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  35561. __decorate([
  35562. BABYLON.serialize(),
  35563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35564. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  35565. __decorate([
  35566. BABYLON.serialize(),
  35567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35568. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  35569. __decorate([
  35570. BABYLON.serialize(),
  35571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35572. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  35573. __decorate([
  35574. BABYLON.serialize(),
  35575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35576. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  35577. __decorate([
  35578. BABYLON.serialize(),
  35579. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35580. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  35581. __decorate([
  35582. BABYLON.serializeAsTexture(),
  35583. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35584. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  35585. __decorate([
  35586. BABYLON.serialize(),
  35587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35588. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  35589. return PBRMaterial;
  35590. }(BABYLON.PBRBaseMaterial));
  35591. BABYLON.PBRMaterial = PBRMaterial;
  35592. })(BABYLON || (BABYLON = {}));
  35593. //# sourceMappingURL=babylon.pbrMaterial.js.map
  35594. var BABYLON;
  35595. (function (BABYLON) {
  35596. /**
  35597. * The PBR material of BJS following the metal roughness convention.
  35598. *
  35599. * This fits to the PBR convention in the GLTF definition:
  35600. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  35601. */
  35602. var PBRMetallicRoughnessMaterial = (function (_super) {
  35603. __extends(PBRMetallicRoughnessMaterial, _super);
  35604. /**
  35605. * Instantiates a new PBRMetalRoughnessMaterial instance.
  35606. *
  35607. * @param name The material name
  35608. * @param scene The scene the material will be use in.
  35609. */
  35610. function PBRMetallicRoughnessMaterial(name, scene) {
  35611. var _this = _super.call(this, name, scene) || this;
  35612. _this._useRoughnessFromMetallicTextureAlpha = false;
  35613. _this._useRoughnessFromMetallicTextureGreen = true;
  35614. _this._useMetallnessFromMetallicTextureBlue = true;
  35615. return _this;
  35616. }
  35617. /**
  35618. * Return the currrent class name of the material.
  35619. */
  35620. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  35621. return "PBRMetallicRoughnessMaterial";
  35622. };
  35623. /**
  35624. * Return the active textures of the material.
  35625. */
  35626. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  35627. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35628. if (this.baseTexture) {
  35629. activeTextures.push(this.baseTexture);
  35630. }
  35631. if (this.metallicRoughnessTexture) {
  35632. activeTextures.push(this.metallicRoughnessTexture);
  35633. }
  35634. return activeTextures;
  35635. };
  35636. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  35637. if (_super.prototype.hasTexture.call(this, texture)) {
  35638. return true;
  35639. }
  35640. if (this.baseTexture === texture) {
  35641. return true;
  35642. }
  35643. if (this.metallicRoughnessTexture === texture) {
  35644. return true;
  35645. }
  35646. return false;
  35647. };
  35648. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  35649. var _this = this;
  35650. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  35651. clone.id = name;
  35652. clone.name = name;
  35653. return clone;
  35654. };
  35655. /**
  35656. * Serialize the material to a parsable JSON object.
  35657. */
  35658. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  35659. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  35660. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  35661. return serializationObject;
  35662. };
  35663. /**
  35664. * Parses a JSON object correponding to the serialize function.
  35665. */
  35666. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  35667. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  35668. };
  35669. __decorate([
  35670. BABYLON.serializeAsColor3(),
  35671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  35672. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  35673. __decorate([
  35674. BABYLON.serializeAsTexture(),
  35675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  35676. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  35677. __decorate([
  35678. BABYLON.serialize(),
  35679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35680. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  35681. __decorate([
  35682. BABYLON.serialize(),
  35683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35684. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  35685. __decorate([
  35686. BABYLON.serializeAsTexture(),
  35687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  35688. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  35689. return PBRMetallicRoughnessMaterial;
  35690. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  35691. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  35692. })(BABYLON || (BABYLON = {}));
  35693. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  35694. var BABYLON;
  35695. (function (BABYLON) {
  35696. /**
  35697. * The PBR material of BJS following the specular glossiness convention.
  35698. *
  35699. * This fits to the PBR convention in the GLTF definition:
  35700. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  35701. */
  35702. var PBRSpecularGlossinessMaterial = (function (_super) {
  35703. __extends(PBRSpecularGlossinessMaterial, _super);
  35704. /**
  35705. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  35706. *
  35707. * @param name The material name
  35708. * @param scene The scene the material will be use in.
  35709. */
  35710. function PBRSpecularGlossinessMaterial(name, scene) {
  35711. var _this = _super.call(this, name, scene) || this;
  35712. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  35713. return _this;
  35714. }
  35715. /**
  35716. * Return the currrent class name of the material.
  35717. */
  35718. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  35719. return "PBRSpecularGlossinessMaterial";
  35720. };
  35721. /**
  35722. * Return the active textures of the material.
  35723. */
  35724. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  35725. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35726. if (this.diffuseTexture) {
  35727. activeTextures.push(this.diffuseTexture);
  35728. }
  35729. if (this.specularGlossinessTexture) {
  35730. activeTextures.push(this.specularGlossinessTexture);
  35731. }
  35732. return activeTextures;
  35733. };
  35734. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  35735. if (_super.prototype.hasTexture.call(this, texture)) {
  35736. return true;
  35737. }
  35738. if (this.diffuseTexture === texture) {
  35739. return true;
  35740. }
  35741. if (this.specularGlossinessTexture === texture) {
  35742. return true;
  35743. }
  35744. return false;
  35745. };
  35746. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  35747. var _this = this;
  35748. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  35749. clone.id = name;
  35750. clone.name = name;
  35751. return clone;
  35752. };
  35753. /**
  35754. * Serialize the material to a parsable JSON object.
  35755. */
  35756. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  35757. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  35758. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  35759. return serializationObject;
  35760. };
  35761. /**
  35762. * Parses a JSON object correponding to the serialize function.
  35763. */
  35764. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  35765. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  35766. };
  35767. __decorate([
  35768. BABYLON.serializeAsColor3("diffuse"),
  35769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  35770. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  35771. __decorate([
  35772. BABYLON.serializeAsTexture(),
  35773. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  35774. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  35775. __decorate([
  35776. BABYLON.serializeAsColor3("specular"),
  35777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  35778. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  35779. __decorate([
  35780. BABYLON.serialize(),
  35781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  35782. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  35783. __decorate([
  35784. BABYLON.serializeAsTexture(),
  35785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  35786. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  35787. return PBRSpecularGlossinessMaterial;
  35788. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  35789. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  35790. })(BABYLON || (BABYLON = {}));
  35791. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  35792. var BABYLON;
  35793. (function (BABYLON) {
  35794. BABYLON.CameraInputTypes = {};
  35795. var CameraInputsManager = (function () {
  35796. function CameraInputsManager(camera) {
  35797. this.attached = {};
  35798. this.camera = camera;
  35799. this.checkInputs = function () { };
  35800. }
  35801. CameraInputsManager.prototype.add = function (input) {
  35802. var type = input.getSimpleName();
  35803. if (this.attached[type]) {
  35804. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  35805. return;
  35806. }
  35807. this.attached[type] = input;
  35808. input.camera = this.camera;
  35809. //for checkInputs, we are dynamically creating a function
  35810. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  35811. if (input.checkInputs) {
  35812. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  35813. }
  35814. if (this.attachedElement) {
  35815. input.attachControl(this.attachedElement);
  35816. }
  35817. };
  35818. CameraInputsManager.prototype.remove = function (inputToRemove) {
  35819. for (var cam in this.attached) {
  35820. var input = this.attached[cam];
  35821. if (input === inputToRemove) {
  35822. input.detachControl(this.attachedElement);
  35823. input.camera = null;
  35824. delete this.attached[cam];
  35825. this.rebuildInputCheck();
  35826. }
  35827. }
  35828. };
  35829. CameraInputsManager.prototype.removeByType = function (inputType) {
  35830. for (var cam in this.attached) {
  35831. var input = this.attached[cam];
  35832. if (input.getClassName() === inputType) {
  35833. input.detachControl(this.attachedElement);
  35834. input.camera = null;
  35835. delete this.attached[cam];
  35836. this.rebuildInputCheck();
  35837. }
  35838. }
  35839. };
  35840. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  35841. var current = this.checkInputs;
  35842. return function () {
  35843. current();
  35844. fn();
  35845. };
  35846. };
  35847. CameraInputsManager.prototype.attachInput = function (input) {
  35848. input.attachControl(this.attachedElement, this.noPreventDefault);
  35849. };
  35850. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  35851. if (this.attachedElement) {
  35852. return;
  35853. }
  35854. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  35855. this.attachedElement = element;
  35856. this.noPreventDefault = noPreventDefault;
  35857. for (var cam in this.attached) {
  35858. this.attached[cam].attachControl(element, noPreventDefault);
  35859. }
  35860. };
  35861. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  35862. if (disconnect === void 0) { disconnect = false; }
  35863. if (this.attachedElement !== element) {
  35864. return;
  35865. }
  35866. for (var cam in this.attached) {
  35867. this.attached[cam].detachControl(element);
  35868. if (disconnect) {
  35869. this.attached[cam].camera = null;
  35870. }
  35871. }
  35872. this.attachedElement = null;
  35873. };
  35874. CameraInputsManager.prototype.rebuildInputCheck = function () {
  35875. this.checkInputs = function () { };
  35876. for (var cam in this.attached) {
  35877. var input = this.attached[cam];
  35878. if (input.checkInputs) {
  35879. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  35880. }
  35881. }
  35882. };
  35883. CameraInputsManager.prototype.clear = function () {
  35884. if (this.attachedElement) {
  35885. this.detachElement(this.attachedElement, true);
  35886. }
  35887. this.attached = {};
  35888. this.attachedElement = null;
  35889. this.checkInputs = function () { };
  35890. };
  35891. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  35892. var inputs = {};
  35893. for (var cam in this.attached) {
  35894. var input = this.attached[cam];
  35895. var res = BABYLON.SerializationHelper.Serialize(input);
  35896. inputs[input.getClassName()] = res;
  35897. }
  35898. serializedCamera.inputsmgr = inputs;
  35899. };
  35900. CameraInputsManager.prototype.parse = function (parsedCamera) {
  35901. var parsedInputs = parsedCamera.inputsmgr;
  35902. if (parsedInputs) {
  35903. this.clear();
  35904. for (var n in parsedInputs) {
  35905. var construct = BABYLON.CameraInputTypes[n];
  35906. if (construct) {
  35907. var parsedinput = parsedInputs[n];
  35908. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  35909. this.add(input);
  35910. }
  35911. }
  35912. }
  35913. else {
  35914. //2016-03-08 this part is for managing backward compatibility
  35915. for (var n in this.attached) {
  35916. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  35917. if (construct) {
  35918. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  35919. this.remove(this.attached[n]);
  35920. this.add(input);
  35921. }
  35922. }
  35923. }
  35924. };
  35925. return CameraInputsManager;
  35926. }());
  35927. BABYLON.CameraInputsManager = CameraInputsManager;
  35928. })(BABYLON || (BABYLON = {}));
  35929. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  35930. var BABYLON;
  35931. (function (BABYLON) {
  35932. var FreeCameraMouseInput = (function () {
  35933. function FreeCameraMouseInput(touchEnabled) {
  35934. if (touchEnabled === void 0) { touchEnabled = true; }
  35935. this.touchEnabled = touchEnabled;
  35936. this.buttons = [0, 1, 2];
  35937. this.angularSensibility = 2000.0;
  35938. }
  35939. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  35940. var _this = this;
  35941. var engine = this.camera.getEngine();
  35942. if (!this._pointerInput) {
  35943. this._pointerInput = function (p, s) {
  35944. var evt = p.event;
  35945. if (engine.isInVRExclusivePointerMode) {
  35946. return;
  35947. }
  35948. if (!_this.touchEnabled && evt.pointerType === "touch") {
  35949. return;
  35950. }
  35951. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  35952. return;
  35953. }
  35954. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  35955. try {
  35956. evt.srcElement.setPointerCapture(evt.pointerId);
  35957. }
  35958. catch (e) {
  35959. //Nothing to do with the error. Execution will continue.
  35960. }
  35961. _this.previousPosition = {
  35962. x: evt.clientX,
  35963. y: evt.clientY
  35964. };
  35965. if (!noPreventDefault) {
  35966. evt.preventDefault();
  35967. element.focus();
  35968. }
  35969. }
  35970. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  35971. try {
  35972. evt.srcElement.releasePointerCapture(evt.pointerId);
  35973. }
  35974. catch (e) {
  35975. //Nothing to do with the error.
  35976. }
  35977. _this.previousPosition = null;
  35978. if (!noPreventDefault) {
  35979. evt.preventDefault();
  35980. }
  35981. }
  35982. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  35983. if (!_this.previousPosition || engine.isPointerLock) {
  35984. return;
  35985. }
  35986. var offsetX = evt.clientX - _this.previousPosition.x;
  35987. var offsetY = evt.clientY - _this.previousPosition.y;
  35988. if (_this.camera.getScene().useRightHandedSystem) {
  35989. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  35990. }
  35991. else {
  35992. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  35993. }
  35994. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  35995. _this.previousPosition = {
  35996. x: evt.clientX,
  35997. y: evt.clientY
  35998. };
  35999. if (!noPreventDefault) {
  36000. evt.preventDefault();
  36001. }
  36002. }
  36003. };
  36004. }
  36005. this._onMouseMove = function (evt) {
  36006. if (!engine.isPointerLock) {
  36007. return;
  36008. }
  36009. if (engine.isInVRExclusivePointerMode) {
  36010. return;
  36011. }
  36012. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  36013. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  36014. if (_this.camera.getScene().useRightHandedSystem) {
  36015. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  36016. }
  36017. else {
  36018. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  36019. }
  36020. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  36021. _this.previousPosition = null;
  36022. if (!noPreventDefault) {
  36023. evt.preventDefault();
  36024. }
  36025. };
  36026. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  36027. element.addEventListener("mousemove", this._onMouseMove, false);
  36028. };
  36029. FreeCameraMouseInput.prototype.detachControl = function (element) {
  36030. if (this._observer && element) {
  36031. this.camera.getScene().onPointerObservable.remove(this._observer);
  36032. element.removeEventListener("mousemove", this._onMouseMove);
  36033. this._observer = null;
  36034. this._onMouseMove = null;
  36035. this.previousPosition = null;
  36036. }
  36037. };
  36038. FreeCameraMouseInput.prototype.getClassName = function () {
  36039. return "FreeCameraMouseInput";
  36040. };
  36041. FreeCameraMouseInput.prototype.getSimpleName = function () {
  36042. return "mouse";
  36043. };
  36044. __decorate([
  36045. BABYLON.serialize()
  36046. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  36047. __decorate([
  36048. BABYLON.serialize()
  36049. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  36050. return FreeCameraMouseInput;
  36051. }());
  36052. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  36053. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  36054. })(BABYLON || (BABYLON = {}));
  36055. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  36056. var BABYLON;
  36057. (function (BABYLON) {
  36058. var FreeCameraKeyboardMoveInput = (function () {
  36059. function FreeCameraKeyboardMoveInput() {
  36060. this._keys = new Array();
  36061. this.keysUp = [38];
  36062. this.keysDown = [40];
  36063. this.keysLeft = [37];
  36064. this.keysRight = [39];
  36065. }
  36066. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  36067. var _this = this;
  36068. if (this._onCanvasBlurObserver) {
  36069. return;
  36070. }
  36071. this._scene = this.camera.getScene();
  36072. this._engine = this._scene.getEngine();
  36073. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  36074. _this._keys = [];
  36075. });
  36076. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  36077. var evt = info.event;
  36078. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  36079. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  36080. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  36081. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  36082. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  36083. var index = _this._keys.indexOf(evt.keyCode);
  36084. if (index === -1) {
  36085. _this._keys.push(evt.keyCode);
  36086. }
  36087. if (!noPreventDefault) {
  36088. evt.preventDefault();
  36089. }
  36090. }
  36091. }
  36092. else {
  36093. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  36094. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  36095. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  36096. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  36097. var index = _this._keys.indexOf(evt.keyCode);
  36098. if (index >= 0) {
  36099. _this._keys.splice(index, 1);
  36100. }
  36101. if (!noPreventDefault) {
  36102. evt.preventDefault();
  36103. }
  36104. }
  36105. }
  36106. });
  36107. };
  36108. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  36109. if (this._scene) {
  36110. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  36111. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  36112. this._onKeyboardObserver = null;
  36113. this._onCanvasBlurObserver = null;
  36114. }
  36115. this._keys = [];
  36116. };
  36117. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  36118. if (this._onKeyboardObserver) {
  36119. var camera = this.camera;
  36120. // Keyboard
  36121. for (var index = 0; index < this._keys.length; index++) {
  36122. var keyCode = this._keys[index];
  36123. var speed = camera._computeLocalCameraSpeed();
  36124. if (this.keysLeft.indexOf(keyCode) !== -1) {
  36125. camera._localDirection.copyFromFloats(-speed, 0, 0);
  36126. }
  36127. else if (this.keysUp.indexOf(keyCode) !== -1) {
  36128. camera._localDirection.copyFromFloats(0, 0, speed);
  36129. }
  36130. else if (this.keysRight.indexOf(keyCode) !== -1) {
  36131. camera._localDirection.copyFromFloats(speed, 0, 0);
  36132. }
  36133. else if (this.keysDown.indexOf(keyCode) !== -1) {
  36134. camera._localDirection.copyFromFloats(0, 0, -speed);
  36135. }
  36136. if (camera.getScene().useRightHandedSystem) {
  36137. camera._localDirection.z *= -1;
  36138. }
  36139. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  36140. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  36141. camera.cameraDirection.addInPlace(camera._transformedDirection);
  36142. }
  36143. }
  36144. };
  36145. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  36146. return "FreeCameraKeyboardMoveInput";
  36147. };
  36148. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  36149. this._keys = [];
  36150. };
  36151. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  36152. return "keyboard";
  36153. };
  36154. __decorate([
  36155. BABYLON.serialize()
  36156. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  36157. __decorate([
  36158. BABYLON.serialize()
  36159. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  36160. __decorate([
  36161. BABYLON.serialize()
  36162. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  36163. __decorate([
  36164. BABYLON.serialize()
  36165. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  36166. return FreeCameraKeyboardMoveInput;
  36167. }());
  36168. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  36169. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  36170. })(BABYLON || (BABYLON = {}));
  36171. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  36172. var BABYLON;
  36173. (function (BABYLON) {
  36174. var FreeCameraInputsManager = (function (_super) {
  36175. __extends(FreeCameraInputsManager, _super);
  36176. function FreeCameraInputsManager(camera) {
  36177. return _super.call(this, camera) || this;
  36178. }
  36179. FreeCameraInputsManager.prototype.addKeyboard = function () {
  36180. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  36181. return this;
  36182. };
  36183. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  36184. if (touchEnabled === void 0) { touchEnabled = true; }
  36185. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  36186. return this;
  36187. };
  36188. FreeCameraInputsManager.prototype.addGamepad = function () {
  36189. this.add(new BABYLON.FreeCameraGamepadInput());
  36190. return this;
  36191. };
  36192. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  36193. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  36194. return this;
  36195. };
  36196. FreeCameraInputsManager.prototype.addTouch = function () {
  36197. this.add(new BABYLON.FreeCameraTouchInput());
  36198. return this;
  36199. };
  36200. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  36201. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  36202. return this;
  36203. };
  36204. return FreeCameraInputsManager;
  36205. }(BABYLON.CameraInputsManager));
  36206. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  36207. })(BABYLON || (BABYLON = {}));
  36208. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  36209. /// <reference path="babylon.camera.ts" />
  36210. var BABYLON;
  36211. (function (BABYLON) {
  36212. var TargetCamera = (function (_super) {
  36213. __extends(TargetCamera, _super);
  36214. function TargetCamera(name, position, scene) {
  36215. var _this = _super.call(this, name, position, scene) || this;
  36216. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  36217. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  36218. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  36219. _this.speed = 2.0;
  36220. _this.noRotationConstraint = false;
  36221. _this.lockedTarget = null;
  36222. _this._currentTarget = BABYLON.Vector3.Zero();
  36223. _this._viewMatrix = BABYLON.Matrix.Zero();
  36224. _this._camMatrix = BABYLON.Matrix.Zero();
  36225. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  36226. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  36227. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  36228. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  36229. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  36230. _this._lookAtTemp = BABYLON.Matrix.Zero();
  36231. _this._tempMatrix = BABYLON.Matrix.Zero();
  36232. return _this;
  36233. }
  36234. TargetCamera.prototype.getFrontPosition = function (distance) {
  36235. var direction = this.getTarget().subtract(this.position);
  36236. direction.normalize();
  36237. direction.scaleInPlace(distance);
  36238. return this.globalPosition.add(direction);
  36239. };
  36240. TargetCamera.prototype._getLockedTargetPosition = function () {
  36241. if (!this.lockedTarget) {
  36242. return null;
  36243. }
  36244. if (this.lockedTarget.absolutePosition) {
  36245. this.lockedTarget.computeWorldMatrix();
  36246. }
  36247. return this.lockedTarget.absolutePosition || this.lockedTarget;
  36248. };
  36249. TargetCamera.prototype.storeState = function () {
  36250. this._storedPosition = this.position.clone();
  36251. this._storedRotation = this.rotation.clone();
  36252. if (this.rotationQuaternion) {
  36253. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  36254. }
  36255. return _super.prototype.storeState.call(this);
  36256. };
  36257. /**
  36258. * Restored camera state. You must call storeState() first
  36259. */
  36260. TargetCamera.prototype._restoreStateValues = function () {
  36261. if (!_super.prototype._restoreStateValues.call(this)) {
  36262. return false;
  36263. }
  36264. this.position = this._storedPosition.clone();
  36265. this.rotation = this._storedRotation.clone();
  36266. if (this.rotationQuaternion) {
  36267. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  36268. }
  36269. this.cameraDirection.copyFromFloats(0, 0, 0);
  36270. this.cameraRotation.copyFromFloats(0, 0);
  36271. return true;
  36272. };
  36273. // Cache
  36274. TargetCamera.prototype._initCache = function () {
  36275. _super.prototype._initCache.call(this);
  36276. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  36277. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  36278. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  36279. };
  36280. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  36281. if (!ignoreParentClass) {
  36282. _super.prototype._updateCache.call(this);
  36283. }
  36284. var lockedTargetPosition = this._getLockedTargetPosition();
  36285. if (!lockedTargetPosition) {
  36286. this._cache.lockedTarget = null;
  36287. }
  36288. else {
  36289. if (!this._cache.lockedTarget) {
  36290. this._cache.lockedTarget = lockedTargetPosition.clone();
  36291. }
  36292. else {
  36293. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  36294. }
  36295. }
  36296. this._cache.rotation.copyFrom(this.rotation);
  36297. if (this.rotationQuaternion)
  36298. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  36299. };
  36300. // Synchronized
  36301. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  36302. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  36303. return false;
  36304. }
  36305. var lockedTargetPosition = this._getLockedTargetPosition();
  36306. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  36307. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  36308. };
  36309. // Methods
  36310. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  36311. var engine = this.getEngine();
  36312. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  36313. };
  36314. // Target
  36315. TargetCamera.prototype.setTarget = function (target) {
  36316. this.upVector.normalize();
  36317. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  36318. this._camMatrix.invert();
  36319. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  36320. var vDir = target.subtract(this.position);
  36321. if (vDir.x >= 0.0) {
  36322. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  36323. }
  36324. else {
  36325. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  36326. }
  36327. this.rotation.z = 0;
  36328. if (isNaN(this.rotation.x)) {
  36329. this.rotation.x = 0;
  36330. }
  36331. if (isNaN(this.rotation.y)) {
  36332. this.rotation.y = 0;
  36333. }
  36334. if (isNaN(this.rotation.z)) {
  36335. this.rotation.z = 0;
  36336. }
  36337. if (this.rotationQuaternion) {
  36338. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  36339. }
  36340. };
  36341. /**
  36342. * Return the current target position of the camera. This value is expressed in local space.
  36343. */
  36344. TargetCamera.prototype.getTarget = function () {
  36345. return this._currentTarget;
  36346. };
  36347. TargetCamera.prototype._decideIfNeedsToMove = function () {
  36348. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  36349. };
  36350. TargetCamera.prototype._updatePosition = function () {
  36351. if (this.parent) {
  36352. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  36353. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  36354. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  36355. return;
  36356. }
  36357. this.position.addInPlace(this.cameraDirection);
  36358. };
  36359. TargetCamera.prototype._checkInputs = function () {
  36360. var needToMove = this._decideIfNeedsToMove();
  36361. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  36362. // Move
  36363. if (needToMove) {
  36364. this._updatePosition();
  36365. }
  36366. // Rotate
  36367. if (needToRotate) {
  36368. this.rotation.x += this.cameraRotation.x;
  36369. this.rotation.y += this.cameraRotation.y;
  36370. //rotate, if quaternion is set and rotation was used
  36371. if (this.rotationQuaternion) {
  36372. var len = this.rotation.lengthSquared();
  36373. if (len) {
  36374. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  36375. }
  36376. }
  36377. if (!this.noRotationConstraint) {
  36378. var limit = (Math.PI / 2) * 0.95;
  36379. if (this.rotation.x > limit)
  36380. this.rotation.x = limit;
  36381. if (this.rotation.x < -limit)
  36382. this.rotation.x = -limit;
  36383. }
  36384. }
  36385. // Inertia
  36386. if (needToMove) {
  36387. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  36388. this.cameraDirection.x = 0;
  36389. }
  36390. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  36391. this.cameraDirection.y = 0;
  36392. }
  36393. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  36394. this.cameraDirection.z = 0;
  36395. }
  36396. this.cameraDirection.scaleInPlace(this.inertia);
  36397. }
  36398. if (needToRotate) {
  36399. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  36400. this.cameraRotation.x = 0;
  36401. }
  36402. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  36403. this.cameraRotation.y = 0;
  36404. }
  36405. this.cameraRotation.scaleInPlace(this.inertia);
  36406. }
  36407. _super.prototype._checkInputs.call(this);
  36408. };
  36409. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  36410. if (this.rotationQuaternion) {
  36411. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  36412. }
  36413. else {
  36414. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  36415. }
  36416. //update the up vector!
  36417. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  36418. };
  36419. TargetCamera.prototype._getViewMatrix = function () {
  36420. if (!this.lockedTarget) {
  36421. // Compute
  36422. this._updateCameraRotationMatrix();
  36423. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  36424. // Computing target and final matrix
  36425. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  36426. }
  36427. else {
  36428. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  36429. }
  36430. if (this.getScene().useRightHandedSystem) {
  36431. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  36432. }
  36433. else {
  36434. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  36435. }
  36436. return this._viewMatrix;
  36437. };
  36438. /**
  36439. * @override
  36440. * Override Camera.createRigCamera
  36441. */
  36442. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  36443. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  36444. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  36445. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  36446. if (!this.rotationQuaternion) {
  36447. this.rotationQuaternion = new BABYLON.Quaternion();
  36448. }
  36449. rigCamera._cameraRigParams = {};
  36450. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  36451. }
  36452. return rigCamera;
  36453. }
  36454. return null;
  36455. };
  36456. /**
  36457. * @override
  36458. * Override Camera._updateRigCameras
  36459. */
  36460. TargetCamera.prototype._updateRigCameras = function () {
  36461. var camLeft = this._rigCameras[0];
  36462. var camRight = this._rigCameras[1];
  36463. switch (this.cameraRigMode) {
  36464. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  36465. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  36466. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  36467. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  36468. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  36469. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  36470. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  36471. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  36472. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  36473. camLeft.setTarget(this.getTarget());
  36474. camRight.setTarget(this.getTarget());
  36475. break;
  36476. case BABYLON.Camera.RIG_MODE_VR:
  36477. if (camLeft.rotationQuaternion) {
  36478. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  36479. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  36480. }
  36481. else {
  36482. camLeft.rotation.copyFrom(this.rotation);
  36483. camRight.rotation.copyFrom(this.rotation);
  36484. }
  36485. camLeft.position.copyFrom(this.position);
  36486. camRight.position.copyFrom(this.position);
  36487. break;
  36488. }
  36489. _super.prototype._updateRigCameras.call(this);
  36490. };
  36491. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  36492. if (!this._rigCamTransformMatrix) {
  36493. this._rigCamTransformMatrix = new BABYLON.Matrix();
  36494. }
  36495. var target = this.getTarget();
  36496. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  36497. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  36498. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  36499. };
  36500. TargetCamera.prototype.getClassName = function () {
  36501. return "TargetCamera";
  36502. };
  36503. __decorate([
  36504. BABYLON.serializeAsVector3()
  36505. ], TargetCamera.prototype, "rotation", void 0);
  36506. __decorate([
  36507. BABYLON.serialize()
  36508. ], TargetCamera.prototype, "speed", void 0);
  36509. __decorate([
  36510. BABYLON.serializeAsMeshReference("lockedTargetId")
  36511. ], TargetCamera.prototype, "lockedTarget", void 0);
  36512. return TargetCamera;
  36513. }(BABYLON.Camera));
  36514. BABYLON.TargetCamera = TargetCamera;
  36515. })(BABYLON || (BABYLON = {}));
  36516. //# sourceMappingURL=babylon.targetCamera.js.map
  36517. var BABYLON;
  36518. (function (BABYLON) {
  36519. var FreeCamera = (function (_super) {
  36520. __extends(FreeCamera, _super);
  36521. function FreeCamera(name, position, scene) {
  36522. var _this = _super.call(this, name, position, scene) || this;
  36523. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  36524. _this.checkCollisions = false;
  36525. _this.applyGravity = false;
  36526. _this._needMoveForGravity = false;
  36527. _this._oldPosition = BABYLON.Vector3.Zero();
  36528. _this._diffPosition = BABYLON.Vector3.Zero();
  36529. _this._newPosition = BABYLON.Vector3.Zero();
  36530. // Collisions
  36531. _this._collisionMask = -1;
  36532. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  36533. if (collidedMesh === void 0) { collidedMesh = null; }
  36534. //TODO move this to the collision coordinator!
  36535. if (_this.getScene().workerCollisions)
  36536. newPosition.multiplyInPlace(_this._collider.radius);
  36537. var updatePosition = function (newPos) {
  36538. _this._newPosition.copyFrom(newPos);
  36539. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  36540. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  36541. _this.position.addInPlace(_this._diffPosition);
  36542. if (_this.onCollide && collidedMesh) {
  36543. _this.onCollide(collidedMesh);
  36544. }
  36545. }
  36546. };
  36547. updatePosition(newPosition);
  36548. };
  36549. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  36550. _this.inputs.addKeyboard().addMouse();
  36551. return _this;
  36552. }
  36553. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  36554. //-- begin properties for backward compatibility for inputs
  36555. get: function () {
  36556. var mouse = this.inputs.attached["mouse"];
  36557. if (mouse)
  36558. return mouse.angularSensibility;
  36559. return null;
  36560. },
  36561. set: function (value) {
  36562. var mouse = this.inputs.attached["mouse"];
  36563. if (mouse)
  36564. mouse.angularSensibility = value;
  36565. },
  36566. enumerable: true,
  36567. configurable: true
  36568. });
  36569. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  36570. get: function () {
  36571. var keyboard = this.inputs.attached["keyboard"];
  36572. if (keyboard)
  36573. return keyboard.keysUp;
  36574. return null;
  36575. },
  36576. set: function (value) {
  36577. var keyboard = this.inputs.attached["keyboard"];
  36578. if (keyboard)
  36579. keyboard.keysUp = value;
  36580. },
  36581. enumerable: true,
  36582. configurable: true
  36583. });
  36584. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  36585. get: function () {
  36586. var keyboard = this.inputs.attached["keyboard"];
  36587. if (keyboard)
  36588. return keyboard.keysDown;
  36589. return null;
  36590. },
  36591. set: function (value) {
  36592. var keyboard = this.inputs.attached["keyboard"];
  36593. if (keyboard)
  36594. keyboard.keysDown = value;
  36595. },
  36596. enumerable: true,
  36597. configurable: true
  36598. });
  36599. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  36600. get: function () {
  36601. var keyboard = this.inputs.attached["keyboard"];
  36602. if (keyboard)
  36603. return keyboard.keysLeft;
  36604. return null;
  36605. },
  36606. set: function (value) {
  36607. var keyboard = this.inputs.attached["keyboard"];
  36608. if (keyboard)
  36609. keyboard.keysLeft = value;
  36610. },
  36611. enumerable: true,
  36612. configurable: true
  36613. });
  36614. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  36615. get: function () {
  36616. var keyboard = this.inputs.attached["keyboard"];
  36617. if (keyboard)
  36618. return keyboard.keysRight;
  36619. return null;
  36620. },
  36621. set: function (value) {
  36622. var keyboard = this.inputs.attached["keyboard"];
  36623. if (keyboard)
  36624. keyboard.keysRight = value;
  36625. },
  36626. enumerable: true,
  36627. configurable: true
  36628. });
  36629. // Controls
  36630. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  36631. this.inputs.attachElement(element, noPreventDefault);
  36632. };
  36633. FreeCamera.prototype.detachControl = function (element) {
  36634. this.inputs.detachElement(element);
  36635. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  36636. this.cameraRotation = new BABYLON.Vector2(0, 0);
  36637. };
  36638. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  36639. get: function () {
  36640. return this._collisionMask;
  36641. },
  36642. set: function (mask) {
  36643. this._collisionMask = !isNaN(mask) ? mask : -1;
  36644. },
  36645. enumerable: true,
  36646. configurable: true
  36647. });
  36648. FreeCamera.prototype._collideWithWorld = function (displacement) {
  36649. var globalPosition;
  36650. if (this.parent) {
  36651. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  36652. }
  36653. else {
  36654. globalPosition = this.position;
  36655. }
  36656. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  36657. if (!this._collider) {
  36658. this._collider = new BABYLON.Collider();
  36659. }
  36660. this._collider.radius = this.ellipsoid;
  36661. this._collider.collisionMask = this._collisionMask;
  36662. //no need for clone, as long as gravity is not on.
  36663. var actualDisplacement = displacement;
  36664. //add gravity to the direction to prevent the dual-collision checking
  36665. if (this.applyGravity) {
  36666. //this prevents mending with cameraDirection, a global variable of the free camera class.
  36667. actualDisplacement = displacement.add(this.getScene().gravity);
  36668. }
  36669. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  36670. };
  36671. FreeCamera.prototype._checkInputs = function () {
  36672. if (!this._localDirection) {
  36673. this._localDirection = BABYLON.Vector3.Zero();
  36674. this._transformedDirection = BABYLON.Vector3.Zero();
  36675. }
  36676. this.inputs.checkInputs();
  36677. _super.prototype._checkInputs.call(this);
  36678. };
  36679. FreeCamera.prototype._decideIfNeedsToMove = function () {
  36680. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  36681. };
  36682. FreeCamera.prototype._updatePosition = function () {
  36683. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  36684. this._collideWithWorld(this.cameraDirection);
  36685. }
  36686. else {
  36687. _super.prototype._updatePosition.call(this);
  36688. }
  36689. };
  36690. FreeCamera.prototype.dispose = function () {
  36691. this.inputs.clear();
  36692. _super.prototype.dispose.call(this);
  36693. };
  36694. FreeCamera.prototype.getClassName = function () {
  36695. return "FreeCamera";
  36696. };
  36697. __decorate([
  36698. BABYLON.serializeAsVector3()
  36699. ], FreeCamera.prototype, "ellipsoid", void 0);
  36700. __decorate([
  36701. BABYLON.serialize()
  36702. ], FreeCamera.prototype, "checkCollisions", void 0);
  36703. __decorate([
  36704. BABYLON.serialize()
  36705. ], FreeCamera.prototype, "applyGravity", void 0);
  36706. return FreeCamera;
  36707. }(BABYLON.TargetCamera));
  36708. BABYLON.FreeCamera = FreeCamera;
  36709. })(BABYLON || (BABYLON = {}));
  36710. //# sourceMappingURL=babylon.freeCamera.js.map
  36711. var BABYLON;
  36712. (function (BABYLON) {
  36713. var ArcRotateCameraKeyboardMoveInput = (function () {
  36714. function ArcRotateCameraKeyboardMoveInput() {
  36715. this._keys = new Array();
  36716. this.keysUp = [38];
  36717. this.keysDown = [40];
  36718. this.keysLeft = [37];
  36719. this.keysRight = [39];
  36720. this.keysReset = [220];
  36721. this.panningSensibility = 50.0;
  36722. this.zoomingSensibility = 25.0;
  36723. this.useAltToZoom = true;
  36724. }
  36725. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  36726. var _this = this;
  36727. if (this._onCanvasBlurObserver) {
  36728. return;
  36729. }
  36730. this._scene = this.camera.getScene();
  36731. this._engine = this._scene.getEngine();
  36732. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  36733. _this._keys = [];
  36734. });
  36735. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  36736. var evt = info.event;
  36737. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  36738. _this._ctrlPressed = evt.ctrlKey;
  36739. _this._altPressed = evt.altKey;
  36740. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  36741. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  36742. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  36743. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  36744. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  36745. var index = _this._keys.indexOf(evt.keyCode);
  36746. if (index === -1) {
  36747. _this._keys.push(evt.keyCode);
  36748. }
  36749. if (evt.preventDefault) {
  36750. if (!noPreventDefault) {
  36751. evt.preventDefault();
  36752. }
  36753. }
  36754. }
  36755. }
  36756. else {
  36757. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  36758. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  36759. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  36760. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  36761. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  36762. var index = _this._keys.indexOf(evt.keyCode);
  36763. if (index >= 0) {
  36764. _this._keys.splice(index, 1);
  36765. }
  36766. if (evt.preventDefault) {
  36767. if (!noPreventDefault) {
  36768. evt.preventDefault();
  36769. }
  36770. }
  36771. }
  36772. }
  36773. });
  36774. };
  36775. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  36776. if (this._scene) {
  36777. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  36778. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  36779. this._onKeyboardObserver = null;
  36780. this._onCanvasBlurObserver = null;
  36781. }
  36782. this._keys = [];
  36783. };
  36784. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  36785. if (this._onKeyboardObserver) {
  36786. var camera = this.camera;
  36787. for (var index = 0; index < this._keys.length; index++) {
  36788. var keyCode = this._keys[index];
  36789. if (this.keysLeft.indexOf(keyCode) !== -1) {
  36790. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  36791. camera.inertialPanningX -= 1 / this.panningSensibility;
  36792. }
  36793. else {
  36794. camera.inertialAlphaOffset -= 0.01;
  36795. }
  36796. }
  36797. else if (this.keysUp.indexOf(keyCode) !== -1) {
  36798. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  36799. camera.inertialPanningY += 1 / this.panningSensibility;
  36800. }
  36801. else if (this._altPressed && this.useAltToZoom) {
  36802. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  36803. }
  36804. else {
  36805. camera.inertialBetaOffset -= 0.01;
  36806. }
  36807. }
  36808. else if (this.keysRight.indexOf(keyCode) !== -1) {
  36809. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  36810. camera.inertialPanningX += 1 / this.panningSensibility;
  36811. }
  36812. else {
  36813. camera.inertialAlphaOffset += 0.01;
  36814. }
  36815. }
  36816. else if (this.keysDown.indexOf(keyCode) !== -1) {
  36817. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  36818. camera.inertialPanningY -= 1 / this.panningSensibility;
  36819. }
  36820. else if (this._altPressed && this.useAltToZoom) {
  36821. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  36822. }
  36823. else {
  36824. camera.inertialBetaOffset += 0.01;
  36825. }
  36826. }
  36827. else if (this.keysReset.indexOf(keyCode) !== -1) {
  36828. camera.restoreState();
  36829. }
  36830. }
  36831. }
  36832. };
  36833. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  36834. return "ArcRotateCameraKeyboardMoveInput";
  36835. };
  36836. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  36837. return "keyboard";
  36838. };
  36839. __decorate([
  36840. BABYLON.serialize()
  36841. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  36842. __decorate([
  36843. BABYLON.serialize()
  36844. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  36845. __decorate([
  36846. BABYLON.serialize()
  36847. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  36848. __decorate([
  36849. BABYLON.serialize()
  36850. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  36851. __decorate([
  36852. BABYLON.serialize()
  36853. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  36854. __decorate([
  36855. BABYLON.serialize()
  36856. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  36857. __decorate([
  36858. BABYLON.serialize()
  36859. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  36860. __decorate([
  36861. BABYLON.serialize()
  36862. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  36863. return ArcRotateCameraKeyboardMoveInput;
  36864. }());
  36865. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  36866. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  36867. })(BABYLON || (BABYLON = {}));
  36868. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  36869. var BABYLON;
  36870. (function (BABYLON) {
  36871. var ArcRotateCameraMouseWheelInput = (function () {
  36872. function ArcRotateCameraMouseWheelInput() {
  36873. this.wheelPrecision = 3.0;
  36874. /**
  36875. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  36876. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  36877. */
  36878. this.wheelDeltaPercentage = 0;
  36879. }
  36880. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  36881. var _this = this;
  36882. this._wheel = function (p, s) {
  36883. //sanity check - this should be a PointerWheel event.
  36884. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  36885. return;
  36886. var event = p.event;
  36887. var delta = 0;
  36888. if (event.wheelDelta) {
  36889. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  36890. }
  36891. else if (event.detail) {
  36892. delta = -event.detail / _this.wheelPrecision;
  36893. }
  36894. if (delta)
  36895. _this.camera.inertialRadiusOffset += delta;
  36896. if (event.preventDefault) {
  36897. if (!noPreventDefault) {
  36898. event.preventDefault();
  36899. }
  36900. }
  36901. };
  36902. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  36903. };
  36904. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  36905. if (this._observer && element) {
  36906. this.camera.getScene().onPointerObservable.remove(this._observer);
  36907. this._observer = null;
  36908. this._wheel = null;
  36909. }
  36910. };
  36911. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  36912. return "ArcRotateCameraMouseWheelInput";
  36913. };
  36914. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  36915. return "mousewheel";
  36916. };
  36917. __decorate([
  36918. BABYLON.serialize()
  36919. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  36920. __decorate([
  36921. BABYLON.serialize()
  36922. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  36923. return ArcRotateCameraMouseWheelInput;
  36924. }());
  36925. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  36926. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  36927. })(BABYLON || (BABYLON = {}));
  36928. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  36929. var BABYLON;
  36930. (function (BABYLON) {
  36931. var ArcRotateCameraPointersInput = (function () {
  36932. function ArcRotateCameraPointersInput() {
  36933. this.buttons = [0, 1, 2];
  36934. this.angularSensibilityX = 1000.0;
  36935. this.angularSensibilityY = 1000.0;
  36936. this.pinchPrecision = 12.0;
  36937. /**
  36938. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  36939. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  36940. */
  36941. this.pinchDeltaPercentage = 0;
  36942. this.panningSensibility = 1000.0;
  36943. this.multiTouchPanning = true;
  36944. this.multiTouchPanAndZoom = true;
  36945. this._isPanClick = false;
  36946. this.pinchInwards = true;
  36947. }
  36948. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  36949. var _this = this;
  36950. var engine = this.camera.getEngine();
  36951. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  36952. var pointA, pointB;
  36953. var previousPinchSquaredDistance = 0;
  36954. var initialDistance = 0;
  36955. var twoFingerActivityCount = 0;
  36956. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  36957. this._pointerInput = function (p, s) {
  36958. var evt = p.event;
  36959. if (engine.isInVRExclusivePointerMode) {
  36960. return;
  36961. }
  36962. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  36963. return;
  36964. }
  36965. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  36966. try {
  36967. evt.srcElement.setPointerCapture(evt.pointerId);
  36968. }
  36969. catch (e) {
  36970. //Nothing to do with the error. Execution will continue.
  36971. }
  36972. // Manage panning with pan button click
  36973. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  36974. // manage pointers
  36975. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  36976. if (pointA === undefined) {
  36977. pointA = cacheSoloPointer;
  36978. }
  36979. else if (pointB === undefined) {
  36980. pointB = cacheSoloPointer;
  36981. }
  36982. if (!noPreventDefault) {
  36983. evt.preventDefault();
  36984. element.focus();
  36985. }
  36986. }
  36987. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  36988. _this.camera.restoreState();
  36989. }
  36990. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  36991. try {
  36992. evt.srcElement.releasePointerCapture(evt.pointerId);
  36993. }
  36994. catch (e) {
  36995. //Nothing to do with the error.
  36996. }
  36997. cacheSoloPointer = null;
  36998. previousPinchSquaredDistance = 0;
  36999. previousMultiTouchPanPosition.isPaning = false;
  37000. previousMultiTouchPanPosition.isPinching = false;
  37001. twoFingerActivityCount = 0;
  37002. initialDistance = 0;
  37003. if (p.event.pointerType !== "touch") {
  37004. pointB = undefined; // Mouse and pen are mono pointer
  37005. }
  37006. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  37007. //but emptying completly pointers collection is required to fix a bug on iPhone :
  37008. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  37009. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  37010. if (engine.badOS) {
  37011. pointA = pointB = undefined;
  37012. }
  37013. else {
  37014. //only remove the impacted pointer in case of multitouch allowing on most
  37015. //platforms switching from rotate to zoom and pan seamlessly.
  37016. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  37017. pointA = pointB;
  37018. pointB = undefined;
  37019. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  37020. }
  37021. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  37022. pointB = undefined;
  37023. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  37024. }
  37025. else {
  37026. pointA = pointB = undefined;
  37027. }
  37028. }
  37029. if (!noPreventDefault) {
  37030. evt.preventDefault();
  37031. }
  37032. }
  37033. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  37034. if (!noPreventDefault) {
  37035. evt.preventDefault();
  37036. }
  37037. // One button down
  37038. if (pointA && pointB === undefined) {
  37039. if (_this.panningSensibility !== 0 &&
  37040. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  37041. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  37042. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  37043. }
  37044. else {
  37045. var offsetX = evt.clientX - cacheSoloPointer.x;
  37046. var offsetY = evt.clientY - cacheSoloPointer.y;
  37047. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  37048. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  37049. }
  37050. cacheSoloPointer.x = evt.clientX;
  37051. cacheSoloPointer.y = evt.clientY;
  37052. }
  37053. else if (pointA && pointB) {
  37054. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  37055. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  37056. ed.x = evt.clientX;
  37057. ed.y = evt.clientY;
  37058. var direction = _this.pinchInwards ? 1 : -1;
  37059. var distX = pointA.x - pointB.x;
  37060. var distY = pointA.y - pointB.y;
  37061. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  37062. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  37063. if (previousPinchSquaredDistance === 0) {
  37064. initialDistance = pinchDistance;
  37065. previousPinchSquaredDistance = pinchSquaredDistance;
  37066. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  37067. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  37068. return;
  37069. }
  37070. if (_this.multiTouchPanAndZoom) {
  37071. if (_this.pinchDeltaPercentage) {
  37072. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  37073. }
  37074. else {
  37075. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  37076. (_this.pinchPrecision *
  37077. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  37078. direction);
  37079. }
  37080. if (_this.panningSensibility !== 0) {
  37081. var pointersCenterX = (pointA.x + pointB.x) / 2;
  37082. var pointersCenterY = (pointA.y + pointB.y) / 2;
  37083. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  37084. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  37085. previousMultiTouchPanPosition.x = pointersCenterX;
  37086. previousMultiTouchPanPosition.y = pointersCenterY;
  37087. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  37088. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  37089. }
  37090. }
  37091. else {
  37092. twoFingerActivityCount++;
  37093. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  37094. if (_this.pinchDeltaPercentage) {
  37095. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  37096. }
  37097. else {
  37098. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  37099. (_this.pinchPrecision *
  37100. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  37101. direction);
  37102. }
  37103. previousMultiTouchPanPosition.isPaning = false;
  37104. previousMultiTouchPanPosition.isPinching = true;
  37105. }
  37106. else {
  37107. if (cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  37108. if (!previousMultiTouchPanPosition.isPaning) {
  37109. previousMultiTouchPanPosition.isPaning = true;
  37110. previousMultiTouchPanPosition.isPinching = false;
  37111. previousMultiTouchPanPosition.x = ed.x;
  37112. previousMultiTouchPanPosition.y = ed.y;
  37113. return;
  37114. }
  37115. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  37116. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  37117. }
  37118. }
  37119. if (cacheSoloPointer.pointerId === evt.pointerId) {
  37120. previousMultiTouchPanPosition.x = ed.x;
  37121. previousMultiTouchPanPosition.y = ed.y;
  37122. }
  37123. }
  37124. previousPinchSquaredDistance = pinchSquaredDistance;
  37125. }
  37126. }
  37127. };
  37128. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  37129. this._onContextMenu = function (evt) {
  37130. evt.preventDefault();
  37131. };
  37132. if (!this.camera._useCtrlForPanning) {
  37133. element.addEventListener("contextmenu", this._onContextMenu, false);
  37134. }
  37135. this._onLostFocus = function () {
  37136. //this._keys = [];
  37137. pointA = pointB = undefined;
  37138. previousPinchSquaredDistance = 0;
  37139. previousMultiTouchPanPosition.isPaning = false;
  37140. previousMultiTouchPanPosition.isPinching = false;
  37141. twoFingerActivityCount = 0;
  37142. cacheSoloPointer = null;
  37143. initialDistance = 0;
  37144. };
  37145. this._onMouseMove = function (evt) {
  37146. if (!engine.isPointerLock) {
  37147. return;
  37148. }
  37149. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  37150. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  37151. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  37152. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  37153. if (!noPreventDefault) {
  37154. evt.preventDefault();
  37155. }
  37156. };
  37157. this._onGestureStart = function (e) {
  37158. if (window.MSGesture === undefined) {
  37159. return;
  37160. }
  37161. if (!_this._MSGestureHandler) {
  37162. _this._MSGestureHandler = new MSGesture();
  37163. _this._MSGestureHandler.target = element;
  37164. }
  37165. _this._MSGestureHandler.addPointer(e.pointerId);
  37166. };
  37167. this._onGesture = function (e) {
  37168. _this.camera.radius *= e.scale;
  37169. if (e.preventDefault) {
  37170. if (!noPreventDefault) {
  37171. e.stopPropagation();
  37172. e.preventDefault();
  37173. }
  37174. }
  37175. };
  37176. element.addEventListener("mousemove", this._onMouseMove, false);
  37177. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  37178. element.addEventListener("MSGestureChange", this._onGesture, false);
  37179. BABYLON.Tools.RegisterTopRootEvents([
  37180. { name: "blur", handler: this._onLostFocus }
  37181. ]);
  37182. };
  37183. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  37184. BABYLON.Tools.UnregisterTopRootEvents([
  37185. { name: "blur", handler: this._onLostFocus }
  37186. ]);
  37187. if (element && this._observer) {
  37188. this.camera.getScene().onPointerObservable.remove(this._observer);
  37189. this._observer = null;
  37190. element.removeEventListener("contextmenu", this._onContextMenu);
  37191. element.removeEventListener("mousemove", this._onMouseMove);
  37192. element.removeEventListener("MSPointerDown", this._onGestureStart);
  37193. element.removeEventListener("MSGestureChange", this._onGesture);
  37194. this._isPanClick = false;
  37195. this.pinchInwards = true;
  37196. this._onMouseMove = null;
  37197. this._onGestureStart = null;
  37198. this._onGesture = null;
  37199. this._MSGestureHandler = null;
  37200. this._onLostFocus = null;
  37201. this._onContextMenu = null;
  37202. }
  37203. };
  37204. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  37205. return "ArcRotateCameraPointersInput";
  37206. };
  37207. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  37208. return "pointers";
  37209. };
  37210. __decorate([
  37211. BABYLON.serialize()
  37212. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  37213. __decorate([
  37214. BABYLON.serialize()
  37215. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  37216. __decorate([
  37217. BABYLON.serialize()
  37218. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  37219. __decorate([
  37220. BABYLON.serialize()
  37221. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  37222. __decorate([
  37223. BABYLON.serialize()
  37224. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  37225. __decorate([
  37226. BABYLON.serialize()
  37227. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  37228. __decorate([
  37229. BABYLON.serialize()
  37230. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  37231. __decorate([
  37232. BABYLON.serialize()
  37233. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  37234. return ArcRotateCameraPointersInput;
  37235. }());
  37236. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  37237. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  37238. })(BABYLON || (BABYLON = {}));
  37239. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  37240. /// <reference path="babylon.targetCamera.ts" />
  37241. /// <reference path="..\Tools\babylon.tools.ts" />
  37242. var BABYLON;
  37243. (function (BABYLON) {
  37244. var ArcRotateCamera = (function (_super) {
  37245. __extends(ArcRotateCamera, _super);
  37246. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  37247. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  37248. _this.inertialAlphaOffset = 0;
  37249. _this.inertialBetaOffset = 0;
  37250. _this.inertialRadiusOffset = 0;
  37251. _this.lowerAlphaLimit = null;
  37252. _this.upperAlphaLimit = null;
  37253. _this.lowerBetaLimit = 0.01;
  37254. _this.upperBetaLimit = Math.PI;
  37255. _this.lowerRadiusLimit = null;
  37256. _this.upperRadiusLimit = null;
  37257. _this.inertialPanningX = 0;
  37258. _this.inertialPanningY = 0;
  37259. _this.pinchToPanMaxDistance = 20;
  37260. _this.panningDistanceLimit = null;
  37261. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  37262. _this.panningInertia = 0.9;
  37263. //-- end properties for backward compatibility for inputs
  37264. _this.zoomOnFactor = 1;
  37265. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  37266. _this.allowUpsideDown = true;
  37267. _this._viewMatrix = new BABYLON.Matrix();
  37268. // Panning
  37269. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  37270. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  37271. _this.checkCollisions = false;
  37272. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  37273. _this._previousPosition = BABYLON.Vector3.Zero();
  37274. _this._collisionVelocity = BABYLON.Vector3.Zero();
  37275. _this._newPosition = BABYLON.Vector3.Zero();
  37276. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  37277. if (collidedMesh === void 0) { collidedMesh = null; }
  37278. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  37279. newPosition.multiplyInPlace(_this._collider.radius);
  37280. }
  37281. if (!collidedMesh) {
  37282. _this._previousPosition.copyFrom(_this.position);
  37283. }
  37284. else {
  37285. _this.setPosition(newPosition);
  37286. if (_this.onCollide) {
  37287. _this.onCollide(collidedMesh);
  37288. }
  37289. }
  37290. // Recompute because of constraints
  37291. var cosa = Math.cos(_this.alpha);
  37292. var sina = Math.sin(_this.alpha);
  37293. var cosb = Math.cos(_this.beta);
  37294. var sinb = Math.sin(_this.beta);
  37295. if (sinb === 0) {
  37296. sinb = 0.0001;
  37297. }
  37298. var target = _this._getTargetPosition();
  37299. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  37300. _this.position.copyFrom(_this._newPosition);
  37301. var up = _this.upVector;
  37302. if (_this.allowUpsideDown && _this.beta < 0) {
  37303. up = up.clone();
  37304. up = up.negate();
  37305. }
  37306. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  37307. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  37308. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  37309. _this._collisionTriggered = false;
  37310. };
  37311. _this._target = BABYLON.Vector3.Zero();
  37312. if (target) {
  37313. _this.setTarget(target);
  37314. }
  37315. _this.alpha = alpha;
  37316. _this.beta = beta;
  37317. _this.radius = radius;
  37318. _this.getViewMatrix();
  37319. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  37320. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  37321. return _this;
  37322. }
  37323. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  37324. get: function () {
  37325. return this._target;
  37326. },
  37327. set: function (value) {
  37328. this.setTarget(value);
  37329. },
  37330. enumerable: true,
  37331. configurable: true
  37332. });
  37333. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  37334. //-- begin properties for backward compatibility for inputs
  37335. get: function () {
  37336. var pointers = this.inputs.attached["pointers"];
  37337. if (pointers)
  37338. return pointers.angularSensibilityX;
  37339. return null;
  37340. },
  37341. set: function (value) {
  37342. var pointers = this.inputs.attached["pointers"];
  37343. if (pointers) {
  37344. pointers.angularSensibilityX = value;
  37345. }
  37346. },
  37347. enumerable: true,
  37348. configurable: true
  37349. });
  37350. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  37351. get: function () {
  37352. var pointers = this.inputs.attached["pointers"];
  37353. if (pointers)
  37354. return pointers.angularSensibilityY;
  37355. return null;
  37356. },
  37357. set: function (value) {
  37358. var pointers = this.inputs.attached["pointers"];
  37359. if (pointers) {
  37360. pointers.angularSensibilityY = value;
  37361. }
  37362. },
  37363. enumerable: true,
  37364. configurable: true
  37365. });
  37366. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  37367. get: function () {
  37368. var pointers = this.inputs.attached["pointers"];
  37369. if (pointers)
  37370. return pointers.pinchPrecision;
  37371. return null;
  37372. },
  37373. set: function (value) {
  37374. var pointers = this.inputs.attached["pointers"];
  37375. if (pointers) {
  37376. pointers.pinchPrecision = value;
  37377. }
  37378. },
  37379. enumerable: true,
  37380. configurable: true
  37381. });
  37382. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  37383. get: function () {
  37384. var pointers = this.inputs.attached["pointers"];
  37385. if (pointers)
  37386. return pointers.pinchDeltaPercentage;
  37387. return null;
  37388. },
  37389. set: function (value) {
  37390. var pointers = this.inputs.attached["pointers"];
  37391. if (pointers) {
  37392. pointers.pinchDeltaPercentage = value;
  37393. }
  37394. },
  37395. enumerable: true,
  37396. configurable: true
  37397. });
  37398. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  37399. get: function () {
  37400. var pointers = this.inputs.attached["pointers"];
  37401. if (pointers)
  37402. return pointers.panningSensibility;
  37403. return null;
  37404. },
  37405. set: function (value) {
  37406. var pointers = this.inputs.attached["pointers"];
  37407. if (pointers) {
  37408. pointers.panningSensibility = value;
  37409. }
  37410. },
  37411. enumerable: true,
  37412. configurable: true
  37413. });
  37414. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  37415. get: function () {
  37416. var keyboard = this.inputs.attached["keyboard"];
  37417. if (keyboard)
  37418. return keyboard.keysUp;
  37419. return null;
  37420. },
  37421. set: function (value) {
  37422. var keyboard = this.inputs.attached["keyboard"];
  37423. if (keyboard)
  37424. keyboard.keysUp = value;
  37425. },
  37426. enumerable: true,
  37427. configurable: true
  37428. });
  37429. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  37430. get: function () {
  37431. var keyboard = this.inputs.attached["keyboard"];
  37432. if (keyboard)
  37433. return keyboard.keysDown;
  37434. return null;
  37435. },
  37436. set: function (value) {
  37437. var keyboard = this.inputs.attached["keyboard"];
  37438. if (keyboard)
  37439. keyboard.keysDown = value;
  37440. },
  37441. enumerable: true,
  37442. configurable: true
  37443. });
  37444. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  37445. get: function () {
  37446. var keyboard = this.inputs.attached["keyboard"];
  37447. if (keyboard)
  37448. return keyboard.keysLeft;
  37449. return null;
  37450. },
  37451. set: function (value) {
  37452. var keyboard = this.inputs.attached["keyboard"];
  37453. if (keyboard)
  37454. keyboard.keysLeft = value;
  37455. },
  37456. enumerable: true,
  37457. configurable: true
  37458. });
  37459. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  37460. get: function () {
  37461. var keyboard = this.inputs.attached["keyboard"];
  37462. if (keyboard)
  37463. return keyboard.keysRight;
  37464. return null;
  37465. },
  37466. set: function (value) {
  37467. var keyboard = this.inputs.attached["keyboard"];
  37468. if (keyboard)
  37469. keyboard.keysRight = value;
  37470. },
  37471. enumerable: true,
  37472. configurable: true
  37473. });
  37474. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  37475. get: function () {
  37476. var mousewheel = this.inputs.attached["mousewheel"];
  37477. if (mousewheel)
  37478. return mousewheel.wheelPrecision;
  37479. return null;
  37480. },
  37481. set: function (value) {
  37482. var mousewheel = this.inputs.attached["mousewheel"];
  37483. if (mousewheel)
  37484. mousewheel.wheelPrecision = value;
  37485. },
  37486. enumerable: true,
  37487. configurable: true
  37488. });
  37489. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  37490. get: function () {
  37491. var mousewheel = this.inputs.attached["mousewheel"];
  37492. if (mousewheel)
  37493. return mousewheel.wheelDeltaPercentage;
  37494. return null;
  37495. },
  37496. set: function (value) {
  37497. var mousewheel = this.inputs.attached["mousewheel"];
  37498. if (mousewheel)
  37499. mousewheel.wheelDeltaPercentage = value;
  37500. },
  37501. enumerable: true,
  37502. configurable: true
  37503. });
  37504. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  37505. get: function () {
  37506. return this._bouncingBehavior;
  37507. },
  37508. enumerable: true,
  37509. configurable: true
  37510. });
  37511. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  37512. get: function () {
  37513. return this._bouncingBehavior != null;
  37514. },
  37515. set: function (value) {
  37516. if (value === this.useBouncingBehavior) {
  37517. return;
  37518. }
  37519. if (value) {
  37520. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  37521. this.addBehavior(this._bouncingBehavior);
  37522. }
  37523. else {
  37524. this.removeBehavior(this._bouncingBehavior);
  37525. this._bouncingBehavior = null;
  37526. }
  37527. },
  37528. enumerable: true,
  37529. configurable: true
  37530. });
  37531. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  37532. get: function () {
  37533. return this._framingBehavior;
  37534. },
  37535. enumerable: true,
  37536. configurable: true
  37537. });
  37538. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  37539. get: function () {
  37540. return this._framingBehavior != null;
  37541. },
  37542. set: function (value) {
  37543. if (value === this.useFramingBehavior) {
  37544. return;
  37545. }
  37546. if (value) {
  37547. this._framingBehavior = new BABYLON.FramingBehavior();
  37548. this.addBehavior(this._framingBehavior);
  37549. }
  37550. else {
  37551. this.removeBehavior(this._framingBehavior);
  37552. this._framingBehavior = null;
  37553. }
  37554. },
  37555. enumerable: true,
  37556. configurable: true
  37557. });
  37558. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  37559. get: function () {
  37560. return this._autoRotationBehavior;
  37561. },
  37562. enumerable: true,
  37563. configurable: true
  37564. });
  37565. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  37566. get: function () {
  37567. return this._autoRotationBehavior != null;
  37568. },
  37569. set: function (value) {
  37570. if (value === this.useAutoRotationBehavior) {
  37571. return;
  37572. }
  37573. if (value) {
  37574. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  37575. this.addBehavior(this._autoRotationBehavior);
  37576. }
  37577. else {
  37578. this.removeBehavior(this._autoRotationBehavior);
  37579. this._autoRotationBehavior = null;
  37580. }
  37581. },
  37582. enumerable: true,
  37583. configurable: true
  37584. });
  37585. // Cache
  37586. ArcRotateCamera.prototype._initCache = function () {
  37587. _super.prototype._initCache.call(this);
  37588. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37589. this._cache.alpha = undefined;
  37590. this._cache.beta = undefined;
  37591. this._cache.radius = undefined;
  37592. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  37593. };
  37594. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  37595. if (!ignoreParentClass) {
  37596. _super.prototype._updateCache.call(this);
  37597. }
  37598. this._cache._target.copyFrom(this._getTargetPosition());
  37599. this._cache.alpha = this.alpha;
  37600. this._cache.beta = this.beta;
  37601. this._cache.radius = this.radius;
  37602. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  37603. };
  37604. ArcRotateCamera.prototype._getTargetPosition = function () {
  37605. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  37606. var pos = this._targetHost.getAbsolutePosition();
  37607. if (this._targetBoundingCenter) {
  37608. pos.addToRef(this._targetBoundingCenter, this._target);
  37609. }
  37610. else {
  37611. this._target.copyFrom(pos);
  37612. }
  37613. }
  37614. var lockedTargetPosition = this._getLockedTargetPosition();
  37615. if (lockedTargetPosition) {
  37616. return lockedTargetPosition;
  37617. }
  37618. return this._target;
  37619. };
  37620. ArcRotateCamera.prototype.storeState = function () {
  37621. this._storedAlpha = this.alpha;
  37622. this._storedBeta = this.beta;
  37623. this._storedRadius = this.radius;
  37624. this._storedTarget = this._getTargetPosition().clone();
  37625. return _super.prototype.storeState.call(this);
  37626. };
  37627. /**
  37628. * Restored camera state. You must call storeState() first
  37629. */
  37630. ArcRotateCamera.prototype._restoreStateValues = function () {
  37631. if (!_super.prototype._restoreStateValues.call(this)) {
  37632. return false;
  37633. }
  37634. this.alpha = this._storedAlpha;
  37635. this.beta = this._storedBeta;
  37636. this.radius = this._storedRadius;
  37637. this.setTarget(this._storedTarget.clone());
  37638. this.inertialAlphaOffset = 0;
  37639. this.inertialBetaOffset = 0;
  37640. this.inertialRadiusOffset = 0;
  37641. this.inertialPanningX = 0;
  37642. this.inertialPanningY = 0;
  37643. return true;
  37644. };
  37645. // Synchronized
  37646. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  37647. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  37648. return false;
  37649. return this._cache._target.equals(this._getTargetPosition())
  37650. && this._cache.alpha === this.alpha
  37651. && this._cache.beta === this.beta
  37652. && this._cache.radius === this.radius
  37653. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  37654. };
  37655. // Methods
  37656. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  37657. var _this = this;
  37658. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  37659. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  37660. this._useCtrlForPanning = useCtrlForPanning;
  37661. this._panningMouseButton = panningMouseButton;
  37662. this.inputs.attachElement(element, noPreventDefault);
  37663. this._reset = function () {
  37664. _this.inertialAlphaOffset = 0;
  37665. _this.inertialBetaOffset = 0;
  37666. _this.inertialRadiusOffset = 0;
  37667. _this.inertialPanningX = 0;
  37668. _this.inertialPanningY = 0;
  37669. };
  37670. };
  37671. ArcRotateCamera.prototype.detachControl = function (element) {
  37672. this.inputs.detachElement(element);
  37673. if (this._reset) {
  37674. this._reset();
  37675. }
  37676. };
  37677. ArcRotateCamera.prototype._checkInputs = function () {
  37678. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  37679. if (this._collisionTriggered) {
  37680. return;
  37681. }
  37682. this.inputs.checkInputs();
  37683. // Inertia
  37684. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  37685. if (this.getScene().useRightHandedSystem) {
  37686. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  37687. }
  37688. else {
  37689. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  37690. }
  37691. this.beta += this.inertialBetaOffset;
  37692. this.radius -= this.inertialRadiusOffset;
  37693. this.inertialAlphaOffset *= this.inertia;
  37694. this.inertialBetaOffset *= this.inertia;
  37695. this.inertialRadiusOffset *= this.inertia;
  37696. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  37697. this.inertialAlphaOffset = 0;
  37698. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  37699. this.inertialBetaOffset = 0;
  37700. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  37701. this.inertialRadiusOffset = 0;
  37702. }
  37703. // Panning inertia
  37704. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  37705. if (!this._localDirection) {
  37706. this._localDirection = BABYLON.Vector3.Zero();
  37707. this._transformedDirection = BABYLON.Vector3.Zero();
  37708. }
  37709. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  37710. this._localDirection.multiplyInPlace(this.panningAxis);
  37711. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  37712. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  37713. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  37714. if (!this.panningAxis.y) {
  37715. this._transformedDirection.y = 0;
  37716. }
  37717. if (!this._targetHost) {
  37718. if (this.panningDistanceLimit) {
  37719. this._transformedDirection.addInPlace(this._target);
  37720. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  37721. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  37722. this._target.copyFrom(this._transformedDirection);
  37723. }
  37724. }
  37725. else {
  37726. this._target.addInPlace(this._transformedDirection);
  37727. }
  37728. }
  37729. this.inertialPanningX *= this.panningInertia;
  37730. this.inertialPanningY *= this.panningInertia;
  37731. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  37732. this.inertialPanningX = 0;
  37733. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  37734. this.inertialPanningY = 0;
  37735. }
  37736. // Limits
  37737. this._checkLimits();
  37738. _super.prototype._checkInputs.call(this);
  37739. };
  37740. ArcRotateCamera.prototype._checkLimits = function () {
  37741. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  37742. if (this.allowUpsideDown && this.beta > Math.PI) {
  37743. this.beta = this.beta - (2 * Math.PI);
  37744. }
  37745. }
  37746. else {
  37747. if (this.beta < this.lowerBetaLimit) {
  37748. this.beta = this.lowerBetaLimit;
  37749. }
  37750. }
  37751. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  37752. if (this.allowUpsideDown && this.beta < -Math.PI) {
  37753. this.beta = this.beta + (2 * Math.PI);
  37754. }
  37755. }
  37756. else {
  37757. if (this.beta > this.upperBetaLimit) {
  37758. this.beta = this.upperBetaLimit;
  37759. }
  37760. }
  37761. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  37762. this.alpha = this.lowerAlphaLimit;
  37763. }
  37764. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  37765. this.alpha = this.upperAlphaLimit;
  37766. }
  37767. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  37768. this.radius = this.lowerRadiusLimit;
  37769. }
  37770. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  37771. this.radius = this.upperRadiusLimit;
  37772. }
  37773. };
  37774. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  37775. var radiusv3 = this.position.subtract(this._getTargetPosition());
  37776. this.radius = radiusv3.length();
  37777. if (this.radius === 0) {
  37778. this.radius = 0.0001; // Just to avoid division by zero
  37779. }
  37780. // Alpha
  37781. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  37782. if (radiusv3.z < 0) {
  37783. this.alpha = 2 * Math.PI - this.alpha;
  37784. }
  37785. // Beta
  37786. this.beta = Math.acos(radiusv3.y / this.radius);
  37787. this._checkLimits();
  37788. };
  37789. ArcRotateCamera.prototype.setPosition = function (position) {
  37790. if (this.position.equals(position)) {
  37791. return;
  37792. }
  37793. this.position.copyFrom(position);
  37794. this.rebuildAnglesAndRadius();
  37795. };
  37796. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  37797. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  37798. if (allowSamePosition === void 0) { allowSamePosition = false; }
  37799. if (target.getBoundingInfo) {
  37800. if (toBoundingCenter) {
  37801. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  37802. }
  37803. else {
  37804. this._targetBoundingCenter = null;
  37805. }
  37806. this._targetHost = target;
  37807. this._target = this._getTargetPosition();
  37808. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  37809. }
  37810. else {
  37811. var newTarget = target;
  37812. var currentTarget = this._getTargetPosition();
  37813. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  37814. return;
  37815. }
  37816. this._targetHost = null;
  37817. this._target = newTarget;
  37818. this._targetBoundingCenter = null;
  37819. this.onMeshTargetChangedObservable.notifyObservers(null);
  37820. }
  37821. this.rebuildAnglesAndRadius();
  37822. };
  37823. ArcRotateCamera.prototype._getViewMatrix = function () {
  37824. // Compute
  37825. var cosa = Math.cos(this.alpha);
  37826. var sina = Math.sin(this.alpha);
  37827. var cosb = Math.cos(this.beta);
  37828. var sinb = Math.sin(this.beta);
  37829. if (sinb === 0) {
  37830. sinb = 0.0001;
  37831. }
  37832. var target = this._getTargetPosition();
  37833. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  37834. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  37835. if (!this._collider) {
  37836. this._collider = new BABYLON.Collider();
  37837. }
  37838. this._collider.radius = this.collisionRadius;
  37839. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  37840. this._collisionTriggered = true;
  37841. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  37842. }
  37843. else {
  37844. this.position.copyFrom(this._newPosition);
  37845. var up = this.upVector;
  37846. if (this.allowUpsideDown && sinb < 0) {
  37847. up = up.clone();
  37848. up = up.negate();
  37849. }
  37850. if (this.getScene().useRightHandedSystem) {
  37851. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  37852. }
  37853. else {
  37854. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  37855. }
  37856. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  37857. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  37858. }
  37859. this._currentTarget = target;
  37860. return this._viewMatrix;
  37861. };
  37862. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  37863. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  37864. meshes = meshes || this.getScene().meshes;
  37865. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  37866. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  37867. this.radius = distance * this.zoomOnFactor;
  37868. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  37869. };
  37870. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  37871. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  37872. var meshesOrMinMaxVector;
  37873. var distance;
  37874. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  37875. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  37876. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  37877. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  37878. }
  37879. else {
  37880. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  37881. meshesOrMinMaxVector = minMaxVectorAndDistance;
  37882. distance = minMaxVectorAndDistance.distance;
  37883. }
  37884. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  37885. if (!doNotUpdateMaxZ) {
  37886. this.maxZ = distance * 2;
  37887. }
  37888. };
  37889. /**
  37890. * @override
  37891. * Override Camera.createRigCamera
  37892. */
  37893. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  37894. var alphaShift;
  37895. switch (this.cameraRigMode) {
  37896. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  37897. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  37898. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  37899. case BABYLON.Camera.RIG_MODE_VR:
  37900. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  37901. break;
  37902. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  37903. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  37904. break;
  37905. }
  37906. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  37907. rigCam._cameraRigParams = {};
  37908. return rigCam;
  37909. };
  37910. /**
  37911. * @override
  37912. * Override Camera._updateRigCameras
  37913. */
  37914. ArcRotateCamera.prototype._updateRigCameras = function () {
  37915. var camLeft = this._rigCameras[0];
  37916. var camRight = this._rigCameras[1];
  37917. camLeft.beta = camRight.beta = this.beta;
  37918. camLeft.radius = camRight.radius = this.radius;
  37919. switch (this.cameraRigMode) {
  37920. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  37921. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  37922. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  37923. case BABYLON.Camera.RIG_MODE_VR:
  37924. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  37925. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  37926. break;
  37927. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  37928. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  37929. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  37930. break;
  37931. }
  37932. _super.prototype._updateRigCameras.call(this);
  37933. };
  37934. ArcRotateCamera.prototype.dispose = function () {
  37935. this.inputs.clear();
  37936. _super.prototype.dispose.call(this);
  37937. };
  37938. ArcRotateCamera.prototype.getClassName = function () {
  37939. return "ArcRotateCamera";
  37940. };
  37941. __decorate([
  37942. BABYLON.serialize()
  37943. ], ArcRotateCamera.prototype, "alpha", void 0);
  37944. __decorate([
  37945. BABYLON.serialize()
  37946. ], ArcRotateCamera.prototype, "beta", void 0);
  37947. __decorate([
  37948. BABYLON.serialize()
  37949. ], ArcRotateCamera.prototype, "radius", void 0);
  37950. __decorate([
  37951. BABYLON.serializeAsVector3("target")
  37952. ], ArcRotateCamera.prototype, "_target", void 0);
  37953. __decorate([
  37954. BABYLON.serialize()
  37955. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  37956. __decorate([
  37957. BABYLON.serialize()
  37958. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  37959. __decorate([
  37960. BABYLON.serialize()
  37961. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  37962. __decorate([
  37963. BABYLON.serialize()
  37964. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  37965. __decorate([
  37966. BABYLON.serialize()
  37967. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  37968. __decorate([
  37969. BABYLON.serialize()
  37970. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  37971. __decorate([
  37972. BABYLON.serialize()
  37973. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  37974. __decorate([
  37975. BABYLON.serialize()
  37976. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  37977. __decorate([
  37978. BABYLON.serialize()
  37979. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  37980. __decorate([
  37981. BABYLON.serialize()
  37982. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  37983. __decorate([
  37984. BABYLON.serialize()
  37985. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  37986. __decorate([
  37987. BABYLON.serialize()
  37988. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  37989. __decorate([
  37990. BABYLON.serialize()
  37991. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  37992. __decorate([
  37993. BABYLON.serializeAsVector3()
  37994. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  37995. __decorate([
  37996. BABYLON.serialize()
  37997. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  37998. __decorate([
  37999. BABYLON.serialize()
  38000. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  38001. __decorate([
  38002. BABYLON.serialize()
  38003. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  38004. return ArcRotateCamera;
  38005. }(BABYLON.TargetCamera));
  38006. BABYLON.ArcRotateCamera = ArcRotateCamera;
  38007. })(BABYLON || (BABYLON = {}));
  38008. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  38009. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  38010. var BABYLON;
  38011. (function (BABYLON) {
  38012. var ArcRotateCameraInputsManager = (function (_super) {
  38013. __extends(ArcRotateCameraInputsManager, _super);
  38014. function ArcRotateCameraInputsManager(camera) {
  38015. return _super.call(this, camera) || this;
  38016. }
  38017. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  38018. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  38019. return this;
  38020. };
  38021. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  38022. this.add(new BABYLON.ArcRotateCameraPointersInput());
  38023. return this;
  38024. };
  38025. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  38026. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  38027. return this;
  38028. };
  38029. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  38030. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  38031. return this;
  38032. };
  38033. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  38034. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  38035. return this;
  38036. };
  38037. return ArcRotateCameraInputsManager;
  38038. }(BABYLON.CameraInputsManager));
  38039. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  38040. })(BABYLON || (BABYLON = {}));
  38041. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  38042. var BABYLON;
  38043. (function (BABYLON) {
  38044. var HemisphericLight = (function (_super) {
  38045. __extends(HemisphericLight, _super);
  38046. /**
  38047. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  38048. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  38049. * The HemisphericLight can't cast shadows.
  38050. * Documentation : http://doc.babylonjs.com/tutorials/lights
  38051. */
  38052. function HemisphericLight(name, direction, scene) {
  38053. var _this = _super.call(this, name, scene) || this;
  38054. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  38055. _this.direction = direction || BABYLON.Vector3.Up();
  38056. return _this;
  38057. }
  38058. HemisphericLight.prototype._buildUniformLayout = function () {
  38059. this._uniformBuffer.addUniform("vLightData", 4);
  38060. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  38061. this._uniformBuffer.addUniform("vLightSpecular", 3);
  38062. this._uniformBuffer.addUniform("vLightGround", 3);
  38063. this._uniformBuffer.addUniform("shadowsInfo", 3);
  38064. this._uniformBuffer.addUniform("depthValues", 2);
  38065. this._uniformBuffer.create();
  38066. };
  38067. /**
  38068. * Returns the string "HemisphericLight".
  38069. */
  38070. HemisphericLight.prototype.getClassName = function () {
  38071. return "HemisphericLight";
  38072. };
  38073. /**
  38074. * Sets the HemisphericLight direction towards the passed target (Vector3).
  38075. * Returns the updated direction.
  38076. */
  38077. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  38078. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  38079. return this.direction;
  38080. };
  38081. HemisphericLight.prototype.getShadowGenerator = function () {
  38082. return null;
  38083. };
  38084. /**
  38085. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  38086. * Returns the HemisphericLight.
  38087. */
  38088. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  38089. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  38090. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  38091. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  38092. return this;
  38093. };
  38094. HemisphericLight.prototype._getWorldMatrix = function () {
  38095. if (!this._worldMatrix) {
  38096. this._worldMatrix = BABYLON.Matrix.Identity();
  38097. }
  38098. return this._worldMatrix;
  38099. };
  38100. /**
  38101. * Returns the integer 3.
  38102. */
  38103. HemisphericLight.prototype.getTypeID = function () {
  38104. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  38105. };
  38106. __decorate([
  38107. BABYLON.serializeAsColor3()
  38108. ], HemisphericLight.prototype, "groundColor", void 0);
  38109. __decorate([
  38110. BABYLON.serializeAsVector3()
  38111. ], HemisphericLight.prototype, "direction", void 0);
  38112. return HemisphericLight;
  38113. }(BABYLON.Light));
  38114. BABYLON.HemisphericLight = HemisphericLight;
  38115. })(BABYLON || (BABYLON = {}));
  38116. //# sourceMappingURL=babylon.hemisphericLight.js.map
  38117. var BABYLON;
  38118. (function (BABYLON) {
  38119. var ShadowLight = (function (_super) {
  38120. __extends(ShadowLight, _super);
  38121. function ShadowLight() {
  38122. var _this = _super !== null && _super.apply(this, arguments) || this;
  38123. _this._needProjectionMatrixCompute = true;
  38124. return _this;
  38125. }
  38126. Object.defineProperty(ShadowLight.prototype, "direction", {
  38127. get: function () {
  38128. return this._direction;
  38129. },
  38130. set: function (value) {
  38131. this._direction = value;
  38132. },
  38133. enumerable: true,
  38134. configurable: true
  38135. });
  38136. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  38137. get: function () {
  38138. return this._shadowMinZ;
  38139. },
  38140. set: function (value) {
  38141. this._shadowMinZ = value;
  38142. this.forceProjectionMatrixCompute();
  38143. },
  38144. enumerable: true,
  38145. configurable: true
  38146. });
  38147. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  38148. get: function () {
  38149. return this._shadowMaxZ;
  38150. },
  38151. set: function (value) {
  38152. this._shadowMaxZ = value;
  38153. this.forceProjectionMatrixCompute();
  38154. },
  38155. enumerable: true,
  38156. configurable: true
  38157. });
  38158. /**
  38159. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  38160. */
  38161. ShadowLight.prototype.computeTransformedInformation = function () {
  38162. if (this.parent && this.parent.getWorldMatrix) {
  38163. if (!this.transformedPosition) {
  38164. this.transformedPosition = BABYLON.Vector3.Zero();
  38165. }
  38166. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  38167. // In case the direction is present.
  38168. if (this.direction) {
  38169. if (!this.transformedDirection) {
  38170. this.transformedDirection = BABYLON.Vector3.Zero();
  38171. }
  38172. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  38173. }
  38174. return true;
  38175. }
  38176. return false;
  38177. };
  38178. /**
  38179. * Return the depth scale used for the shadow map.
  38180. */
  38181. ShadowLight.prototype.getDepthScale = function () {
  38182. return 50.0;
  38183. };
  38184. /**
  38185. * Returns the light direction (Vector3) for any passed face index.
  38186. */
  38187. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  38188. return this.transformedDirection ? this.transformedDirection : this.direction;
  38189. };
  38190. /**
  38191. * Returns the DirectionalLight absolute position in the World.
  38192. */
  38193. ShadowLight.prototype.getAbsolutePosition = function () {
  38194. return this.transformedPosition ? this.transformedPosition : this.position;
  38195. };
  38196. /**
  38197. * Sets the DirectionalLight direction toward the passed target (Vector3).
  38198. * Returns the updated DirectionalLight direction (Vector3).
  38199. */
  38200. ShadowLight.prototype.setDirectionToTarget = function (target) {
  38201. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  38202. return this.direction;
  38203. };
  38204. /**
  38205. * Returns the light rotation (Vector3).
  38206. */
  38207. ShadowLight.prototype.getRotation = function () {
  38208. this.direction.normalize();
  38209. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  38210. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  38211. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  38212. };
  38213. /**
  38214. * Boolean : false by default.
  38215. */
  38216. ShadowLight.prototype.needCube = function () {
  38217. return false;
  38218. };
  38219. /**
  38220. * Specifies wether or not the projection matrix should be recomputed this frame.
  38221. */
  38222. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  38223. return this._needProjectionMatrixCompute;
  38224. };
  38225. /**
  38226. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  38227. */
  38228. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  38229. this._needProjectionMatrixCompute = true;
  38230. };
  38231. /**
  38232. * Get the world matrix of the sahdow lights.
  38233. */
  38234. ShadowLight.prototype._getWorldMatrix = function () {
  38235. if (!this._worldMatrix) {
  38236. this._worldMatrix = BABYLON.Matrix.Identity();
  38237. }
  38238. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  38239. return this._worldMatrix;
  38240. };
  38241. /**
  38242. * Gets the minZ used for shadow according to both the scene and the light.
  38243. * @param activeCamera
  38244. */
  38245. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  38246. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  38247. };
  38248. /**
  38249. * Gets the maxZ used for shadow according to both the scene and the light.
  38250. * @param activeCamera
  38251. */
  38252. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  38253. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  38254. };
  38255. /**
  38256. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  38257. * Returns the light.
  38258. */
  38259. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  38260. if (this.customProjectionMatrixBuilder) {
  38261. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  38262. }
  38263. else {
  38264. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  38265. }
  38266. return this;
  38267. };
  38268. __decorate([
  38269. BABYLON.serializeAsVector3()
  38270. ], ShadowLight.prototype, "position", void 0);
  38271. __decorate([
  38272. BABYLON.serializeAsVector3()
  38273. ], ShadowLight.prototype, "direction", null);
  38274. __decorate([
  38275. BABYLON.serialize()
  38276. ], ShadowLight.prototype, "shadowMinZ", null);
  38277. __decorate([
  38278. BABYLON.serialize()
  38279. ], ShadowLight.prototype, "shadowMaxZ", null);
  38280. return ShadowLight;
  38281. }(BABYLON.Light));
  38282. BABYLON.ShadowLight = ShadowLight;
  38283. })(BABYLON || (BABYLON = {}));
  38284. //# sourceMappingURL=babylon.shadowLight.js.map
  38285. var BABYLON;
  38286. (function (BABYLON) {
  38287. var PointLight = (function (_super) {
  38288. __extends(PointLight, _super);
  38289. /**
  38290. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  38291. * A PointLight emits the light in every direction.
  38292. * It can cast shadows.
  38293. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  38294. * ```javascript
  38295. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  38296. * ```
  38297. * Documentation : http://doc.babylonjs.com/tutorials/lights
  38298. */
  38299. function PointLight(name, position, scene) {
  38300. var _this = _super.call(this, name, scene) || this;
  38301. _this._shadowAngle = Math.PI / 2;
  38302. _this.position = position;
  38303. return _this;
  38304. }
  38305. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  38306. /**
  38307. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  38308. * This specifies what angle the shadow will use to be created.
  38309. *
  38310. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  38311. */
  38312. get: function () {
  38313. return this._shadowAngle;
  38314. },
  38315. /**
  38316. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  38317. * This specifies what angle the shadow will use to be created.
  38318. *
  38319. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  38320. */
  38321. set: function (value) {
  38322. this._shadowAngle = value;
  38323. this.forceProjectionMatrixCompute();
  38324. },
  38325. enumerable: true,
  38326. configurable: true
  38327. });
  38328. Object.defineProperty(PointLight.prototype, "direction", {
  38329. get: function () {
  38330. return this._direction;
  38331. },
  38332. /**
  38333. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  38334. */
  38335. set: function (value) {
  38336. var previousNeedCube = this.needCube();
  38337. this._direction = value;
  38338. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  38339. this._shadowGenerator.recreateShadowMap();
  38340. }
  38341. },
  38342. enumerable: true,
  38343. configurable: true
  38344. });
  38345. /**
  38346. * Returns the string "PointLight"
  38347. */
  38348. PointLight.prototype.getClassName = function () {
  38349. return "PointLight";
  38350. };
  38351. /**
  38352. * Returns the integer 0.
  38353. */
  38354. PointLight.prototype.getTypeID = function () {
  38355. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  38356. };
  38357. /**
  38358. * Specifies wether or not the shadowmap should be a cube texture.
  38359. */
  38360. PointLight.prototype.needCube = function () {
  38361. return !this.direction;
  38362. };
  38363. /**
  38364. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  38365. */
  38366. PointLight.prototype.getShadowDirection = function (faceIndex) {
  38367. if (this.direction) {
  38368. return _super.prototype.getShadowDirection.call(this, faceIndex);
  38369. }
  38370. else {
  38371. switch (faceIndex) {
  38372. case 0:
  38373. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  38374. case 1:
  38375. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  38376. case 2:
  38377. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  38378. case 3:
  38379. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  38380. case 4:
  38381. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  38382. case 5:
  38383. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  38384. }
  38385. }
  38386. return BABYLON.Vector3.Zero();
  38387. };
  38388. /**
  38389. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  38390. * - fov = PI / 2
  38391. * - aspect ratio : 1.0
  38392. * - z-near and far equal to the active camera minZ and maxZ.
  38393. * Returns the PointLight.
  38394. */
  38395. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  38396. var activeCamera = this.getScene().activeCamera;
  38397. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  38398. };
  38399. PointLight.prototype._buildUniformLayout = function () {
  38400. this._uniformBuffer.addUniform("vLightData", 4);
  38401. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  38402. this._uniformBuffer.addUniform("vLightSpecular", 3);
  38403. this._uniformBuffer.addUniform("shadowsInfo", 3);
  38404. this._uniformBuffer.addUniform("depthValues", 2);
  38405. this._uniformBuffer.create();
  38406. };
  38407. /**
  38408. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  38409. * Returns the PointLight.
  38410. */
  38411. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  38412. if (this.computeTransformedInformation()) {
  38413. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  38414. return this;
  38415. }
  38416. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  38417. return this;
  38418. };
  38419. __decorate([
  38420. BABYLON.serialize()
  38421. ], PointLight.prototype, "shadowAngle", null);
  38422. return PointLight;
  38423. }(BABYLON.ShadowLight));
  38424. BABYLON.PointLight = PointLight;
  38425. })(BABYLON || (BABYLON = {}));
  38426. //# sourceMappingURL=babylon.pointLight.js.map
  38427. /// <reference path="babylon.light.ts" />
  38428. var BABYLON;
  38429. (function (BABYLON) {
  38430. var DirectionalLight = (function (_super) {
  38431. __extends(DirectionalLight, _super);
  38432. /**
  38433. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  38434. * The directional light is emitted from everywhere in the given direction.
  38435. * It can cast shawdows.
  38436. * Documentation : http://doc.babylonjs.com/tutorials/lights
  38437. */
  38438. function DirectionalLight(name, direction, scene) {
  38439. var _this = _super.call(this, name, scene) || this;
  38440. _this._shadowFrustumSize = 0;
  38441. _this._shadowOrthoScale = 0.5;
  38442. _this.autoUpdateExtends = true;
  38443. // Cache
  38444. _this._orthoLeft = Number.MAX_VALUE;
  38445. _this._orthoRight = Number.MIN_VALUE;
  38446. _this._orthoTop = Number.MIN_VALUE;
  38447. _this._orthoBottom = Number.MAX_VALUE;
  38448. _this.position = direction.scale(-1.0);
  38449. _this.direction = direction;
  38450. return _this;
  38451. }
  38452. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  38453. /**
  38454. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  38455. */
  38456. get: function () {
  38457. return this._shadowFrustumSize;
  38458. },
  38459. /**
  38460. * Specifies a fix frustum size for the shadow generation.
  38461. */
  38462. set: function (value) {
  38463. this._shadowFrustumSize = value;
  38464. this.forceProjectionMatrixCompute();
  38465. },
  38466. enumerable: true,
  38467. configurable: true
  38468. });
  38469. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  38470. get: function () {
  38471. return this._shadowOrthoScale;
  38472. },
  38473. set: function (value) {
  38474. this._shadowOrthoScale = value;
  38475. this.forceProjectionMatrixCompute();
  38476. },
  38477. enumerable: true,
  38478. configurable: true
  38479. });
  38480. /**
  38481. * Returns the string "DirectionalLight".
  38482. */
  38483. DirectionalLight.prototype.getClassName = function () {
  38484. return "DirectionalLight";
  38485. };
  38486. /**
  38487. * Returns the integer 1.
  38488. */
  38489. DirectionalLight.prototype.getTypeID = function () {
  38490. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  38491. };
  38492. /**
  38493. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  38494. * Returns the DirectionalLight Shadow projection matrix.
  38495. */
  38496. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  38497. if (this.shadowFrustumSize > 0) {
  38498. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  38499. }
  38500. else {
  38501. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  38502. }
  38503. };
  38504. /**
  38505. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  38506. * Returns the DirectionalLight Shadow projection matrix.
  38507. */
  38508. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  38509. var activeCamera = this.getScene().activeCamera;
  38510. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  38511. };
  38512. /**
  38513. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  38514. * Returns the DirectionalLight Shadow projection matrix.
  38515. */
  38516. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  38517. var activeCamera = this.getScene().activeCamera;
  38518. // Check extends
  38519. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  38520. var tempVector3 = BABYLON.Vector3.Zero();
  38521. this._orthoLeft = Number.MAX_VALUE;
  38522. this._orthoRight = Number.MIN_VALUE;
  38523. this._orthoTop = Number.MIN_VALUE;
  38524. this._orthoBottom = Number.MAX_VALUE;
  38525. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  38526. var mesh = renderList[meshIndex];
  38527. if (!mesh) {
  38528. continue;
  38529. }
  38530. var boundingInfo = mesh.getBoundingInfo();
  38531. if (!boundingInfo) {
  38532. continue;
  38533. }
  38534. var boundingBox = boundingInfo.boundingBox;
  38535. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  38536. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  38537. if (tempVector3.x < this._orthoLeft)
  38538. this._orthoLeft = tempVector3.x;
  38539. if (tempVector3.y < this._orthoBottom)
  38540. this._orthoBottom = tempVector3.y;
  38541. if (tempVector3.x > this._orthoRight)
  38542. this._orthoRight = tempVector3.x;
  38543. if (tempVector3.y > this._orthoTop)
  38544. this._orthoTop = tempVector3.y;
  38545. }
  38546. }
  38547. }
  38548. var xOffset = this._orthoRight - this._orthoLeft;
  38549. var yOffset = this._orthoTop - this._orthoBottom;
  38550. 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);
  38551. };
  38552. DirectionalLight.prototype._buildUniformLayout = function () {
  38553. this._uniformBuffer.addUniform("vLightData", 4);
  38554. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  38555. this._uniformBuffer.addUniform("vLightSpecular", 3);
  38556. this._uniformBuffer.addUniform("shadowsInfo", 3);
  38557. this._uniformBuffer.addUniform("depthValues", 2);
  38558. this._uniformBuffer.create();
  38559. };
  38560. /**
  38561. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  38562. * Returns the DirectionalLight.
  38563. */
  38564. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  38565. if (this.computeTransformedInformation()) {
  38566. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  38567. return this;
  38568. }
  38569. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  38570. return this;
  38571. };
  38572. /**
  38573. * Gets the minZ used for shadow according to both the scene and the light.
  38574. *
  38575. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  38576. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  38577. * @param activeCamera
  38578. */
  38579. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  38580. return 1;
  38581. };
  38582. /**
  38583. * Gets the maxZ used for shadow according to both the scene and the light.
  38584. *
  38585. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  38586. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  38587. * @param activeCamera
  38588. */
  38589. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  38590. return 1;
  38591. };
  38592. __decorate([
  38593. BABYLON.serialize()
  38594. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  38595. __decorate([
  38596. BABYLON.serialize()
  38597. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  38598. __decorate([
  38599. BABYLON.serialize()
  38600. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  38601. return DirectionalLight;
  38602. }(BABYLON.ShadowLight));
  38603. BABYLON.DirectionalLight = DirectionalLight;
  38604. })(BABYLON || (BABYLON = {}));
  38605. //# sourceMappingURL=babylon.directionalLight.js.map
  38606. var BABYLON;
  38607. (function (BABYLON) {
  38608. var SpotLight = (function (_super) {
  38609. __extends(SpotLight, _super);
  38610. /**
  38611. * Creates a SpotLight object in the scene with the passed parameters :
  38612. * - `position` (Vector3) is the initial SpotLight position,
  38613. * - `direction` (Vector3) is the initial SpotLight direction,
  38614. * - `angle` (float, in radians) is the spot light cone angle,
  38615. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  38616. * A spot light is a simply light oriented cone.
  38617. * It can cast shadows.
  38618. * Documentation : http://doc.babylonjs.com/tutorials/lights
  38619. */
  38620. function SpotLight(name, position, direction, angle, exponent, scene) {
  38621. var _this = _super.call(this, name, scene) || this;
  38622. _this.position = position;
  38623. _this.direction = direction;
  38624. _this.angle = angle;
  38625. _this.exponent = exponent;
  38626. return _this;
  38627. }
  38628. Object.defineProperty(SpotLight.prototype, "angle", {
  38629. get: function () {
  38630. return this._angle;
  38631. },
  38632. set: function (value) {
  38633. this._angle = value;
  38634. this.forceProjectionMatrixCompute();
  38635. },
  38636. enumerable: true,
  38637. configurable: true
  38638. });
  38639. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  38640. get: function () {
  38641. return this._shadowAngleScale;
  38642. },
  38643. /**
  38644. * Allows scaling the angle of the light for shadow generation only.
  38645. */
  38646. set: function (value) {
  38647. this._shadowAngleScale = value;
  38648. this.forceProjectionMatrixCompute();
  38649. },
  38650. enumerable: true,
  38651. configurable: true
  38652. });
  38653. /**
  38654. * Returns the string "SpotLight".
  38655. */
  38656. SpotLight.prototype.getClassName = function () {
  38657. return "SpotLight";
  38658. };
  38659. /**
  38660. * Returns the integer 2.
  38661. */
  38662. SpotLight.prototype.getTypeID = function () {
  38663. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  38664. };
  38665. /**
  38666. * 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.
  38667. * Returns the SpotLight.
  38668. */
  38669. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  38670. var activeCamera = this.getScene().activeCamera;
  38671. this._shadowAngleScale = this._shadowAngleScale || 1;
  38672. var angle = this._shadowAngleScale * this._angle;
  38673. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  38674. };
  38675. SpotLight.prototype._buildUniformLayout = function () {
  38676. this._uniformBuffer.addUniform("vLightData", 4);
  38677. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  38678. this._uniformBuffer.addUniform("vLightSpecular", 3);
  38679. this._uniformBuffer.addUniform("vLightDirection", 3);
  38680. this._uniformBuffer.addUniform("shadowsInfo", 3);
  38681. this._uniformBuffer.addUniform("depthValues", 2);
  38682. this._uniformBuffer.create();
  38683. };
  38684. /**
  38685. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  38686. * Return the SpotLight.
  38687. */
  38688. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  38689. var normalizeDirection;
  38690. if (this.computeTransformedInformation()) {
  38691. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  38692. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  38693. }
  38694. else {
  38695. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  38696. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  38697. }
  38698. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  38699. return this;
  38700. };
  38701. __decorate([
  38702. BABYLON.serialize()
  38703. ], SpotLight.prototype, "angle", null);
  38704. __decorate([
  38705. BABYLON.serialize()
  38706. /**
  38707. * Allows scaling the angle of the light for shadow generation only.
  38708. */
  38709. ], SpotLight.prototype, "shadowAngleScale", null);
  38710. __decorate([
  38711. BABYLON.serialize()
  38712. ], SpotLight.prototype, "exponent", void 0);
  38713. return SpotLight;
  38714. }(BABYLON.ShadowLight));
  38715. BABYLON.SpotLight = SpotLight;
  38716. })(BABYLON || (BABYLON = {}));
  38717. //# sourceMappingURL=babylon.spotLight.js.map
  38718. var BABYLON;
  38719. (function (BABYLON) {
  38720. var AnimationRange = (function () {
  38721. function AnimationRange(name, from, to) {
  38722. this.name = name;
  38723. this.from = from;
  38724. this.to = to;
  38725. }
  38726. AnimationRange.prototype.clone = function () {
  38727. return new AnimationRange(this.name, this.from, this.to);
  38728. };
  38729. return AnimationRange;
  38730. }());
  38731. BABYLON.AnimationRange = AnimationRange;
  38732. /**
  38733. * Composed of a frame, and an action function
  38734. */
  38735. var AnimationEvent = (function () {
  38736. function AnimationEvent(frame, action, onlyOnce) {
  38737. this.frame = frame;
  38738. this.action = action;
  38739. this.onlyOnce = onlyOnce;
  38740. this.isDone = false;
  38741. }
  38742. return AnimationEvent;
  38743. }());
  38744. BABYLON.AnimationEvent = AnimationEvent;
  38745. var PathCursor = (function () {
  38746. function PathCursor(path) {
  38747. this.path = path;
  38748. this._onchange = new Array();
  38749. this.value = 0;
  38750. this.animations = new Array();
  38751. }
  38752. PathCursor.prototype.getPoint = function () {
  38753. var point = this.path.getPointAtLengthPosition(this.value);
  38754. return new BABYLON.Vector3(point.x, 0, point.y);
  38755. };
  38756. PathCursor.prototype.moveAhead = function (step) {
  38757. if (step === void 0) { step = 0.002; }
  38758. this.move(step);
  38759. return this;
  38760. };
  38761. PathCursor.prototype.moveBack = function (step) {
  38762. if (step === void 0) { step = 0.002; }
  38763. this.move(-step);
  38764. return this;
  38765. };
  38766. PathCursor.prototype.move = function (step) {
  38767. if (Math.abs(step) > 1) {
  38768. throw "step size should be less than 1.";
  38769. }
  38770. this.value += step;
  38771. this.ensureLimits();
  38772. this.raiseOnChange();
  38773. return this;
  38774. };
  38775. PathCursor.prototype.ensureLimits = function () {
  38776. while (this.value > 1) {
  38777. this.value -= 1;
  38778. }
  38779. while (this.value < 0) {
  38780. this.value += 1;
  38781. }
  38782. return this;
  38783. };
  38784. // used by animation engine
  38785. PathCursor.prototype.raiseOnChange = function () {
  38786. var _this = this;
  38787. this._onchange.forEach(function (f) { return f(_this); });
  38788. return this;
  38789. };
  38790. PathCursor.prototype.onchange = function (f) {
  38791. this._onchange.push(f);
  38792. return this;
  38793. };
  38794. return PathCursor;
  38795. }());
  38796. BABYLON.PathCursor = PathCursor;
  38797. var Animation = (function () {
  38798. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  38799. this.name = name;
  38800. this.targetProperty = targetProperty;
  38801. this.framePerSecond = framePerSecond;
  38802. this.dataType = dataType;
  38803. this.loopMode = loopMode;
  38804. this.enableBlending = enableBlending;
  38805. this._runtimeAnimations = new Array();
  38806. // The set of event that will be linked to this animation
  38807. this._events = new Array();
  38808. this.blendingSpeed = 0.01;
  38809. this._ranges = {};
  38810. this.targetPropertyPath = targetProperty.split(".");
  38811. this.dataType = dataType;
  38812. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  38813. }
  38814. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  38815. var dataType = undefined;
  38816. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  38817. dataType = Animation.ANIMATIONTYPE_FLOAT;
  38818. }
  38819. else if (from instanceof BABYLON.Quaternion) {
  38820. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  38821. }
  38822. else if (from instanceof BABYLON.Vector3) {
  38823. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  38824. }
  38825. else if (from instanceof BABYLON.Vector2) {
  38826. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  38827. }
  38828. else if (from instanceof BABYLON.Color3) {
  38829. dataType = Animation.ANIMATIONTYPE_COLOR3;
  38830. }
  38831. else if (from instanceof BABYLON.Size) {
  38832. dataType = Animation.ANIMATIONTYPE_SIZE;
  38833. }
  38834. if (dataType == undefined) {
  38835. return null;
  38836. }
  38837. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  38838. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  38839. animation.setKeys(keys);
  38840. if (easingFunction !== undefined) {
  38841. animation.setEasingFunction(easingFunction);
  38842. }
  38843. return animation;
  38844. };
  38845. /**
  38846. * Sets up an animation.
  38847. * @param property the property to animate
  38848. * @param animationType the animation type to apply
  38849. * @param easingFunction the easing function used in the animation
  38850. * @returns The created animation
  38851. */
  38852. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  38853. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  38854. animation.setEasingFunction(easingFunction);
  38855. return animation;
  38856. };
  38857. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  38858. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  38859. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  38860. };
  38861. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  38862. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  38863. node.animations.push(animation);
  38864. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  38865. };
  38866. /**
  38867. * Transition property of the Camera to the target Value.
  38868. * @param property The property to transition
  38869. * @param targetValue The target Value of the property
  38870. * @param host The object where the property to animate belongs
  38871. * @param scene Scene used to run the animation
  38872. * @param frameRate Framerate (in frame/s) to use
  38873. * @param transition The transition type we want to use
  38874. * @param duration The duration of the animation, in milliseconds
  38875. * @param onAnimationEnd Call back trigger at the end of the animation.
  38876. */
  38877. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  38878. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  38879. if (duration <= 0) {
  38880. host[property] = targetValue;
  38881. if (onAnimationEnd) {
  38882. onAnimationEnd();
  38883. }
  38884. return null;
  38885. }
  38886. var endFrame = frameRate * (duration / 1000);
  38887. transition.setKeys([{
  38888. frame: 0,
  38889. value: host[property].clone ? host[property].clone() : host[property]
  38890. },
  38891. {
  38892. frame: endFrame,
  38893. value: targetValue
  38894. }]);
  38895. if (!host.animations) {
  38896. host.animations = [];
  38897. }
  38898. host.animations.push(transition);
  38899. var animation = scene.beginAnimation(host, 0, endFrame, false);
  38900. animation.onAnimationEnd = onAnimationEnd;
  38901. return animation;
  38902. };
  38903. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  38904. /**
  38905. * Return the array of runtime animations currently using this animation
  38906. */
  38907. get: function () {
  38908. return this._runtimeAnimations;
  38909. },
  38910. enumerable: true,
  38911. configurable: true
  38912. });
  38913. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  38914. get: function () {
  38915. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  38916. var runtimeAnimation = _a[_i];
  38917. if (!runtimeAnimation.isStopped) {
  38918. return true;
  38919. }
  38920. }
  38921. return false;
  38922. },
  38923. enumerable: true,
  38924. configurable: true
  38925. });
  38926. // Methods
  38927. /**
  38928. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  38929. */
  38930. Animation.prototype.toString = function (fullDetails) {
  38931. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  38932. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  38933. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  38934. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  38935. if (fullDetails) {
  38936. ret += ", Ranges: {";
  38937. var first = true;
  38938. for (var name in this._ranges) {
  38939. if (first) {
  38940. ret += ", ";
  38941. first = false;
  38942. }
  38943. ret += name;
  38944. }
  38945. ret += "}";
  38946. }
  38947. return ret;
  38948. };
  38949. /**
  38950. * Add an event to this animation.
  38951. */
  38952. Animation.prototype.addEvent = function (event) {
  38953. this._events.push(event);
  38954. };
  38955. /**
  38956. * Remove all events found at the given frame
  38957. * @param frame
  38958. */
  38959. Animation.prototype.removeEvents = function (frame) {
  38960. for (var index = 0; index < this._events.length; index++) {
  38961. if (this._events[index].frame === frame) {
  38962. this._events.splice(index, 1);
  38963. index--;
  38964. }
  38965. }
  38966. };
  38967. Animation.prototype.getEvents = function () {
  38968. return this._events;
  38969. };
  38970. Animation.prototype.createRange = function (name, from, to) {
  38971. // check name not already in use; could happen for bones after serialized
  38972. if (!this._ranges[name]) {
  38973. this._ranges[name] = new AnimationRange(name, from, to);
  38974. }
  38975. };
  38976. Animation.prototype.deleteRange = function (name, deleteFrames) {
  38977. if (deleteFrames === void 0) { deleteFrames = true; }
  38978. if (this._ranges[name]) {
  38979. if (deleteFrames) {
  38980. var from = this._ranges[name].from;
  38981. var to = this._ranges[name].to;
  38982. // this loop MUST go high to low for multiple splices to work
  38983. for (var key = this._keys.length - 1; key >= 0; key--) {
  38984. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  38985. this._keys.splice(key, 1);
  38986. }
  38987. }
  38988. }
  38989. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  38990. }
  38991. };
  38992. Animation.prototype.getRange = function (name) {
  38993. return this._ranges[name];
  38994. };
  38995. Animation.prototype.getKeys = function () {
  38996. return this._keys;
  38997. };
  38998. Animation.prototype.getHighestFrame = function () {
  38999. var ret = 0;
  39000. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  39001. if (ret < this._keys[key].frame) {
  39002. ret = this._keys[key].frame;
  39003. }
  39004. }
  39005. return ret;
  39006. };
  39007. Animation.prototype.getEasingFunction = function () {
  39008. return this._easingFunction;
  39009. };
  39010. Animation.prototype.setEasingFunction = function (easingFunction) {
  39011. this._easingFunction = easingFunction;
  39012. };
  39013. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  39014. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  39015. };
  39016. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  39017. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  39018. };
  39019. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  39020. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  39021. };
  39022. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  39023. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  39024. };
  39025. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  39026. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  39027. };
  39028. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  39029. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  39030. };
  39031. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  39032. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  39033. };
  39034. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  39035. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  39036. };
  39037. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  39038. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  39039. };
  39040. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  39041. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  39042. };
  39043. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  39044. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  39045. };
  39046. Animation.prototype.clone = function () {
  39047. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  39048. clone.enableBlending = this.enableBlending;
  39049. clone.blendingSpeed = this.blendingSpeed;
  39050. if (this._keys) {
  39051. clone.setKeys(this._keys);
  39052. }
  39053. if (this._ranges) {
  39054. clone._ranges = {};
  39055. for (var name in this._ranges) {
  39056. clone._ranges[name] = this._ranges[name].clone();
  39057. }
  39058. }
  39059. return clone;
  39060. };
  39061. Animation.prototype.setKeys = function (values) {
  39062. this._keys = values.slice(0);
  39063. };
  39064. Animation.prototype.serialize = function () {
  39065. var serializationObject = {};
  39066. serializationObject.name = this.name;
  39067. serializationObject.property = this.targetProperty;
  39068. serializationObject.framePerSecond = this.framePerSecond;
  39069. serializationObject.dataType = this.dataType;
  39070. serializationObject.loopBehavior = this.loopMode;
  39071. serializationObject.enableBlending = this.enableBlending;
  39072. serializationObject.blendingSpeed = this.blendingSpeed;
  39073. var dataType = this.dataType;
  39074. serializationObject.keys = [];
  39075. var keys = this.getKeys();
  39076. for (var index = 0; index < keys.length; index++) {
  39077. var animationKey = keys[index];
  39078. var key = {};
  39079. key.frame = animationKey.frame;
  39080. switch (dataType) {
  39081. case Animation.ANIMATIONTYPE_FLOAT:
  39082. key.values = [animationKey.value];
  39083. break;
  39084. case Animation.ANIMATIONTYPE_QUATERNION:
  39085. case Animation.ANIMATIONTYPE_MATRIX:
  39086. case Animation.ANIMATIONTYPE_VECTOR3:
  39087. case Animation.ANIMATIONTYPE_COLOR3:
  39088. key.values = animationKey.value.asArray();
  39089. break;
  39090. }
  39091. serializationObject.keys.push(key);
  39092. }
  39093. serializationObject.ranges = [];
  39094. for (var name in this._ranges) {
  39095. var range = {};
  39096. range.name = name;
  39097. range.from = this._ranges[name].from;
  39098. range.to = this._ranges[name].to;
  39099. serializationObject.ranges.push(range);
  39100. }
  39101. return serializationObject;
  39102. };
  39103. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  39104. get: function () {
  39105. return Animation._ANIMATIONTYPE_FLOAT;
  39106. },
  39107. enumerable: true,
  39108. configurable: true
  39109. });
  39110. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  39111. get: function () {
  39112. return Animation._ANIMATIONTYPE_VECTOR3;
  39113. },
  39114. enumerable: true,
  39115. configurable: true
  39116. });
  39117. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  39118. get: function () {
  39119. return Animation._ANIMATIONTYPE_VECTOR2;
  39120. },
  39121. enumerable: true,
  39122. configurable: true
  39123. });
  39124. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  39125. get: function () {
  39126. return Animation._ANIMATIONTYPE_SIZE;
  39127. },
  39128. enumerable: true,
  39129. configurable: true
  39130. });
  39131. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  39132. get: function () {
  39133. return Animation._ANIMATIONTYPE_QUATERNION;
  39134. },
  39135. enumerable: true,
  39136. configurable: true
  39137. });
  39138. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  39139. get: function () {
  39140. return Animation._ANIMATIONTYPE_MATRIX;
  39141. },
  39142. enumerable: true,
  39143. configurable: true
  39144. });
  39145. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  39146. get: function () {
  39147. return Animation._ANIMATIONTYPE_COLOR3;
  39148. },
  39149. enumerable: true,
  39150. configurable: true
  39151. });
  39152. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  39153. get: function () {
  39154. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  39155. },
  39156. enumerable: true,
  39157. configurable: true
  39158. });
  39159. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  39160. get: function () {
  39161. return Animation._ANIMATIONLOOPMODE_CYCLE;
  39162. },
  39163. enumerable: true,
  39164. configurable: true
  39165. });
  39166. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  39167. get: function () {
  39168. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  39169. },
  39170. enumerable: true,
  39171. configurable: true
  39172. });
  39173. Animation.Parse = function (parsedAnimation) {
  39174. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  39175. var dataType = parsedAnimation.dataType;
  39176. var keys = [];
  39177. var data;
  39178. var index;
  39179. if (parsedAnimation.enableBlending) {
  39180. animation.enableBlending = parsedAnimation.enableBlending;
  39181. }
  39182. if (parsedAnimation.blendingSpeed) {
  39183. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  39184. }
  39185. for (index = 0; index < parsedAnimation.keys.length; index++) {
  39186. var key = parsedAnimation.keys[index];
  39187. var inTangent;
  39188. var outTangent;
  39189. switch (dataType) {
  39190. case Animation.ANIMATIONTYPE_FLOAT:
  39191. data = key.values[0];
  39192. if (key.values.length >= 1) {
  39193. inTangent = key.values[1];
  39194. }
  39195. if (key.values.length >= 2) {
  39196. outTangent = key.values[2];
  39197. }
  39198. break;
  39199. case Animation.ANIMATIONTYPE_QUATERNION:
  39200. data = BABYLON.Quaternion.FromArray(key.values);
  39201. if (key.values.length >= 8) {
  39202. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  39203. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  39204. inTangent = _inTangent;
  39205. }
  39206. }
  39207. if (key.values.length >= 12) {
  39208. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  39209. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  39210. outTangent = _outTangent;
  39211. }
  39212. }
  39213. break;
  39214. case Animation.ANIMATIONTYPE_MATRIX:
  39215. data = BABYLON.Matrix.FromArray(key.values);
  39216. break;
  39217. case Animation.ANIMATIONTYPE_COLOR3:
  39218. data = BABYLON.Color3.FromArray(key.values);
  39219. break;
  39220. case Animation.ANIMATIONTYPE_VECTOR3:
  39221. default:
  39222. data = BABYLON.Vector3.FromArray(key.values);
  39223. break;
  39224. }
  39225. var keyData = {};
  39226. keyData.frame = key.frame;
  39227. keyData.value = data;
  39228. if (inTangent != undefined) {
  39229. keyData.inTangent = inTangent;
  39230. }
  39231. if (outTangent != undefined) {
  39232. keyData.outTangent = outTangent;
  39233. }
  39234. keys.push(keyData);
  39235. }
  39236. animation.setKeys(keys);
  39237. if (parsedAnimation.ranges) {
  39238. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  39239. data = parsedAnimation.ranges[index];
  39240. animation.createRange(data.name, data.from, data.to);
  39241. }
  39242. }
  39243. return animation;
  39244. };
  39245. Animation.AppendSerializedAnimations = function (source, destination) {
  39246. if (source.animations) {
  39247. destination.animations = [];
  39248. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  39249. var animation = source.animations[animationIndex];
  39250. destination.animations.push(animation.serialize());
  39251. }
  39252. }
  39253. };
  39254. Animation.AllowMatricesInterpolation = false;
  39255. // Statics
  39256. Animation._ANIMATIONTYPE_FLOAT = 0;
  39257. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  39258. Animation._ANIMATIONTYPE_QUATERNION = 2;
  39259. Animation._ANIMATIONTYPE_MATRIX = 3;
  39260. Animation._ANIMATIONTYPE_COLOR3 = 4;
  39261. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  39262. Animation._ANIMATIONTYPE_SIZE = 6;
  39263. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  39264. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  39265. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  39266. return Animation;
  39267. }());
  39268. BABYLON.Animation = Animation;
  39269. })(BABYLON || (BABYLON = {}));
  39270. //# sourceMappingURL=babylon.animation.js.map
  39271. var BABYLON;
  39272. (function (BABYLON) {
  39273. var RuntimeAnimation = (function () {
  39274. function RuntimeAnimation(target, animation) {
  39275. this._offsetsCache = {};
  39276. this._highLimitsCache = {};
  39277. this._stopped = false;
  39278. this._blendingFactor = 0;
  39279. this._ratioOffset = 0;
  39280. this._animation = animation;
  39281. this._target = target;
  39282. animation._runtimeAnimations.push(this);
  39283. }
  39284. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  39285. get: function () {
  39286. return this._animation;
  39287. },
  39288. enumerable: true,
  39289. configurable: true
  39290. });
  39291. RuntimeAnimation.prototype.reset = function () {
  39292. this._offsetsCache = {};
  39293. this._highLimitsCache = {};
  39294. this.currentFrame = 0;
  39295. this._blendingFactor = 0;
  39296. this._originalBlendValue = null;
  39297. };
  39298. RuntimeAnimation.prototype.isStopped = function () {
  39299. return this._stopped;
  39300. };
  39301. RuntimeAnimation.prototype.dispose = function () {
  39302. var index = this._animation.runtimeAnimations.indexOf(this);
  39303. if (index > -1) {
  39304. this._animation.runtimeAnimations.splice(index, 1);
  39305. }
  39306. };
  39307. RuntimeAnimation.prototype._getKeyValue = function (value) {
  39308. if (typeof value === "function") {
  39309. return value();
  39310. }
  39311. return value;
  39312. };
  39313. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  39314. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  39315. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  39316. }
  39317. this.currentFrame = currentFrame;
  39318. var keys = this._animation.getKeys();
  39319. // Try to get a hash to find the right key
  39320. 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));
  39321. if (keys[startKeyIndex].frame >= currentFrame) {
  39322. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  39323. startKeyIndex--;
  39324. }
  39325. }
  39326. for (var key = startKeyIndex; key < keys.length; key++) {
  39327. var endKey = keys[key + 1];
  39328. if (endKey.frame >= currentFrame) {
  39329. var startKey = keys[key];
  39330. var startValue = this._getKeyValue(startKey.value);
  39331. var endValue = this._getKeyValue(endKey.value);
  39332. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  39333. var frameDelta = endKey.frame - startKey.frame;
  39334. // gradient : percent of currentFrame between the frame inf and the frame sup
  39335. var gradient = (currentFrame - startKey.frame) / frameDelta;
  39336. // check for easingFunction and correction of gradient
  39337. var easingFunction = this._animation.getEasingFunction();
  39338. if (easingFunction != null) {
  39339. gradient = easingFunction.ease(gradient);
  39340. }
  39341. switch (this._animation.dataType) {
  39342. // Float
  39343. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  39344. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  39345. switch (loopMode) {
  39346. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39347. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39348. return floatValue;
  39349. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39350. return offsetValue * repeatCount + floatValue;
  39351. }
  39352. break;
  39353. // Quaternion
  39354. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  39355. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  39356. switch (loopMode) {
  39357. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39358. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39359. return quatValue;
  39360. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39361. return quatValue.add(offsetValue.scale(repeatCount));
  39362. }
  39363. return quatValue;
  39364. // Vector3
  39365. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  39366. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  39367. switch (loopMode) {
  39368. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39369. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39370. return vec3Value;
  39371. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39372. return vec3Value.add(offsetValue.scale(repeatCount));
  39373. }
  39374. // Vector2
  39375. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  39376. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  39377. switch (loopMode) {
  39378. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39379. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39380. return vec2Value;
  39381. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39382. return vec2Value.add(offsetValue.scale(repeatCount));
  39383. }
  39384. // Size
  39385. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  39386. switch (loopMode) {
  39387. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39388. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39389. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  39390. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39391. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  39392. }
  39393. // Color3
  39394. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  39395. switch (loopMode) {
  39396. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39397. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39398. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  39399. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39400. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  39401. }
  39402. // Matrix
  39403. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  39404. switch (loopMode) {
  39405. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39406. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39407. if (BABYLON.Animation.AllowMatricesInterpolation) {
  39408. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  39409. }
  39410. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39411. return startValue;
  39412. }
  39413. default:
  39414. break;
  39415. }
  39416. break;
  39417. }
  39418. }
  39419. return this._getKeyValue(keys[keys.length - 1].value);
  39420. };
  39421. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  39422. if (blend === void 0) { blend = false; }
  39423. // Set value
  39424. var path;
  39425. var destination;
  39426. var targetPropertyPath = this._animation.targetPropertyPath;
  39427. if (targetPropertyPath.length > 1) {
  39428. var property = this._target[targetPropertyPath[0]];
  39429. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  39430. property = property[targetPropertyPath[index]];
  39431. }
  39432. path = targetPropertyPath[targetPropertyPath.length - 1];
  39433. destination = property;
  39434. }
  39435. else {
  39436. path = targetPropertyPath[0];
  39437. destination = this._target;
  39438. }
  39439. // Blending
  39440. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  39441. if (!this._originalBlendValue) {
  39442. if (destination[path].clone) {
  39443. this._originalBlendValue = destination[path].clone();
  39444. }
  39445. else {
  39446. this._originalBlendValue = destination[path];
  39447. }
  39448. }
  39449. if (this._originalBlendValue.prototype) {
  39450. if (this._originalBlendValue.prototype.Lerp) {
  39451. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  39452. }
  39453. else {
  39454. destination[path] = currentValue;
  39455. }
  39456. }
  39457. else if (this._originalBlendValue.m) {
  39458. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  39459. }
  39460. else {
  39461. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  39462. }
  39463. this._blendingFactor += this._animation.blendingSpeed;
  39464. }
  39465. else {
  39466. destination[path] = currentValue;
  39467. }
  39468. if (this._target.markAsDirty) {
  39469. this._target.markAsDirty(this._animation.targetProperty);
  39470. }
  39471. };
  39472. RuntimeAnimation.prototype.goToFrame = function (frame) {
  39473. var keys = this._animation.getKeys();
  39474. if (frame < keys[0].frame) {
  39475. frame = keys[0].frame;
  39476. }
  39477. else if (frame > keys[keys.length - 1].frame) {
  39478. frame = keys[keys.length - 1].frame;
  39479. }
  39480. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  39481. this.setValue(currentValue);
  39482. };
  39483. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  39484. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  39485. this._ratioOffset = this._previousRatio - newRatio;
  39486. };
  39487. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  39488. if (blend === void 0) { blend = false; }
  39489. var targetPropertyPath = this._animation.targetPropertyPath;
  39490. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  39491. this._stopped = true;
  39492. return false;
  39493. }
  39494. var returnValue = true;
  39495. var keys = this._animation.getKeys();
  39496. // Adding a start key at frame 0 if missing
  39497. if (keys[0].frame !== 0) {
  39498. var newKey = { frame: 0, value: keys[0].value };
  39499. keys.splice(0, 0, newKey);
  39500. }
  39501. // Check limits
  39502. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  39503. from = keys[0].frame;
  39504. }
  39505. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  39506. to = keys[keys.length - 1].frame;
  39507. }
  39508. //to and from cannot be the same key
  39509. if (from === to) {
  39510. if (from > keys[0].frame) {
  39511. from--;
  39512. }
  39513. else if (to < keys[keys.length - 1].frame) {
  39514. to++;
  39515. }
  39516. }
  39517. // Compute ratio
  39518. var range = to - from;
  39519. var offsetValue;
  39520. // ratio represents the frame delta between from and to
  39521. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  39522. var highLimitValue = 0;
  39523. this._previousDelay = delay;
  39524. this._previousRatio = ratio;
  39525. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  39526. returnValue = false;
  39527. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  39528. }
  39529. else {
  39530. // Get max value if required
  39531. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  39532. var keyOffset = to.toString() + from.toString();
  39533. if (!this._offsetsCache[keyOffset]) {
  39534. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  39535. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  39536. switch (this._animation.dataType) {
  39537. // Float
  39538. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  39539. this._offsetsCache[keyOffset] = toValue - fromValue;
  39540. break;
  39541. // Quaternion
  39542. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  39543. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  39544. break;
  39545. // Vector3
  39546. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  39547. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  39548. // Vector2
  39549. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  39550. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  39551. // Size
  39552. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  39553. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  39554. // Color3
  39555. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  39556. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  39557. default:
  39558. break;
  39559. }
  39560. this._highLimitsCache[keyOffset] = toValue;
  39561. }
  39562. highLimitValue = this._highLimitsCache[keyOffset];
  39563. offsetValue = this._offsetsCache[keyOffset];
  39564. }
  39565. }
  39566. if (offsetValue === undefined) {
  39567. switch (this._animation.dataType) {
  39568. // Float
  39569. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  39570. offsetValue = 0;
  39571. break;
  39572. // Quaternion
  39573. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  39574. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  39575. break;
  39576. // Vector3
  39577. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  39578. offsetValue = BABYLON.Vector3.Zero();
  39579. break;
  39580. // Vector2
  39581. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  39582. offsetValue = BABYLON.Vector2.Zero();
  39583. break;
  39584. // Size
  39585. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  39586. offsetValue = BABYLON.Size.Zero();
  39587. break;
  39588. // Color3
  39589. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  39590. offsetValue = BABYLON.Color3.Black();
  39591. }
  39592. }
  39593. // Compute value
  39594. var repeatCount = (ratio / range) >> 0;
  39595. var currentFrame = returnValue ? from + ratio % range : to;
  39596. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  39597. // Set value
  39598. this.setValue(currentValue);
  39599. // Check events
  39600. var events = this._animation.getEvents();
  39601. for (var index = 0; index < events.length; index++) {
  39602. // Make sure current frame has passed event frame and that event frame is within the current range
  39603. // Also, handle both forward and reverse animations
  39604. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  39605. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  39606. var event = events[index];
  39607. if (!event.isDone) {
  39608. // If event should be done only once, remove it.
  39609. if (event.onlyOnce) {
  39610. events.splice(index, 1);
  39611. index--;
  39612. }
  39613. event.isDone = true;
  39614. event.action();
  39615. } // Don't do anything if the event has already be done.
  39616. }
  39617. else if (events[index].isDone && !events[index].onlyOnce) {
  39618. // reset event, the animation is looping
  39619. events[index].isDone = false;
  39620. }
  39621. }
  39622. if (!returnValue) {
  39623. this._stopped = true;
  39624. }
  39625. return returnValue;
  39626. };
  39627. return RuntimeAnimation;
  39628. }());
  39629. BABYLON.RuntimeAnimation = RuntimeAnimation;
  39630. })(BABYLON || (BABYLON = {}));
  39631. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  39632. var BABYLON;
  39633. (function (BABYLON) {
  39634. var Animatable = (function () {
  39635. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  39636. if (fromFrame === void 0) { fromFrame = 0; }
  39637. if (toFrame === void 0) { toFrame = 100; }
  39638. if (loopAnimation === void 0) { loopAnimation = false; }
  39639. if (speedRatio === void 0) { speedRatio = 1.0; }
  39640. this.target = target;
  39641. this.fromFrame = fromFrame;
  39642. this.toFrame = toFrame;
  39643. this.loopAnimation = loopAnimation;
  39644. this.onAnimationEnd = onAnimationEnd;
  39645. this._localDelayOffset = null;
  39646. this._pausedDelay = null;
  39647. this._runtimeAnimations = new Array();
  39648. this._paused = false;
  39649. this._speedRatio = 1;
  39650. this.animationStarted = false;
  39651. if (animations) {
  39652. this.appendAnimations(target, animations);
  39653. }
  39654. this._speedRatio = speedRatio;
  39655. this._scene = scene;
  39656. scene._activeAnimatables.push(this);
  39657. }
  39658. Object.defineProperty(Animatable.prototype, "speedRatio", {
  39659. get: function () {
  39660. return this._speedRatio;
  39661. },
  39662. set: function (value) {
  39663. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  39664. var animation = this._runtimeAnimations[index];
  39665. animation._prepareForSpeedRatioChange(value);
  39666. }
  39667. this._speedRatio = value;
  39668. },
  39669. enumerable: true,
  39670. configurable: true
  39671. });
  39672. // Methods
  39673. Animatable.prototype.getAnimations = function () {
  39674. return this._runtimeAnimations;
  39675. };
  39676. Animatable.prototype.appendAnimations = function (target, animations) {
  39677. for (var index = 0; index < animations.length; index++) {
  39678. var animation = animations[index];
  39679. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  39680. }
  39681. };
  39682. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  39683. var runtimeAnimations = this._runtimeAnimations;
  39684. for (var index = 0; index < runtimeAnimations.length; index++) {
  39685. if (runtimeAnimations[index].animation.targetProperty === property) {
  39686. return runtimeAnimations[index].animation;
  39687. }
  39688. }
  39689. return null;
  39690. };
  39691. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  39692. var runtimeAnimations = this._runtimeAnimations;
  39693. for (var index = 0; index < runtimeAnimations.length; index++) {
  39694. if (runtimeAnimations[index].animation.targetProperty === property) {
  39695. return runtimeAnimations[index];
  39696. }
  39697. }
  39698. return null;
  39699. };
  39700. Animatable.prototype.reset = function () {
  39701. var runtimeAnimations = this._runtimeAnimations;
  39702. for (var index = 0; index < runtimeAnimations.length; index++) {
  39703. runtimeAnimations[index].reset();
  39704. }
  39705. this._localDelayOffset = null;
  39706. this._pausedDelay = null;
  39707. };
  39708. Animatable.prototype.enableBlending = function (blendingSpeed) {
  39709. var runtimeAnimations = this._runtimeAnimations;
  39710. for (var index = 0; index < runtimeAnimations.length; index++) {
  39711. runtimeAnimations[index].animation.enableBlending = true;
  39712. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  39713. }
  39714. };
  39715. Animatable.prototype.disableBlending = function () {
  39716. var runtimeAnimations = this._runtimeAnimations;
  39717. for (var index = 0; index < runtimeAnimations.length; index++) {
  39718. runtimeAnimations[index].animation.enableBlending = false;
  39719. }
  39720. };
  39721. Animatable.prototype.goToFrame = function (frame) {
  39722. var runtimeAnimations = this._runtimeAnimations;
  39723. if (runtimeAnimations[0]) {
  39724. var fps = runtimeAnimations[0].animation.framePerSecond;
  39725. var currentFrame = runtimeAnimations[0].currentFrame;
  39726. var adjustTime = frame - currentFrame;
  39727. var delay = adjustTime * 1000 / fps;
  39728. this._localDelayOffset -= delay;
  39729. }
  39730. for (var index = 0; index < runtimeAnimations.length; index++) {
  39731. runtimeAnimations[index].goToFrame(frame);
  39732. }
  39733. };
  39734. Animatable.prototype.pause = function () {
  39735. if (this._paused) {
  39736. return;
  39737. }
  39738. this._paused = true;
  39739. };
  39740. Animatable.prototype.restart = function () {
  39741. this._paused = false;
  39742. };
  39743. Animatable.prototype.stop = function (animationName) {
  39744. if (animationName) {
  39745. var idx = this._scene._activeAnimatables.indexOf(this);
  39746. if (idx > -1) {
  39747. var runtimeAnimations = this._runtimeAnimations;
  39748. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  39749. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  39750. continue;
  39751. }
  39752. runtimeAnimations[index].dispose();
  39753. runtimeAnimations.splice(index, 1);
  39754. }
  39755. if (runtimeAnimations.length == 0) {
  39756. this._scene._activeAnimatables.splice(idx, 1);
  39757. if (this.onAnimationEnd) {
  39758. this.onAnimationEnd();
  39759. }
  39760. }
  39761. }
  39762. }
  39763. else {
  39764. var index = this._scene._activeAnimatables.indexOf(this);
  39765. if (index > -1) {
  39766. this._scene._activeAnimatables.splice(index, 1);
  39767. var runtimeAnimations = this._runtimeAnimations;
  39768. for (var index = 0; index < runtimeAnimations.length; index++) {
  39769. runtimeAnimations[index].dispose();
  39770. }
  39771. if (this.onAnimationEnd) {
  39772. this.onAnimationEnd();
  39773. }
  39774. }
  39775. }
  39776. };
  39777. Animatable.prototype._animate = function (delay) {
  39778. if (this._paused) {
  39779. this.animationStarted = false;
  39780. if (this._pausedDelay === null) {
  39781. this._pausedDelay = delay;
  39782. }
  39783. return true;
  39784. }
  39785. if (this._localDelayOffset === null) {
  39786. this._localDelayOffset = delay;
  39787. }
  39788. else if (this._pausedDelay !== null) {
  39789. this._localDelayOffset += delay - this._pausedDelay;
  39790. this._pausedDelay = null;
  39791. }
  39792. // Animating
  39793. var running = false;
  39794. var runtimeAnimations = this._runtimeAnimations;
  39795. var index;
  39796. for (index = 0; index < runtimeAnimations.length; index++) {
  39797. var animation = runtimeAnimations[index];
  39798. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  39799. running = running || isRunning;
  39800. }
  39801. this.animationStarted = running;
  39802. if (!running) {
  39803. // Remove from active animatables
  39804. index = this._scene._activeAnimatables.indexOf(this);
  39805. this._scene._activeAnimatables.splice(index, 1);
  39806. // Dispose all runtime animations
  39807. for (index = 0; index < runtimeAnimations.length; index++) {
  39808. runtimeAnimations[index].dispose();
  39809. }
  39810. }
  39811. if (!running && this.onAnimationEnd) {
  39812. this.onAnimationEnd();
  39813. this.onAnimationEnd = null;
  39814. }
  39815. return running;
  39816. };
  39817. return Animatable;
  39818. }());
  39819. BABYLON.Animatable = Animatable;
  39820. })(BABYLON || (BABYLON = {}));
  39821. //# sourceMappingURL=babylon.animatable.js.map
  39822. var BABYLON;
  39823. (function (BABYLON) {
  39824. var EasingFunction = (function () {
  39825. function EasingFunction() {
  39826. // Properties
  39827. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  39828. }
  39829. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  39830. get: function () {
  39831. return EasingFunction._EASINGMODE_EASEIN;
  39832. },
  39833. enumerable: true,
  39834. configurable: true
  39835. });
  39836. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  39837. get: function () {
  39838. return EasingFunction._EASINGMODE_EASEOUT;
  39839. },
  39840. enumerable: true,
  39841. configurable: true
  39842. });
  39843. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  39844. get: function () {
  39845. return EasingFunction._EASINGMODE_EASEINOUT;
  39846. },
  39847. enumerable: true,
  39848. configurable: true
  39849. });
  39850. EasingFunction.prototype.setEasingMode = function (easingMode) {
  39851. var n = Math.min(Math.max(easingMode, 0), 2);
  39852. this._easingMode = n;
  39853. };
  39854. EasingFunction.prototype.getEasingMode = function () {
  39855. return this._easingMode;
  39856. };
  39857. EasingFunction.prototype.easeInCore = function (gradient) {
  39858. throw new Error('You must implement this method');
  39859. };
  39860. EasingFunction.prototype.ease = function (gradient) {
  39861. switch (this._easingMode) {
  39862. case EasingFunction.EASINGMODE_EASEIN:
  39863. return this.easeInCore(gradient);
  39864. case EasingFunction.EASINGMODE_EASEOUT:
  39865. return (1 - this.easeInCore(1 - gradient));
  39866. }
  39867. if (gradient >= 0.5) {
  39868. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  39869. }
  39870. return (this.easeInCore(gradient * 2) * 0.5);
  39871. };
  39872. //Statics
  39873. EasingFunction._EASINGMODE_EASEIN = 0;
  39874. EasingFunction._EASINGMODE_EASEOUT = 1;
  39875. EasingFunction._EASINGMODE_EASEINOUT = 2;
  39876. return EasingFunction;
  39877. }());
  39878. BABYLON.EasingFunction = EasingFunction;
  39879. var CircleEase = (function (_super) {
  39880. __extends(CircleEase, _super);
  39881. function CircleEase() {
  39882. return _super !== null && _super.apply(this, arguments) || this;
  39883. }
  39884. CircleEase.prototype.easeInCore = function (gradient) {
  39885. gradient = Math.max(0, Math.min(1, gradient));
  39886. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  39887. };
  39888. return CircleEase;
  39889. }(EasingFunction));
  39890. BABYLON.CircleEase = CircleEase;
  39891. var BackEase = (function (_super) {
  39892. __extends(BackEase, _super);
  39893. function BackEase(amplitude) {
  39894. if (amplitude === void 0) { amplitude = 1; }
  39895. var _this = _super.call(this) || this;
  39896. _this.amplitude = amplitude;
  39897. return _this;
  39898. }
  39899. BackEase.prototype.easeInCore = function (gradient) {
  39900. var num = Math.max(0, this.amplitude);
  39901. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  39902. };
  39903. return BackEase;
  39904. }(EasingFunction));
  39905. BABYLON.BackEase = BackEase;
  39906. var BounceEase = (function (_super) {
  39907. __extends(BounceEase, _super);
  39908. function BounceEase(bounces, bounciness) {
  39909. if (bounces === void 0) { bounces = 3; }
  39910. if (bounciness === void 0) { bounciness = 2; }
  39911. var _this = _super.call(this) || this;
  39912. _this.bounces = bounces;
  39913. _this.bounciness = bounciness;
  39914. return _this;
  39915. }
  39916. BounceEase.prototype.easeInCore = function (gradient) {
  39917. var y = Math.max(0.0, this.bounces);
  39918. var bounciness = this.bounciness;
  39919. if (bounciness <= 1.0) {
  39920. bounciness = 1.001;
  39921. }
  39922. var num9 = Math.pow(bounciness, y);
  39923. var num5 = 1.0 - bounciness;
  39924. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  39925. var num15 = gradient * num4;
  39926. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  39927. var num3 = Math.floor(num65);
  39928. var num13 = num3 + 1.0;
  39929. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  39930. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  39931. var num7 = (num8 + num12) * 0.5;
  39932. var num6 = gradient - num7;
  39933. var num2 = num7 - num8;
  39934. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  39935. };
  39936. return BounceEase;
  39937. }(EasingFunction));
  39938. BABYLON.BounceEase = BounceEase;
  39939. var CubicEase = (function (_super) {
  39940. __extends(CubicEase, _super);
  39941. function CubicEase() {
  39942. return _super !== null && _super.apply(this, arguments) || this;
  39943. }
  39944. CubicEase.prototype.easeInCore = function (gradient) {
  39945. return (gradient * gradient * gradient);
  39946. };
  39947. return CubicEase;
  39948. }(EasingFunction));
  39949. BABYLON.CubicEase = CubicEase;
  39950. var ElasticEase = (function (_super) {
  39951. __extends(ElasticEase, _super);
  39952. function ElasticEase(oscillations, springiness) {
  39953. if (oscillations === void 0) { oscillations = 3; }
  39954. if (springiness === void 0) { springiness = 3; }
  39955. var _this = _super.call(this) || this;
  39956. _this.oscillations = oscillations;
  39957. _this.springiness = springiness;
  39958. return _this;
  39959. }
  39960. ElasticEase.prototype.easeInCore = function (gradient) {
  39961. var num2;
  39962. var num3 = Math.max(0.0, this.oscillations);
  39963. var num = Math.max(0.0, this.springiness);
  39964. if (num == 0) {
  39965. num2 = gradient;
  39966. }
  39967. else {
  39968. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  39969. }
  39970. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  39971. };
  39972. return ElasticEase;
  39973. }(EasingFunction));
  39974. BABYLON.ElasticEase = ElasticEase;
  39975. var ExponentialEase = (function (_super) {
  39976. __extends(ExponentialEase, _super);
  39977. function ExponentialEase(exponent) {
  39978. if (exponent === void 0) { exponent = 2; }
  39979. var _this = _super.call(this) || this;
  39980. _this.exponent = exponent;
  39981. return _this;
  39982. }
  39983. ExponentialEase.prototype.easeInCore = function (gradient) {
  39984. if (this.exponent <= 0) {
  39985. return gradient;
  39986. }
  39987. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  39988. };
  39989. return ExponentialEase;
  39990. }(EasingFunction));
  39991. BABYLON.ExponentialEase = ExponentialEase;
  39992. var PowerEase = (function (_super) {
  39993. __extends(PowerEase, _super);
  39994. function PowerEase(power) {
  39995. if (power === void 0) { power = 2; }
  39996. var _this = _super.call(this) || this;
  39997. _this.power = power;
  39998. return _this;
  39999. }
  40000. PowerEase.prototype.easeInCore = function (gradient) {
  40001. var y = Math.max(0.0, this.power);
  40002. return Math.pow(gradient, y);
  40003. };
  40004. return PowerEase;
  40005. }(EasingFunction));
  40006. BABYLON.PowerEase = PowerEase;
  40007. var QuadraticEase = (function (_super) {
  40008. __extends(QuadraticEase, _super);
  40009. function QuadraticEase() {
  40010. return _super !== null && _super.apply(this, arguments) || this;
  40011. }
  40012. QuadraticEase.prototype.easeInCore = function (gradient) {
  40013. return (gradient * gradient);
  40014. };
  40015. return QuadraticEase;
  40016. }(EasingFunction));
  40017. BABYLON.QuadraticEase = QuadraticEase;
  40018. var QuarticEase = (function (_super) {
  40019. __extends(QuarticEase, _super);
  40020. function QuarticEase() {
  40021. return _super !== null && _super.apply(this, arguments) || this;
  40022. }
  40023. QuarticEase.prototype.easeInCore = function (gradient) {
  40024. return (gradient * gradient * gradient * gradient);
  40025. };
  40026. return QuarticEase;
  40027. }(EasingFunction));
  40028. BABYLON.QuarticEase = QuarticEase;
  40029. var QuinticEase = (function (_super) {
  40030. __extends(QuinticEase, _super);
  40031. function QuinticEase() {
  40032. return _super !== null && _super.apply(this, arguments) || this;
  40033. }
  40034. QuinticEase.prototype.easeInCore = function (gradient) {
  40035. return (gradient * gradient * gradient * gradient * gradient);
  40036. };
  40037. return QuinticEase;
  40038. }(EasingFunction));
  40039. BABYLON.QuinticEase = QuinticEase;
  40040. var SineEase = (function (_super) {
  40041. __extends(SineEase, _super);
  40042. function SineEase() {
  40043. return _super !== null && _super.apply(this, arguments) || this;
  40044. }
  40045. SineEase.prototype.easeInCore = function (gradient) {
  40046. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  40047. };
  40048. return SineEase;
  40049. }(EasingFunction));
  40050. BABYLON.SineEase = SineEase;
  40051. var BezierCurveEase = (function (_super) {
  40052. __extends(BezierCurveEase, _super);
  40053. function BezierCurveEase(x1, y1, x2, y2) {
  40054. if (x1 === void 0) { x1 = 0; }
  40055. if (y1 === void 0) { y1 = 0; }
  40056. if (x2 === void 0) { x2 = 1; }
  40057. if (y2 === void 0) { y2 = 1; }
  40058. var _this = _super.call(this) || this;
  40059. _this.x1 = x1;
  40060. _this.y1 = y1;
  40061. _this.x2 = x2;
  40062. _this.y2 = y2;
  40063. return _this;
  40064. }
  40065. BezierCurveEase.prototype.easeInCore = function (gradient) {
  40066. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  40067. };
  40068. return BezierCurveEase;
  40069. }(EasingFunction));
  40070. BABYLON.BezierCurveEase = BezierCurveEase;
  40071. })(BABYLON || (BABYLON = {}));
  40072. //# sourceMappingURL=babylon.easing.js.map
  40073. var BABYLON;
  40074. (function (BABYLON) {
  40075. var Condition = (function () {
  40076. function Condition(actionManager) {
  40077. this._actionManager = actionManager;
  40078. }
  40079. Condition.prototype.isValid = function () {
  40080. return true;
  40081. };
  40082. Condition.prototype._getProperty = function (propertyPath) {
  40083. return this._actionManager._getProperty(propertyPath);
  40084. };
  40085. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  40086. return this._actionManager._getEffectiveTarget(target, propertyPath);
  40087. };
  40088. Condition.prototype.serialize = function () {
  40089. };
  40090. Condition.prototype._serialize = function (serializedCondition) {
  40091. return {
  40092. type: 2,
  40093. children: [],
  40094. name: serializedCondition.name,
  40095. properties: serializedCondition.properties
  40096. };
  40097. };
  40098. return Condition;
  40099. }());
  40100. BABYLON.Condition = Condition;
  40101. var ValueCondition = (function (_super) {
  40102. __extends(ValueCondition, _super);
  40103. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  40104. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  40105. var _this = _super.call(this, actionManager) || this;
  40106. _this.propertyPath = propertyPath;
  40107. _this.value = value;
  40108. _this.operator = operator;
  40109. _this._target = target;
  40110. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  40111. _this._property = _this._getProperty(_this.propertyPath);
  40112. return _this;
  40113. }
  40114. Object.defineProperty(ValueCondition, "IsEqual", {
  40115. get: function () {
  40116. return ValueCondition._IsEqual;
  40117. },
  40118. enumerable: true,
  40119. configurable: true
  40120. });
  40121. Object.defineProperty(ValueCondition, "IsDifferent", {
  40122. get: function () {
  40123. return ValueCondition._IsDifferent;
  40124. },
  40125. enumerable: true,
  40126. configurable: true
  40127. });
  40128. Object.defineProperty(ValueCondition, "IsGreater", {
  40129. get: function () {
  40130. return ValueCondition._IsGreater;
  40131. },
  40132. enumerable: true,
  40133. configurable: true
  40134. });
  40135. Object.defineProperty(ValueCondition, "IsLesser", {
  40136. get: function () {
  40137. return ValueCondition._IsLesser;
  40138. },
  40139. enumerable: true,
  40140. configurable: true
  40141. });
  40142. // Methods
  40143. ValueCondition.prototype.isValid = function () {
  40144. switch (this.operator) {
  40145. case ValueCondition.IsGreater:
  40146. return this._effectiveTarget[this._property] > this.value;
  40147. case ValueCondition.IsLesser:
  40148. return this._effectiveTarget[this._property] < this.value;
  40149. case ValueCondition.IsEqual:
  40150. case ValueCondition.IsDifferent:
  40151. var check;
  40152. if (this.value.equals) {
  40153. check = this.value.equals(this._effectiveTarget[this._property]);
  40154. }
  40155. else {
  40156. check = this.value === this._effectiveTarget[this._property];
  40157. }
  40158. return this.operator === ValueCondition.IsEqual ? check : !check;
  40159. }
  40160. return false;
  40161. };
  40162. ValueCondition.prototype.serialize = function () {
  40163. return this._serialize({
  40164. name: "ValueCondition",
  40165. properties: [
  40166. BABYLON.Action._GetTargetProperty(this._target),
  40167. { name: "propertyPath", value: this.propertyPath },
  40168. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  40169. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  40170. ]
  40171. });
  40172. };
  40173. ValueCondition.GetOperatorName = function (operator) {
  40174. switch (operator) {
  40175. case ValueCondition._IsEqual: return "IsEqual";
  40176. case ValueCondition._IsDifferent: return "IsDifferent";
  40177. case ValueCondition._IsGreater: return "IsGreater";
  40178. case ValueCondition._IsLesser: return "IsLesser";
  40179. default: return "";
  40180. }
  40181. };
  40182. // Statics
  40183. ValueCondition._IsEqual = 0;
  40184. ValueCondition._IsDifferent = 1;
  40185. ValueCondition._IsGreater = 2;
  40186. ValueCondition._IsLesser = 3;
  40187. return ValueCondition;
  40188. }(Condition));
  40189. BABYLON.ValueCondition = ValueCondition;
  40190. var PredicateCondition = (function (_super) {
  40191. __extends(PredicateCondition, _super);
  40192. function PredicateCondition(actionManager, predicate) {
  40193. var _this = _super.call(this, actionManager) || this;
  40194. _this.predicate = predicate;
  40195. return _this;
  40196. }
  40197. PredicateCondition.prototype.isValid = function () {
  40198. return this.predicate();
  40199. };
  40200. return PredicateCondition;
  40201. }(Condition));
  40202. BABYLON.PredicateCondition = PredicateCondition;
  40203. var StateCondition = (function (_super) {
  40204. __extends(StateCondition, _super);
  40205. function StateCondition(actionManager, target, value) {
  40206. var _this = _super.call(this, actionManager) || this;
  40207. _this.value = value;
  40208. _this._target = target;
  40209. return _this;
  40210. }
  40211. // Methods
  40212. StateCondition.prototype.isValid = function () {
  40213. return this._target.state === this.value;
  40214. };
  40215. StateCondition.prototype.serialize = function () {
  40216. return this._serialize({
  40217. name: "StateCondition",
  40218. properties: [
  40219. BABYLON.Action._GetTargetProperty(this._target),
  40220. { name: "value", value: this.value }
  40221. ]
  40222. });
  40223. };
  40224. return StateCondition;
  40225. }(Condition));
  40226. BABYLON.StateCondition = StateCondition;
  40227. })(BABYLON || (BABYLON = {}));
  40228. //# sourceMappingURL=babylon.condition.js.map
  40229. var BABYLON;
  40230. (function (BABYLON) {
  40231. var Action = (function () {
  40232. function Action(triggerOptions, condition) {
  40233. this.triggerOptions = triggerOptions;
  40234. this.onBeforeExecuteObservable = new BABYLON.Observable();
  40235. if (triggerOptions.parameter) {
  40236. this.trigger = triggerOptions.trigger;
  40237. this._triggerParameter = triggerOptions.parameter;
  40238. }
  40239. else {
  40240. this.trigger = triggerOptions;
  40241. }
  40242. this._nextActiveAction = this;
  40243. this._condition = condition;
  40244. }
  40245. // Methods
  40246. Action.prototype._prepare = function () {
  40247. };
  40248. Action.prototype.getTriggerParameter = function () {
  40249. return this._triggerParameter;
  40250. };
  40251. Action.prototype._executeCurrent = function (evt) {
  40252. if (this._nextActiveAction._condition) {
  40253. var condition = this._nextActiveAction._condition;
  40254. var currentRenderId = this._actionManager.getScene().getRenderId();
  40255. // We cache the current evaluation for the current frame
  40256. if (condition._evaluationId === currentRenderId) {
  40257. if (!condition._currentResult) {
  40258. return;
  40259. }
  40260. }
  40261. else {
  40262. condition._evaluationId = currentRenderId;
  40263. if (!condition.isValid()) {
  40264. condition._currentResult = false;
  40265. return;
  40266. }
  40267. condition._currentResult = true;
  40268. }
  40269. }
  40270. this.onBeforeExecuteObservable.notifyObservers(this);
  40271. this._nextActiveAction.execute(evt);
  40272. this.skipToNextActiveAction();
  40273. };
  40274. Action.prototype.execute = function (evt) {
  40275. };
  40276. Action.prototype.skipToNextActiveAction = function () {
  40277. if (this._nextActiveAction._child) {
  40278. if (!this._nextActiveAction._child._actionManager) {
  40279. this._nextActiveAction._child._actionManager = this._actionManager;
  40280. }
  40281. this._nextActiveAction = this._nextActiveAction._child;
  40282. }
  40283. else {
  40284. this._nextActiveAction = this;
  40285. }
  40286. };
  40287. Action.prototype.then = function (action) {
  40288. this._child = action;
  40289. action._actionManager = this._actionManager;
  40290. action._prepare();
  40291. return action;
  40292. };
  40293. Action.prototype._getProperty = function (propertyPath) {
  40294. return this._actionManager._getProperty(propertyPath);
  40295. };
  40296. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  40297. return this._actionManager._getEffectiveTarget(target, propertyPath);
  40298. };
  40299. Action.prototype.serialize = function (parent) {
  40300. };
  40301. // Called by BABYLON.Action objects in serialize(...). Internal use
  40302. Action.prototype._serialize = function (serializedAction, parent) {
  40303. var serializationObject = {
  40304. type: 1,
  40305. children: [],
  40306. name: serializedAction.name,
  40307. properties: serializedAction.properties || []
  40308. };
  40309. // Serialize child
  40310. if (this._child) {
  40311. this._child.serialize(serializationObject);
  40312. }
  40313. // Check if "this" has a condition
  40314. if (this._condition) {
  40315. var serializedCondition = this._condition.serialize();
  40316. serializedCondition.children.push(serializationObject);
  40317. if (parent) {
  40318. parent.children.push(serializedCondition);
  40319. }
  40320. return serializedCondition;
  40321. }
  40322. if (parent) {
  40323. parent.children.push(serializationObject);
  40324. }
  40325. return serializationObject;
  40326. };
  40327. Action._SerializeValueAsString = function (value) {
  40328. if (typeof value === "number") {
  40329. return value.toString();
  40330. }
  40331. if (typeof value === "boolean") {
  40332. return value ? "true" : "false";
  40333. }
  40334. if (value instanceof BABYLON.Vector2) {
  40335. return value.x + ", " + value.y;
  40336. }
  40337. if (value instanceof BABYLON.Vector3) {
  40338. return value.x + ", " + value.y + ", " + value.z;
  40339. }
  40340. if (value instanceof BABYLON.Color3) {
  40341. return value.r + ", " + value.g + ", " + value.b;
  40342. }
  40343. if (value instanceof BABYLON.Color4) {
  40344. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  40345. }
  40346. return value; // string
  40347. };
  40348. Action._GetTargetProperty = function (target) {
  40349. return {
  40350. name: "target",
  40351. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  40352. : target instanceof BABYLON.Light ? "LightProperties"
  40353. : target instanceof BABYLON.Camera ? "CameraProperties"
  40354. : "SceneProperties",
  40355. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  40356. };
  40357. };
  40358. return Action;
  40359. }());
  40360. BABYLON.Action = Action;
  40361. })(BABYLON || (BABYLON = {}));
  40362. //# sourceMappingURL=babylon.action.js.map
  40363. var BABYLON;
  40364. (function (BABYLON) {
  40365. /**
  40366. * ActionEvent is the event beint sent when an action is triggered.
  40367. */
  40368. var ActionEvent = (function () {
  40369. /**
  40370. * @param source The mesh or sprite that triggered the action.
  40371. * @param pointerX The X mouse cursor position at the time of the event
  40372. * @param pointerY The Y mouse cursor position at the time of the event
  40373. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  40374. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  40375. */
  40376. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  40377. this.source = source;
  40378. this.pointerX = pointerX;
  40379. this.pointerY = pointerY;
  40380. this.meshUnderPointer = meshUnderPointer;
  40381. this.sourceEvent = sourceEvent;
  40382. this.additionalData = additionalData;
  40383. }
  40384. /**
  40385. * Helper function to auto-create an ActionEvent from a source mesh.
  40386. * @param source The source mesh that triggered the event
  40387. * @param evt {Event} The original (browser) event
  40388. */
  40389. ActionEvent.CreateNew = function (source, evt, additionalData) {
  40390. var scene = source.getScene();
  40391. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  40392. };
  40393. /**
  40394. * Helper function to auto-create an ActionEvent from a source mesh.
  40395. * @param source The source sprite that triggered the event
  40396. * @param scene Scene associated with the sprite
  40397. * @param evt {Event} The original (browser) event
  40398. */
  40399. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  40400. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  40401. };
  40402. /**
  40403. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  40404. * @param scene the scene where the event occurred
  40405. * @param evt {Event} The original (browser) event
  40406. */
  40407. ActionEvent.CreateNewFromScene = function (scene, evt) {
  40408. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  40409. };
  40410. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  40411. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  40412. };
  40413. return ActionEvent;
  40414. }());
  40415. BABYLON.ActionEvent = ActionEvent;
  40416. /**
  40417. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  40418. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  40419. */
  40420. var ActionManager = (function () {
  40421. function ActionManager(scene) {
  40422. // Members
  40423. this.actions = new Array();
  40424. this.hoverCursor = '';
  40425. this._scene = scene;
  40426. scene._actionManagers.push(this);
  40427. }
  40428. Object.defineProperty(ActionManager, "NothingTrigger", {
  40429. get: function () {
  40430. return ActionManager._NothingTrigger;
  40431. },
  40432. enumerable: true,
  40433. configurable: true
  40434. });
  40435. Object.defineProperty(ActionManager, "OnPickTrigger", {
  40436. get: function () {
  40437. return ActionManager._OnPickTrigger;
  40438. },
  40439. enumerable: true,
  40440. configurable: true
  40441. });
  40442. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  40443. get: function () {
  40444. return ActionManager._OnLeftPickTrigger;
  40445. },
  40446. enumerable: true,
  40447. configurable: true
  40448. });
  40449. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  40450. get: function () {
  40451. return ActionManager._OnRightPickTrigger;
  40452. },
  40453. enumerable: true,
  40454. configurable: true
  40455. });
  40456. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  40457. get: function () {
  40458. return ActionManager._OnCenterPickTrigger;
  40459. },
  40460. enumerable: true,
  40461. configurable: true
  40462. });
  40463. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  40464. get: function () {
  40465. return ActionManager._OnPickDownTrigger;
  40466. },
  40467. enumerable: true,
  40468. configurable: true
  40469. });
  40470. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  40471. get: function () {
  40472. return ActionManager._OnDoublePickTrigger;
  40473. },
  40474. enumerable: true,
  40475. configurable: true
  40476. });
  40477. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  40478. get: function () {
  40479. return ActionManager._OnPickUpTrigger;
  40480. },
  40481. enumerable: true,
  40482. configurable: true
  40483. });
  40484. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  40485. /// This trigger will only be raised if you also declared a OnPickDown
  40486. get: function () {
  40487. return ActionManager._OnPickOutTrigger;
  40488. },
  40489. enumerable: true,
  40490. configurable: true
  40491. });
  40492. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  40493. get: function () {
  40494. return ActionManager._OnLongPressTrigger;
  40495. },
  40496. enumerable: true,
  40497. configurable: true
  40498. });
  40499. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  40500. get: function () {
  40501. return ActionManager._OnPointerOverTrigger;
  40502. },
  40503. enumerable: true,
  40504. configurable: true
  40505. });
  40506. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  40507. get: function () {
  40508. return ActionManager._OnPointerOutTrigger;
  40509. },
  40510. enumerable: true,
  40511. configurable: true
  40512. });
  40513. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  40514. get: function () {
  40515. return ActionManager._OnEveryFrameTrigger;
  40516. },
  40517. enumerable: true,
  40518. configurable: true
  40519. });
  40520. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  40521. get: function () {
  40522. return ActionManager._OnIntersectionEnterTrigger;
  40523. },
  40524. enumerable: true,
  40525. configurable: true
  40526. });
  40527. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  40528. get: function () {
  40529. return ActionManager._OnIntersectionExitTrigger;
  40530. },
  40531. enumerable: true,
  40532. configurable: true
  40533. });
  40534. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  40535. get: function () {
  40536. return ActionManager._OnKeyDownTrigger;
  40537. },
  40538. enumerable: true,
  40539. configurable: true
  40540. });
  40541. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  40542. get: function () {
  40543. return ActionManager._OnKeyUpTrigger;
  40544. },
  40545. enumerable: true,
  40546. configurable: true
  40547. });
  40548. // Methods
  40549. ActionManager.prototype.dispose = function () {
  40550. var index = this._scene._actionManagers.indexOf(this);
  40551. for (var i = 0; i < this.actions.length; i++) {
  40552. var action = this.actions[i];
  40553. ActionManager.Triggers[action.trigger]--;
  40554. if (ActionManager.Triggers[action.trigger] === 0) {
  40555. delete ActionManager.Triggers[action.trigger];
  40556. }
  40557. }
  40558. if (index > -1) {
  40559. this._scene._actionManagers.splice(index, 1);
  40560. }
  40561. };
  40562. ActionManager.prototype.getScene = function () {
  40563. return this._scene;
  40564. };
  40565. /**
  40566. * Does this action manager handles actions of any of the given triggers
  40567. * @param {number[]} triggers - the triggers to be tested
  40568. * @return {boolean} whether one (or more) of the triggers is handeled
  40569. */
  40570. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  40571. for (var index = 0; index < this.actions.length; index++) {
  40572. var action = this.actions[index];
  40573. if (triggers.indexOf(action.trigger) > -1) {
  40574. return true;
  40575. }
  40576. }
  40577. return false;
  40578. };
  40579. /**
  40580. * Does this action manager handles actions of a given trigger
  40581. * @param {number} trigger - the trigger to be tested
  40582. * @return {boolean} whether the trigger is handeled
  40583. */
  40584. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  40585. for (var index = 0; index < this.actions.length; index++) {
  40586. var action = this.actions[index];
  40587. if (action.trigger === trigger) {
  40588. return true;
  40589. }
  40590. }
  40591. return false;
  40592. };
  40593. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  40594. /**
  40595. * Does this action manager has pointer triggers
  40596. * @return {boolean} whether or not it has pointer triggers
  40597. */
  40598. get: function () {
  40599. for (var index = 0; index < this.actions.length; index++) {
  40600. var action = this.actions[index];
  40601. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  40602. return true;
  40603. }
  40604. }
  40605. return false;
  40606. },
  40607. enumerable: true,
  40608. configurable: true
  40609. });
  40610. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  40611. /**
  40612. * Does this action manager has pick triggers
  40613. * @return {boolean} whether or not it has pick triggers
  40614. */
  40615. get: function () {
  40616. for (var index = 0; index < this.actions.length; index++) {
  40617. var action = this.actions[index];
  40618. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  40619. return true;
  40620. }
  40621. }
  40622. return false;
  40623. },
  40624. enumerable: true,
  40625. configurable: true
  40626. });
  40627. Object.defineProperty(ActionManager, "HasTriggers", {
  40628. /**
  40629. * Does exist one action manager with at least one trigger
  40630. * @return {boolean} whether or not it exists one action manager with one trigger
  40631. **/
  40632. get: function () {
  40633. for (var t in ActionManager.Triggers) {
  40634. if (ActionManager.Triggers.hasOwnProperty(t)) {
  40635. return true;
  40636. }
  40637. }
  40638. return false;
  40639. },
  40640. enumerable: true,
  40641. configurable: true
  40642. });
  40643. Object.defineProperty(ActionManager, "HasPickTriggers", {
  40644. /**
  40645. * Does exist one action manager with at least one pick trigger
  40646. * @return {boolean} whether or not it exists one action manager with one pick trigger
  40647. **/
  40648. get: function () {
  40649. for (var t in ActionManager.Triggers) {
  40650. if (ActionManager.Triggers.hasOwnProperty(t)) {
  40651. var t_int = parseInt(t);
  40652. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  40653. return true;
  40654. }
  40655. }
  40656. }
  40657. return false;
  40658. },
  40659. enumerable: true,
  40660. configurable: true
  40661. });
  40662. /**
  40663. * Does exist one action manager that handles actions of a given trigger
  40664. * @param {number} trigger - the trigger to be tested
  40665. * @return {boolean} whether the trigger is handeled by at least one action manager
  40666. **/
  40667. ActionManager.HasSpecificTrigger = function (trigger) {
  40668. for (var t in ActionManager.Triggers) {
  40669. if (ActionManager.Triggers.hasOwnProperty(t)) {
  40670. var t_int = parseInt(t);
  40671. if (t_int === trigger) {
  40672. return true;
  40673. }
  40674. }
  40675. }
  40676. return false;
  40677. };
  40678. /**
  40679. * Registers an action to this action manager
  40680. * @param {BABYLON.Action} action - the action to be registered
  40681. * @return {BABYLON.Action} the action amended (prepared) after registration
  40682. */
  40683. ActionManager.prototype.registerAction = function (action) {
  40684. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  40685. if (this.getScene().actionManager !== this) {
  40686. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  40687. return null;
  40688. }
  40689. }
  40690. this.actions.push(action);
  40691. if (ActionManager.Triggers[action.trigger]) {
  40692. ActionManager.Triggers[action.trigger]++;
  40693. }
  40694. else {
  40695. ActionManager.Triggers[action.trigger] = 1;
  40696. }
  40697. action._actionManager = this;
  40698. action._prepare();
  40699. return action;
  40700. };
  40701. /**
  40702. * Process a specific trigger
  40703. * @param {number} trigger - the trigger to process
  40704. * @param evt {BABYLON.ActionEvent} the event details to be processed
  40705. */
  40706. ActionManager.prototype.processTrigger = function (trigger, evt) {
  40707. for (var index = 0; index < this.actions.length; index++) {
  40708. var action = this.actions[index];
  40709. if (action.trigger === trigger) {
  40710. if (trigger === ActionManager.OnKeyUpTrigger
  40711. || trigger === ActionManager.OnKeyDownTrigger) {
  40712. var parameter = action.getTriggerParameter();
  40713. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  40714. if (!parameter.toLowerCase) {
  40715. continue;
  40716. }
  40717. var lowerCase = parameter.toLowerCase();
  40718. if (lowerCase !== evt.sourceEvent.key) {
  40719. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  40720. var actualkey = String.fromCharCode(unicode).toLowerCase();
  40721. if (actualkey !== lowerCase) {
  40722. continue;
  40723. }
  40724. }
  40725. }
  40726. }
  40727. action._executeCurrent(evt);
  40728. }
  40729. }
  40730. };
  40731. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  40732. var properties = propertyPath.split(".");
  40733. for (var index = 0; index < properties.length - 1; index++) {
  40734. target = target[properties[index]];
  40735. }
  40736. return target;
  40737. };
  40738. ActionManager.prototype._getProperty = function (propertyPath) {
  40739. var properties = propertyPath.split(".");
  40740. return properties[properties.length - 1];
  40741. };
  40742. ActionManager.prototype.serialize = function (name) {
  40743. var root = {
  40744. children: new Array(),
  40745. name: name,
  40746. type: 3,
  40747. properties: new Array() // Empty for root but required
  40748. };
  40749. for (var i = 0; i < this.actions.length; i++) {
  40750. var triggerObject = {
  40751. type: 0,
  40752. children: new Array(),
  40753. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  40754. properties: new Array()
  40755. };
  40756. var triggerOptions = this.actions[i].triggerOptions;
  40757. if (triggerOptions && typeof triggerOptions !== "number") {
  40758. if (triggerOptions.parameter instanceof BABYLON.Node) {
  40759. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  40760. }
  40761. else {
  40762. var parameter = {};
  40763. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  40764. if (triggerOptions.parameter.mesh) {
  40765. parameter._meshId = triggerOptions.parameter.mesh.id;
  40766. }
  40767. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  40768. }
  40769. }
  40770. // Serialize child action, recursively
  40771. this.actions[i].serialize(triggerObject);
  40772. // Add serialized trigger
  40773. root.children.push(triggerObject);
  40774. }
  40775. return root;
  40776. };
  40777. ActionManager.Parse = function (parsedActions, object, scene) {
  40778. var actionManager = new BABYLON.ActionManager(scene);
  40779. if (object === null)
  40780. scene.actionManager = actionManager;
  40781. else
  40782. object.actionManager = actionManager;
  40783. // instanciate a new object
  40784. var instanciate = function (name, params) {
  40785. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  40786. newInstance.constructor.apply(newInstance, params);
  40787. return newInstance;
  40788. };
  40789. var parseParameter = function (name, value, target, propertyPath) {
  40790. if (propertyPath === null) {
  40791. // String, boolean or float
  40792. var floatValue = parseFloat(value);
  40793. if (value === "true" || value === "false")
  40794. return value === "true";
  40795. else
  40796. return isNaN(floatValue) ? value : floatValue;
  40797. }
  40798. var effectiveTarget = propertyPath.split(".");
  40799. var values = value.split(",");
  40800. // Get effective Target
  40801. for (var i = 0; i < effectiveTarget.length; i++) {
  40802. target = target[effectiveTarget[i]];
  40803. }
  40804. // Return appropriate value with its type
  40805. if (typeof (target) === "boolean")
  40806. return values[0] === "true";
  40807. if (typeof (target) === "string")
  40808. return values[0];
  40809. // Parameters with multiple values such as Vector3 etc.
  40810. var split = new Array();
  40811. for (var i = 0; i < values.length; i++)
  40812. split.push(parseFloat(values[i]));
  40813. if (target instanceof BABYLON.Vector3)
  40814. return BABYLON.Vector3.FromArray(split);
  40815. if (target instanceof BABYLON.Vector4)
  40816. return BABYLON.Vector4.FromArray(split);
  40817. if (target instanceof BABYLON.Color3)
  40818. return BABYLON.Color3.FromArray(split);
  40819. if (target instanceof BABYLON.Color4)
  40820. return BABYLON.Color4.FromArray(split);
  40821. return parseFloat(values[0]);
  40822. };
  40823. // traverse graph per trigger
  40824. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  40825. if (combineArray === void 0) { combineArray = null; }
  40826. if (parsedAction.detached)
  40827. return;
  40828. var parameters = new Array();
  40829. var target = null;
  40830. var propertyPath = null;
  40831. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  40832. // Parameters
  40833. if (parsedAction.type === 2)
  40834. parameters.push(actionManager);
  40835. else
  40836. parameters.push(trigger);
  40837. if (combine) {
  40838. var actions = new Array();
  40839. for (var j = 0; j < parsedAction.combine.length; j++) {
  40840. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  40841. }
  40842. parameters.push(actions);
  40843. }
  40844. else {
  40845. for (var i = 0; i < parsedAction.properties.length; i++) {
  40846. var value = parsedAction.properties[i].value;
  40847. var name = parsedAction.properties[i].name;
  40848. var targetType = parsedAction.properties[i].targetType;
  40849. if (name === "target")
  40850. if (targetType !== null && targetType === "SceneProperties")
  40851. value = target = scene;
  40852. else
  40853. value = target = scene.getNodeByName(value);
  40854. else if (name === "parent")
  40855. value = scene.getNodeByName(value);
  40856. else if (name === "sound")
  40857. value = scene.getSoundByName(value);
  40858. else if (name !== "propertyPath") {
  40859. if (parsedAction.type === 2 && name === "operator")
  40860. value = BABYLON.ValueCondition[value];
  40861. else
  40862. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  40863. }
  40864. else {
  40865. propertyPath = value;
  40866. }
  40867. parameters.push(value);
  40868. }
  40869. }
  40870. if (combineArray === null) {
  40871. parameters.push(condition);
  40872. }
  40873. else {
  40874. parameters.push(null);
  40875. }
  40876. // If interpolate value action
  40877. if (parsedAction.name === "InterpolateValueAction") {
  40878. var param = parameters[parameters.length - 2];
  40879. parameters[parameters.length - 1] = param;
  40880. parameters[parameters.length - 2] = condition;
  40881. }
  40882. // Action or condition(s) and not CombineAction
  40883. var newAction = instanciate(parsedAction.name, parameters);
  40884. if (newAction instanceof BABYLON.Condition && condition !== null) {
  40885. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  40886. if (action)
  40887. action.then(nothing);
  40888. else
  40889. actionManager.registerAction(nothing);
  40890. action = nothing;
  40891. }
  40892. if (combineArray === null) {
  40893. if (newAction instanceof BABYLON.Condition) {
  40894. condition = newAction;
  40895. newAction = action;
  40896. }
  40897. else {
  40898. condition = null;
  40899. if (action)
  40900. action.then(newAction);
  40901. else
  40902. actionManager.registerAction(newAction);
  40903. }
  40904. }
  40905. else {
  40906. combineArray.push(newAction);
  40907. }
  40908. for (var i = 0; i < parsedAction.children.length; i++)
  40909. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  40910. };
  40911. // triggers
  40912. for (var i = 0; i < parsedActions.children.length; i++) {
  40913. var triggerParams;
  40914. var trigger = parsedActions.children[i];
  40915. if (trigger.properties.length > 0) {
  40916. var param = trigger.properties[0].value;
  40917. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  40918. if (value._meshId) {
  40919. value.mesh = scene.getMeshByID(value._meshId);
  40920. }
  40921. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  40922. }
  40923. else
  40924. triggerParams = ActionManager[trigger.name];
  40925. for (var j = 0; j < trigger.children.length; j++) {
  40926. if (!trigger.detached)
  40927. traverse(trigger.children[j], triggerParams, null, null);
  40928. }
  40929. }
  40930. };
  40931. ActionManager.GetTriggerName = function (trigger) {
  40932. switch (trigger) {
  40933. case 0: return "NothingTrigger";
  40934. case 1: return "OnPickTrigger";
  40935. case 2: return "OnLeftPickTrigger";
  40936. case 3: return "OnRightPickTrigger";
  40937. case 4: return "OnCenterPickTrigger";
  40938. case 5: return "OnPickDownTrigger";
  40939. case 6: return "OnPickUpTrigger";
  40940. case 7: return "OnLongPressTrigger";
  40941. case 8: return "OnPointerOverTrigger";
  40942. case 9: return "OnPointerOutTrigger";
  40943. case 10: return "OnEveryFrameTrigger";
  40944. case 11: return "OnIntersectionEnterTrigger";
  40945. case 12: return "OnIntersectionExitTrigger";
  40946. case 13: return "OnKeyDownTrigger";
  40947. case 14: return "OnKeyUpTrigger";
  40948. case 15: return "OnPickOutTrigger";
  40949. default: return "";
  40950. }
  40951. };
  40952. // Statics
  40953. ActionManager._NothingTrigger = 0;
  40954. ActionManager._OnPickTrigger = 1;
  40955. ActionManager._OnLeftPickTrigger = 2;
  40956. ActionManager._OnRightPickTrigger = 3;
  40957. ActionManager._OnCenterPickTrigger = 4;
  40958. ActionManager._OnPickDownTrigger = 5;
  40959. ActionManager._OnDoublePickTrigger = 6;
  40960. ActionManager._OnPickUpTrigger = 7;
  40961. ActionManager._OnLongPressTrigger = 8;
  40962. ActionManager._OnPointerOverTrigger = 9;
  40963. ActionManager._OnPointerOutTrigger = 10;
  40964. ActionManager._OnEveryFrameTrigger = 11;
  40965. ActionManager._OnIntersectionEnterTrigger = 12;
  40966. ActionManager._OnIntersectionExitTrigger = 13;
  40967. ActionManager._OnKeyDownTrigger = 14;
  40968. ActionManager._OnKeyUpTrigger = 15;
  40969. ActionManager._OnPickOutTrigger = 16;
  40970. ActionManager.Triggers = {};
  40971. return ActionManager;
  40972. }());
  40973. BABYLON.ActionManager = ActionManager;
  40974. })(BABYLON || (BABYLON = {}));
  40975. //# sourceMappingURL=babylon.actionManager.js.map
  40976. var BABYLON;
  40977. (function (BABYLON) {
  40978. var InterpolateValueAction = (function (_super) {
  40979. __extends(InterpolateValueAction, _super);
  40980. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  40981. if (duration === void 0) { duration = 1000; }
  40982. var _this = _super.call(this, triggerOptions, condition) || this;
  40983. _this.propertyPath = propertyPath;
  40984. _this.value = value;
  40985. _this.duration = duration;
  40986. _this.stopOtherAnimations = stopOtherAnimations;
  40987. _this.onInterpolationDone = onInterpolationDone;
  40988. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  40989. _this._target = _this._effectiveTarget = target;
  40990. return _this;
  40991. }
  40992. InterpolateValueAction.prototype._prepare = function () {
  40993. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40994. this._property = this._getProperty(this.propertyPath);
  40995. };
  40996. InterpolateValueAction.prototype.execute = function () {
  40997. var _this = this;
  40998. var scene = this._actionManager.getScene();
  40999. var keys = [
  41000. {
  41001. frame: 0,
  41002. value: this._effectiveTarget[this._property]
  41003. }, {
  41004. frame: 100,
  41005. value: this.value
  41006. }
  41007. ];
  41008. var dataType;
  41009. if (typeof this.value === "number") {
  41010. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  41011. }
  41012. else if (this.value instanceof BABYLON.Color3) {
  41013. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  41014. }
  41015. else if (this.value instanceof BABYLON.Vector3) {
  41016. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  41017. }
  41018. else if (this.value instanceof BABYLON.Matrix) {
  41019. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  41020. }
  41021. else if (this.value instanceof BABYLON.Quaternion) {
  41022. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  41023. }
  41024. else {
  41025. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  41026. return;
  41027. }
  41028. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  41029. animation.setKeys(keys);
  41030. if (this.stopOtherAnimations) {
  41031. scene.stopAnimation(this._effectiveTarget);
  41032. }
  41033. var wrapper = function () {
  41034. _this.onInterpolationDoneObservable.notifyObservers(_this);
  41035. if (_this.onInterpolationDone) {
  41036. _this.onInterpolationDone();
  41037. }
  41038. };
  41039. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  41040. };
  41041. InterpolateValueAction.prototype.serialize = function (parent) {
  41042. return _super.prototype._serialize.call(this, {
  41043. name: "InterpolateValueAction",
  41044. properties: [
  41045. BABYLON.Action._GetTargetProperty(this._target),
  41046. { name: "propertyPath", value: this.propertyPath },
  41047. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  41048. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  41049. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  41050. ]
  41051. }, parent);
  41052. };
  41053. return InterpolateValueAction;
  41054. }(BABYLON.Action));
  41055. BABYLON.InterpolateValueAction = InterpolateValueAction;
  41056. })(BABYLON || (BABYLON = {}));
  41057. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  41058. var BABYLON;
  41059. (function (BABYLON) {
  41060. var SwitchBooleanAction = (function (_super) {
  41061. __extends(SwitchBooleanAction, _super);
  41062. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  41063. var _this = _super.call(this, triggerOptions, condition) || this;
  41064. _this.propertyPath = propertyPath;
  41065. _this._target = _this._effectiveTarget = target;
  41066. return _this;
  41067. }
  41068. SwitchBooleanAction.prototype._prepare = function () {
  41069. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  41070. this._property = this._getProperty(this.propertyPath);
  41071. };
  41072. SwitchBooleanAction.prototype.execute = function () {
  41073. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  41074. };
  41075. SwitchBooleanAction.prototype.serialize = function (parent) {
  41076. return _super.prototype._serialize.call(this, {
  41077. name: "SwitchBooleanAction",
  41078. properties: [
  41079. BABYLON.Action._GetTargetProperty(this._target),
  41080. { name: "propertyPath", value: this.propertyPath }
  41081. ]
  41082. }, parent);
  41083. };
  41084. return SwitchBooleanAction;
  41085. }(BABYLON.Action));
  41086. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  41087. var SetStateAction = (function (_super) {
  41088. __extends(SetStateAction, _super);
  41089. function SetStateAction(triggerOptions, target, value, condition) {
  41090. var _this = _super.call(this, triggerOptions, condition) || this;
  41091. _this.value = value;
  41092. _this._target = target;
  41093. return _this;
  41094. }
  41095. SetStateAction.prototype.execute = function () {
  41096. this._target.state = this.value;
  41097. };
  41098. SetStateAction.prototype.serialize = function (parent) {
  41099. return _super.prototype._serialize.call(this, {
  41100. name: "SetStateAction",
  41101. properties: [
  41102. BABYLON.Action._GetTargetProperty(this._target),
  41103. { name: "value", value: this.value }
  41104. ]
  41105. }, parent);
  41106. };
  41107. return SetStateAction;
  41108. }(BABYLON.Action));
  41109. BABYLON.SetStateAction = SetStateAction;
  41110. var SetValueAction = (function (_super) {
  41111. __extends(SetValueAction, _super);
  41112. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  41113. var _this = _super.call(this, triggerOptions, condition) || this;
  41114. _this.propertyPath = propertyPath;
  41115. _this.value = value;
  41116. _this._target = _this._effectiveTarget = target;
  41117. return _this;
  41118. }
  41119. SetValueAction.prototype._prepare = function () {
  41120. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  41121. this._property = this._getProperty(this.propertyPath);
  41122. };
  41123. SetValueAction.prototype.execute = function () {
  41124. this._effectiveTarget[this._property] = this.value;
  41125. if (this._target.markAsDirty) {
  41126. this._target.markAsDirty(this._property);
  41127. }
  41128. };
  41129. SetValueAction.prototype.serialize = function (parent) {
  41130. return _super.prototype._serialize.call(this, {
  41131. name: "SetValueAction",
  41132. properties: [
  41133. BABYLON.Action._GetTargetProperty(this._target),
  41134. { name: "propertyPath", value: this.propertyPath },
  41135. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  41136. ]
  41137. }, parent);
  41138. };
  41139. return SetValueAction;
  41140. }(BABYLON.Action));
  41141. BABYLON.SetValueAction = SetValueAction;
  41142. var IncrementValueAction = (function (_super) {
  41143. __extends(IncrementValueAction, _super);
  41144. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  41145. var _this = _super.call(this, triggerOptions, condition) || this;
  41146. _this.propertyPath = propertyPath;
  41147. _this.value = value;
  41148. _this._target = _this._effectiveTarget = target;
  41149. return _this;
  41150. }
  41151. IncrementValueAction.prototype._prepare = function () {
  41152. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  41153. this._property = this._getProperty(this.propertyPath);
  41154. if (typeof this._effectiveTarget[this._property] !== "number") {
  41155. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  41156. }
  41157. };
  41158. IncrementValueAction.prototype.execute = function () {
  41159. this._effectiveTarget[this._property] += this.value;
  41160. if (this._target.markAsDirty) {
  41161. this._target.markAsDirty(this._property);
  41162. }
  41163. };
  41164. IncrementValueAction.prototype.serialize = function (parent) {
  41165. return _super.prototype._serialize.call(this, {
  41166. name: "IncrementValueAction",
  41167. properties: [
  41168. BABYLON.Action._GetTargetProperty(this._target),
  41169. { name: "propertyPath", value: this.propertyPath },
  41170. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  41171. ]
  41172. }, parent);
  41173. };
  41174. return IncrementValueAction;
  41175. }(BABYLON.Action));
  41176. BABYLON.IncrementValueAction = IncrementValueAction;
  41177. var PlayAnimationAction = (function (_super) {
  41178. __extends(PlayAnimationAction, _super);
  41179. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  41180. var _this = _super.call(this, triggerOptions, condition) || this;
  41181. _this.from = from;
  41182. _this.to = to;
  41183. _this.loop = loop;
  41184. _this._target = target;
  41185. return _this;
  41186. }
  41187. PlayAnimationAction.prototype._prepare = function () {
  41188. };
  41189. PlayAnimationAction.prototype.execute = function () {
  41190. var scene = this._actionManager.getScene();
  41191. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  41192. };
  41193. PlayAnimationAction.prototype.serialize = function (parent) {
  41194. return _super.prototype._serialize.call(this, {
  41195. name: "PlayAnimationAction",
  41196. properties: [
  41197. BABYLON.Action._GetTargetProperty(this._target),
  41198. { name: "from", value: String(this.from) },
  41199. { name: "to", value: String(this.to) },
  41200. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  41201. ]
  41202. }, parent);
  41203. };
  41204. return PlayAnimationAction;
  41205. }(BABYLON.Action));
  41206. BABYLON.PlayAnimationAction = PlayAnimationAction;
  41207. var StopAnimationAction = (function (_super) {
  41208. __extends(StopAnimationAction, _super);
  41209. function StopAnimationAction(triggerOptions, target, condition) {
  41210. var _this = _super.call(this, triggerOptions, condition) || this;
  41211. _this._target = target;
  41212. return _this;
  41213. }
  41214. StopAnimationAction.prototype._prepare = function () {
  41215. };
  41216. StopAnimationAction.prototype.execute = function () {
  41217. var scene = this._actionManager.getScene();
  41218. scene.stopAnimation(this._target);
  41219. };
  41220. StopAnimationAction.prototype.serialize = function (parent) {
  41221. return _super.prototype._serialize.call(this, {
  41222. name: "StopAnimationAction",
  41223. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  41224. }, parent);
  41225. };
  41226. return StopAnimationAction;
  41227. }(BABYLON.Action));
  41228. BABYLON.StopAnimationAction = StopAnimationAction;
  41229. var DoNothingAction = (function (_super) {
  41230. __extends(DoNothingAction, _super);
  41231. function DoNothingAction(triggerOptions, condition) {
  41232. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  41233. return _super.call(this, triggerOptions, condition) || this;
  41234. }
  41235. DoNothingAction.prototype.execute = function () {
  41236. };
  41237. DoNothingAction.prototype.serialize = function (parent) {
  41238. return _super.prototype._serialize.call(this, {
  41239. name: "DoNothingAction",
  41240. properties: []
  41241. }, parent);
  41242. };
  41243. return DoNothingAction;
  41244. }(BABYLON.Action));
  41245. BABYLON.DoNothingAction = DoNothingAction;
  41246. var CombineAction = (function (_super) {
  41247. __extends(CombineAction, _super);
  41248. function CombineAction(triggerOptions, children, condition) {
  41249. var _this = _super.call(this, triggerOptions, condition) || this;
  41250. _this.children = children;
  41251. return _this;
  41252. }
  41253. CombineAction.prototype._prepare = function () {
  41254. for (var index = 0; index < this.children.length; index++) {
  41255. this.children[index]._actionManager = this._actionManager;
  41256. this.children[index]._prepare();
  41257. }
  41258. };
  41259. CombineAction.prototype.execute = function (evt) {
  41260. for (var index = 0; index < this.children.length; index++) {
  41261. this.children[index].execute(evt);
  41262. }
  41263. };
  41264. CombineAction.prototype.serialize = function (parent) {
  41265. var serializationObject = _super.prototype._serialize.call(this, {
  41266. name: "CombineAction",
  41267. properties: [],
  41268. combine: []
  41269. }, parent);
  41270. for (var i = 0; i < this.children.length; i++) {
  41271. serializationObject.combine.push(this.children[i].serialize(null));
  41272. }
  41273. return serializationObject;
  41274. };
  41275. return CombineAction;
  41276. }(BABYLON.Action));
  41277. BABYLON.CombineAction = CombineAction;
  41278. var ExecuteCodeAction = (function (_super) {
  41279. __extends(ExecuteCodeAction, _super);
  41280. function ExecuteCodeAction(triggerOptions, func, condition) {
  41281. var _this = _super.call(this, triggerOptions, condition) || this;
  41282. _this.func = func;
  41283. return _this;
  41284. }
  41285. ExecuteCodeAction.prototype.execute = function (evt) {
  41286. this.func(evt);
  41287. };
  41288. return ExecuteCodeAction;
  41289. }(BABYLON.Action));
  41290. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  41291. var SetParentAction = (function (_super) {
  41292. __extends(SetParentAction, _super);
  41293. function SetParentAction(triggerOptions, target, parent, condition) {
  41294. var _this = _super.call(this, triggerOptions, condition) || this;
  41295. _this._target = target;
  41296. _this._parent = parent;
  41297. return _this;
  41298. }
  41299. SetParentAction.prototype._prepare = function () {
  41300. };
  41301. SetParentAction.prototype.execute = function () {
  41302. if (this._target.parent === this._parent) {
  41303. return;
  41304. }
  41305. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  41306. invertParentWorldMatrix.invert();
  41307. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  41308. this._target.parent = this._parent;
  41309. };
  41310. SetParentAction.prototype.serialize = function (parent) {
  41311. return _super.prototype._serialize.call(this, {
  41312. name: "SetParentAction",
  41313. properties: [
  41314. BABYLON.Action._GetTargetProperty(this._target),
  41315. BABYLON.Action._GetTargetProperty(this._parent),
  41316. ]
  41317. }, parent);
  41318. };
  41319. return SetParentAction;
  41320. }(BABYLON.Action));
  41321. BABYLON.SetParentAction = SetParentAction;
  41322. var PlaySoundAction = (function (_super) {
  41323. __extends(PlaySoundAction, _super);
  41324. function PlaySoundAction(triggerOptions, sound, condition) {
  41325. var _this = _super.call(this, triggerOptions, condition) || this;
  41326. _this._sound = sound;
  41327. return _this;
  41328. }
  41329. PlaySoundAction.prototype._prepare = function () {
  41330. };
  41331. PlaySoundAction.prototype.execute = function () {
  41332. if (this._sound !== undefined)
  41333. this._sound.play();
  41334. };
  41335. PlaySoundAction.prototype.serialize = function (parent) {
  41336. return _super.prototype._serialize.call(this, {
  41337. name: "PlaySoundAction",
  41338. properties: [{ name: "sound", value: this._sound.name }]
  41339. }, parent);
  41340. };
  41341. return PlaySoundAction;
  41342. }(BABYLON.Action));
  41343. BABYLON.PlaySoundAction = PlaySoundAction;
  41344. var StopSoundAction = (function (_super) {
  41345. __extends(StopSoundAction, _super);
  41346. function StopSoundAction(triggerOptions, sound, condition) {
  41347. var _this = _super.call(this, triggerOptions, condition) || this;
  41348. _this._sound = sound;
  41349. return _this;
  41350. }
  41351. StopSoundAction.prototype._prepare = function () {
  41352. };
  41353. StopSoundAction.prototype.execute = function () {
  41354. if (this._sound !== undefined)
  41355. this._sound.stop();
  41356. };
  41357. StopSoundAction.prototype.serialize = function (parent) {
  41358. return _super.prototype._serialize.call(this, {
  41359. name: "StopSoundAction",
  41360. properties: [{ name: "sound", value: this._sound.name }]
  41361. }, parent);
  41362. };
  41363. return StopSoundAction;
  41364. }(BABYLON.Action));
  41365. BABYLON.StopSoundAction = StopSoundAction;
  41366. })(BABYLON || (BABYLON = {}));
  41367. //# sourceMappingURL=babylon.directActions.js.map
  41368. var BABYLON;
  41369. (function (BABYLON) {
  41370. var SpriteManager = (function () {
  41371. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  41372. if (epsilon === void 0) { epsilon = 0.01; }
  41373. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41374. this.name = name;
  41375. this.sprites = new Array();
  41376. this.renderingGroupId = 0;
  41377. this.layerMask = 0x0FFFFFFF;
  41378. this.fogEnabled = true;
  41379. this.isPickable = false;
  41380. /**
  41381. * An event triggered when the manager is disposed.
  41382. * @type {BABYLON.Observable}
  41383. */
  41384. this.onDisposeObservable = new BABYLON.Observable();
  41385. this._vertexBuffers = {};
  41386. this._capacity = capacity;
  41387. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  41388. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41389. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41390. if (cellSize.width && cellSize.height) {
  41391. this.cellWidth = cellSize.width;
  41392. this.cellHeight = cellSize.height;
  41393. }
  41394. else if (cellSize !== undefined) {
  41395. this.cellWidth = cellSize;
  41396. this.cellHeight = cellSize;
  41397. }
  41398. else {
  41399. return;
  41400. }
  41401. this._epsilon = epsilon;
  41402. this._scene = scene;
  41403. this._scene.spriteManagers.push(this);
  41404. var indices = [];
  41405. var index = 0;
  41406. for (var count = 0; count < capacity; count++) {
  41407. indices.push(index);
  41408. indices.push(index + 1);
  41409. indices.push(index + 2);
  41410. indices.push(index);
  41411. indices.push(index + 2);
  41412. indices.push(index + 3);
  41413. index += 4;
  41414. }
  41415. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  41416. // VBO
  41417. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  41418. this._vertexData = new Float32Array(capacity * 16 * 4);
  41419. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  41420. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  41421. var options = this._buffer.createVertexBuffer("options", 4, 4);
  41422. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  41423. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  41424. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  41425. this._vertexBuffers["options"] = options;
  41426. this._vertexBuffers["cellInfo"] = cellInfo;
  41427. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  41428. // Effects
  41429. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  41430. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  41431. }
  41432. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  41433. set: function (callback) {
  41434. if (this._onDisposeObserver) {
  41435. this.onDisposeObservable.remove(this._onDisposeObserver);
  41436. }
  41437. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  41438. },
  41439. enumerable: true,
  41440. configurable: true
  41441. });
  41442. Object.defineProperty(SpriteManager.prototype, "texture", {
  41443. get: function () {
  41444. return this._spriteTexture;
  41445. },
  41446. set: function (value) {
  41447. this._spriteTexture = value;
  41448. },
  41449. enumerable: true,
  41450. configurable: true
  41451. });
  41452. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  41453. var arrayOffset = index * 16;
  41454. if (offsetX === 0)
  41455. offsetX = this._epsilon;
  41456. else if (offsetX === 1)
  41457. offsetX = 1 - this._epsilon;
  41458. if (offsetY === 0)
  41459. offsetY = this._epsilon;
  41460. else if (offsetY === 1)
  41461. offsetY = 1 - this._epsilon;
  41462. this._vertexData[arrayOffset] = sprite.position.x;
  41463. this._vertexData[arrayOffset + 1] = sprite.position.y;
  41464. this._vertexData[arrayOffset + 2] = sprite.position.z;
  41465. this._vertexData[arrayOffset + 3] = sprite.angle;
  41466. this._vertexData[arrayOffset + 4] = sprite.width;
  41467. this._vertexData[arrayOffset + 5] = sprite.height;
  41468. this._vertexData[arrayOffset + 6] = offsetX;
  41469. this._vertexData[arrayOffset + 7] = offsetY;
  41470. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  41471. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  41472. var offset = (sprite.cellIndex / rowSize) >> 0;
  41473. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  41474. this._vertexData[arrayOffset + 11] = offset;
  41475. // Color
  41476. this._vertexData[arrayOffset + 12] = sprite.color.r;
  41477. this._vertexData[arrayOffset + 13] = sprite.color.g;
  41478. this._vertexData[arrayOffset + 14] = sprite.color.b;
  41479. this._vertexData[arrayOffset + 15] = sprite.color.a;
  41480. };
  41481. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  41482. var count = Math.min(this._capacity, this.sprites.length);
  41483. var min = BABYLON.Vector3.Zero();
  41484. var max = BABYLON.Vector3.Zero();
  41485. var distance = Number.MAX_VALUE;
  41486. var currentSprite;
  41487. var cameraSpacePosition = BABYLON.Vector3.Zero();
  41488. var cameraView = camera.getViewMatrix();
  41489. for (var index = 0; index < count; index++) {
  41490. var sprite = this.sprites[index];
  41491. if (!sprite) {
  41492. continue;
  41493. }
  41494. if (predicate) {
  41495. if (!predicate(sprite)) {
  41496. continue;
  41497. }
  41498. }
  41499. else if (!sprite.isPickable) {
  41500. continue;
  41501. }
  41502. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  41503. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  41504. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  41505. if (ray.intersectsBoxMinMax(min, max)) {
  41506. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  41507. if (distance > currentDistance) {
  41508. distance = currentDistance;
  41509. currentSprite = sprite;
  41510. if (fastCheck) {
  41511. break;
  41512. }
  41513. }
  41514. }
  41515. }
  41516. if (currentSprite) {
  41517. var result = new BABYLON.PickingInfo();
  41518. result.hit = true;
  41519. result.pickedSprite = currentSprite;
  41520. result.distance = distance;
  41521. return result;
  41522. }
  41523. return null;
  41524. };
  41525. SpriteManager.prototype.render = function () {
  41526. // Check
  41527. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  41528. return;
  41529. var engine = this._scene.getEngine();
  41530. var baseSize = this._spriteTexture.getBaseSize();
  41531. // Sprites
  41532. var deltaTime = engine.getDeltaTime();
  41533. var max = Math.min(this._capacity, this.sprites.length);
  41534. var rowSize = baseSize.width / this.cellWidth;
  41535. var offset = 0;
  41536. for (var index = 0; index < max; index++) {
  41537. var sprite = this.sprites[index];
  41538. if (!sprite) {
  41539. continue;
  41540. }
  41541. sprite._animate(deltaTime);
  41542. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  41543. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  41544. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  41545. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  41546. }
  41547. this._buffer.update(this._vertexData);
  41548. // Render
  41549. var effect = this._effectBase;
  41550. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  41551. effect = this._effectFog;
  41552. }
  41553. engine.enableEffect(effect);
  41554. var viewMatrix = this._scene.getViewMatrix();
  41555. effect.setTexture("diffuseSampler", this._spriteTexture);
  41556. effect.setMatrix("view", viewMatrix);
  41557. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  41558. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  41559. // Fog
  41560. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  41561. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  41562. effect.setColor3("vFogColor", this._scene.fogColor);
  41563. }
  41564. // VBOs
  41565. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  41566. // Draw order
  41567. engine.setDepthFunctionToLessOrEqual();
  41568. effect.setBool("alphaTest", true);
  41569. engine.setColorWrite(false);
  41570. engine.draw(true, 0, max * 6);
  41571. engine.setColorWrite(true);
  41572. effect.setBool("alphaTest", false);
  41573. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  41574. engine.draw(true, 0, max * 6);
  41575. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  41576. };
  41577. SpriteManager.prototype.dispose = function () {
  41578. if (this._buffer) {
  41579. this._buffer.dispose();
  41580. this._buffer = null;
  41581. }
  41582. if (this._indexBuffer) {
  41583. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  41584. this._indexBuffer = null;
  41585. }
  41586. if (this._spriteTexture) {
  41587. this._spriteTexture.dispose();
  41588. this._spriteTexture = null;
  41589. }
  41590. // Remove from scene
  41591. var index = this._scene.spriteManagers.indexOf(this);
  41592. this._scene.spriteManagers.splice(index, 1);
  41593. // Callback
  41594. this.onDisposeObservable.notifyObservers(this);
  41595. this.onDisposeObservable.clear();
  41596. };
  41597. return SpriteManager;
  41598. }());
  41599. BABYLON.SpriteManager = SpriteManager;
  41600. })(BABYLON || (BABYLON = {}));
  41601. //# sourceMappingURL=babylon.spriteManager.js.map
  41602. var BABYLON;
  41603. (function (BABYLON) {
  41604. var Sprite = (function () {
  41605. function Sprite(name, manager) {
  41606. this.name = name;
  41607. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  41608. this.width = 1.0;
  41609. this.height = 1.0;
  41610. this.angle = 0;
  41611. this.cellIndex = 0;
  41612. this.invertU = 0;
  41613. this.invertV = 0;
  41614. this.animations = new Array();
  41615. this.isPickable = false;
  41616. this._animationStarted = false;
  41617. this._loopAnimation = false;
  41618. this._fromIndex = 0;
  41619. this._toIndex = 0;
  41620. this._delay = 0;
  41621. this._direction = 1;
  41622. this._time = 0;
  41623. this._manager = manager;
  41624. this._manager.sprites.push(this);
  41625. this.position = BABYLON.Vector3.Zero();
  41626. }
  41627. Object.defineProperty(Sprite.prototype, "size", {
  41628. get: function () {
  41629. return this.width;
  41630. },
  41631. set: function (value) {
  41632. this.width = value;
  41633. this.height = value;
  41634. },
  41635. enumerable: true,
  41636. configurable: true
  41637. });
  41638. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  41639. this._fromIndex = from;
  41640. this._toIndex = to;
  41641. this._loopAnimation = loop;
  41642. this._delay = delay;
  41643. this._animationStarted = true;
  41644. this._direction = from < to ? 1 : -1;
  41645. this.cellIndex = from;
  41646. this._time = 0;
  41647. this._onAnimationEnd = onAnimationEnd;
  41648. };
  41649. Sprite.prototype.stopAnimation = function () {
  41650. this._animationStarted = false;
  41651. };
  41652. Sprite.prototype._animate = function (deltaTime) {
  41653. if (!this._animationStarted)
  41654. return;
  41655. this._time += deltaTime;
  41656. if (this._time > this._delay) {
  41657. this._time = this._time % this._delay;
  41658. this.cellIndex += this._direction;
  41659. if (this.cellIndex > this._toIndex) {
  41660. if (this._loopAnimation) {
  41661. this.cellIndex = this._fromIndex;
  41662. }
  41663. else {
  41664. this.cellIndex = this._toIndex;
  41665. this._animationStarted = false;
  41666. if (this._onAnimationEnd) {
  41667. this._onAnimationEnd();
  41668. }
  41669. if (this.disposeWhenFinishedAnimating) {
  41670. this.dispose();
  41671. }
  41672. }
  41673. }
  41674. }
  41675. };
  41676. Sprite.prototype.dispose = function () {
  41677. for (var i = 0; i < this._manager.sprites.length; i++) {
  41678. if (this._manager.sprites[i] == this) {
  41679. this._manager.sprites.splice(i, 1);
  41680. }
  41681. }
  41682. };
  41683. return Sprite;
  41684. }());
  41685. BABYLON.Sprite = Sprite;
  41686. })(BABYLON || (BABYLON = {}));
  41687. //# sourceMappingURL=babylon.sprite.js.map
  41688. var BABYLON;
  41689. (function (BABYLON) {
  41690. var IntersectionInfo = (function () {
  41691. function IntersectionInfo(bu, bv, distance) {
  41692. this.bu = bu;
  41693. this.bv = bv;
  41694. this.distance = distance;
  41695. this.faceId = 0;
  41696. this.subMeshId = 0;
  41697. }
  41698. return IntersectionInfo;
  41699. }());
  41700. BABYLON.IntersectionInfo = IntersectionInfo;
  41701. var PickingInfo = (function () {
  41702. function PickingInfo() {
  41703. this.hit = false;
  41704. this.distance = 0;
  41705. this.pickedPoint = null;
  41706. this.pickedMesh = null;
  41707. this.bu = 0;
  41708. this.bv = 0;
  41709. this.faceId = -1;
  41710. this.subMeshId = 0;
  41711. this.pickedSprite = null;
  41712. }
  41713. // Methods
  41714. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  41715. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  41716. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  41717. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41718. return null;
  41719. }
  41720. var indices = this.pickedMesh.getIndices();
  41721. var result;
  41722. if (useVerticesNormals) {
  41723. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41724. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  41725. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  41726. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  41727. normal0 = normal0.scale(this.bu);
  41728. normal1 = normal1.scale(this.bv);
  41729. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  41730. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  41731. }
  41732. else {
  41733. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41734. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  41735. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  41736. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  41737. var p1p2 = vertex1.subtract(vertex2);
  41738. var p3p2 = vertex3.subtract(vertex2);
  41739. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  41740. }
  41741. if (useWorldCoordinates) {
  41742. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  41743. }
  41744. return BABYLON.Vector3.Normalize(result);
  41745. };
  41746. PickingInfo.prototype.getTextureCoordinates = function () {
  41747. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  41748. return null;
  41749. }
  41750. var indices = this.pickedMesh.getIndices();
  41751. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41752. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  41753. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  41754. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  41755. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  41756. uv1 = uv1.scale(this.bu);
  41757. uv2 = uv2.scale(this.bv);
  41758. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  41759. };
  41760. return PickingInfo;
  41761. }());
  41762. BABYLON.PickingInfo = PickingInfo;
  41763. })(BABYLON || (BABYLON = {}));
  41764. //# sourceMappingURL=babylon.pickingInfo.js.map
  41765. var BABYLON;
  41766. (function (BABYLON) {
  41767. var Ray = (function () {
  41768. function Ray(origin, direction, length) {
  41769. if (length === void 0) { length = Number.MAX_VALUE; }
  41770. this.origin = origin;
  41771. this.direction = direction;
  41772. this.length = length;
  41773. }
  41774. // Methods
  41775. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  41776. var d = 0.0;
  41777. var maxValue = Number.MAX_VALUE;
  41778. var inv;
  41779. var min;
  41780. var max;
  41781. var temp;
  41782. if (Math.abs(this.direction.x) < 0.0000001) {
  41783. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  41784. return false;
  41785. }
  41786. }
  41787. else {
  41788. inv = 1.0 / this.direction.x;
  41789. min = (minimum.x - this.origin.x) * inv;
  41790. max = (maximum.x - this.origin.x) * inv;
  41791. if (max === -Infinity) {
  41792. max = Infinity;
  41793. }
  41794. if (min > max) {
  41795. temp = min;
  41796. min = max;
  41797. max = temp;
  41798. }
  41799. d = Math.max(min, d);
  41800. maxValue = Math.min(max, maxValue);
  41801. if (d > maxValue) {
  41802. return false;
  41803. }
  41804. }
  41805. if (Math.abs(this.direction.y) < 0.0000001) {
  41806. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  41807. return false;
  41808. }
  41809. }
  41810. else {
  41811. inv = 1.0 / this.direction.y;
  41812. min = (minimum.y - this.origin.y) * inv;
  41813. max = (maximum.y - this.origin.y) * inv;
  41814. if (max === -Infinity) {
  41815. max = Infinity;
  41816. }
  41817. if (min > max) {
  41818. temp = min;
  41819. min = max;
  41820. max = temp;
  41821. }
  41822. d = Math.max(min, d);
  41823. maxValue = Math.min(max, maxValue);
  41824. if (d > maxValue) {
  41825. return false;
  41826. }
  41827. }
  41828. if (Math.abs(this.direction.z) < 0.0000001) {
  41829. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  41830. return false;
  41831. }
  41832. }
  41833. else {
  41834. inv = 1.0 / this.direction.z;
  41835. min = (minimum.z - this.origin.z) * inv;
  41836. max = (maximum.z - this.origin.z) * inv;
  41837. if (max === -Infinity) {
  41838. max = Infinity;
  41839. }
  41840. if (min > max) {
  41841. temp = min;
  41842. min = max;
  41843. max = temp;
  41844. }
  41845. d = Math.max(min, d);
  41846. maxValue = Math.min(max, maxValue);
  41847. if (d > maxValue) {
  41848. return false;
  41849. }
  41850. }
  41851. return true;
  41852. };
  41853. Ray.prototype.intersectsBox = function (box) {
  41854. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  41855. };
  41856. Ray.prototype.intersectsSphere = function (sphere) {
  41857. var x = sphere.center.x - this.origin.x;
  41858. var y = sphere.center.y - this.origin.y;
  41859. var z = sphere.center.z - this.origin.z;
  41860. var pyth = (x * x) + (y * y) + (z * z);
  41861. var rr = sphere.radius * sphere.radius;
  41862. if (pyth <= rr) {
  41863. return true;
  41864. }
  41865. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  41866. if (dot < 0.0) {
  41867. return false;
  41868. }
  41869. var temp = pyth - (dot * dot);
  41870. return temp <= rr;
  41871. };
  41872. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  41873. if (!this._edge1) {
  41874. this._edge1 = BABYLON.Vector3.Zero();
  41875. this._edge2 = BABYLON.Vector3.Zero();
  41876. this._pvec = BABYLON.Vector3.Zero();
  41877. this._tvec = BABYLON.Vector3.Zero();
  41878. this._qvec = BABYLON.Vector3.Zero();
  41879. }
  41880. vertex1.subtractToRef(vertex0, this._edge1);
  41881. vertex2.subtractToRef(vertex0, this._edge2);
  41882. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  41883. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  41884. if (det === 0) {
  41885. return null;
  41886. }
  41887. var invdet = 1 / det;
  41888. this.origin.subtractToRef(vertex0, this._tvec);
  41889. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  41890. if (bu < 0 || bu > 1.0) {
  41891. return null;
  41892. }
  41893. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  41894. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  41895. if (bv < 0 || bu + bv > 1.0) {
  41896. return null;
  41897. }
  41898. //check if the distance is longer than the predefined length.
  41899. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  41900. if (distance > this.length) {
  41901. return null;
  41902. }
  41903. return new BABYLON.IntersectionInfo(bu, bv, distance);
  41904. };
  41905. Ray.prototype.intersectsPlane = function (plane) {
  41906. var distance;
  41907. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  41908. if (Math.abs(result1) < 9.99999997475243E-07) {
  41909. return null;
  41910. }
  41911. else {
  41912. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  41913. distance = (-plane.d - result2) / result1;
  41914. if (distance < 0.0) {
  41915. if (distance < -9.99999997475243E-07) {
  41916. return null;
  41917. }
  41918. else {
  41919. return 0;
  41920. }
  41921. }
  41922. return distance;
  41923. }
  41924. };
  41925. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  41926. var tm = BABYLON.Tmp.Matrix[0];
  41927. mesh.getWorldMatrix().invertToRef(tm);
  41928. if (this._tmpRay) {
  41929. Ray.TransformToRef(this, tm, this._tmpRay);
  41930. }
  41931. else {
  41932. this._tmpRay = Ray.Transform(this, tm);
  41933. }
  41934. return mesh.intersects(this._tmpRay, fastCheck);
  41935. };
  41936. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  41937. if (results) {
  41938. results.length = 0;
  41939. }
  41940. else {
  41941. results = [];
  41942. }
  41943. for (var i = 0; i < meshes.length; i++) {
  41944. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  41945. if (pickInfo.hit) {
  41946. results.push(pickInfo);
  41947. }
  41948. }
  41949. results.sort(this._comparePickingInfo);
  41950. return results;
  41951. };
  41952. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  41953. if (pickingInfoA.distance < pickingInfoB.distance) {
  41954. return -1;
  41955. }
  41956. else if (pickingInfoA.distance > pickingInfoB.distance) {
  41957. return 1;
  41958. }
  41959. else {
  41960. return 0;
  41961. }
  41962. };
  41963. /**
  41964. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  41965. * @param sega the first point of the segment to test the intersection against
  41966. * @param segb the second point of the segment to test the intersection against
  41967. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  41968. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  41969. */
  41970. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  41971. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  41972. var u = segb.subtract(sega);
  41973. var v = rsegb.subtract(this.origin);
  41974. var w = sega.subtract(this.origin);
  41975. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  41976. var b = BABYLON.Vector3.Dot(u, v);
  41977. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  41978. var d = BABYLON.Vector3.Dot(u, w);
  41979. var e = BABYLON.Vector3.Dot(v, w);
  41980. var D = a * c - b * b; // always >= 0
  41981. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  41982. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  41983. // compute the line parameters of the two closest points
  41984. if (D < Ray.smallnum) {
  41985. sN = 0.0; // force using point P0 on segment S1
  41986. sD = 1.0; // to prevent possible division by 0.0 later
  41987. tN = e;
  41988. tD = c;
  41989. }
  41990. else {
  41991. sN = (b * e - c * d);
  41992. tN = (a * e - b * d);
  41993. if (sN < 0.0) {
  41994. sN = 0.0;
  41995. tN = e;
  41996. tD = c;
  41997. }
  41998. else if (sN > sD) {
  41999. sN = sD;
  42000. tN = e + b;
  42001. tD = c;
  42002. }
  42003. }
  42004. if (tN < 0.0) {
  42005. tN = 0.0;
  42006. // recompute sc for this edge
  42007. if (-d < 0.0) {
  42008. sN = 0.0;
  42009. }
  42010. else if (-d > a)
  42011. sN = sD;
  42012. else {
  42013. sN = -d;
  42014. sD = a;
  42015. }
  42016. }
  42017. else if (tN > tD) {
  42018. tN = tD;
  42019. // recompute sc for this edge
  42020. if ((-d + b) < 0.0) {
  42021. sN = 0;
  42022. }
  42023. else if ((-d + b) > a) {
  42024. sN = sD;
  42025. }
  42026. else {
  42027. sN = (-d + b);
  42028. sD = a;
  42029. }
  42030. }
  42031. // finally do the division to get sc and tc
  42032. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  42033. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  42034. // get the difference of the two closest points
  42035. var qtc = v.multiplyByFloats(tc, tc, tc);
  42036. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  42037. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  42038. if (isIntersected) {
  42039. return qtc.length();
  42040. }
  42041. return -1;
  42042. };
  42043. // Statics
  42044. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  42045. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  42046. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  42047. var direction = end.subtract(start);
  42048. direction.normalize();
  42049. return new Ray(start, direction);
  42050. };
  42051. /**
  42052. * 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
  42053. * transformed to the given world matrix.
  42054. * @param origin The origin point
  42055. * @param end The end point
  42056. * @param world a matrix to transform the ray to. Default is the identity matrix.
  42057. */
  42058. Ray.CreateNewFromTo = function (origin, end, world) {
  42059. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  42060. var direction = end.subtract(origin);
  42061. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  42062. direction.normalize();
  42063. return Ray.Transform(new Ray(origin, direction, length), world);
  42064. };
  42065. Ray.Transform = function (ray, matrix) {
  42066. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  42067. Ray.TransformToRef(ray, matrix, result);
  42068. return result;
  42069. };
  42070. Ray.TransformToRef = function (ray, matrix, result) {
  42071. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  42072. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  42073. result.length = ray.length;
  42074. var dir = result.direction;
  42075. var len = dir.length();
  42076. if (!(len === 0 || len === 1)) {
  42077. var num = 1.0 / len;
  42078. dir.x *= num;
  42079. dir.y *= num;
  42080. dir.z *= num;
  42081. result.length *= len;
  42082. }
  42083. };
  42084. Ray.smallnum = 0.00000001;
  42085. Ray.rayl = 10e8;
  42086. return Ray;
  42087. }());
  42088. BABYLON.Ray = Ray;
  42089. })(BABYLON || (BABYLON = {}));
  42090. //# sourceMappingURL=babylon.ray.js.map
  42091. var BABYLON;
  42092. (function (BABYLON) {
  42093. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  42094. if (boxMin.x > sphereCenter.x + sphereRadius)
  42095. return false;
  42096. if (sphereCenter.x - sphereRadius > boxMax.x)
  42097. return false;
  42098. if (boxMin.y > sphereCenter.y + sphereRadius)
  42099. return false;
  42100. if (sphereCenter.y - sphereRadius > boxMax.y)
  42101. return false;
  42102. if (boxMin.z > sphereCenter.z + sphereRadius)
  42103. return false;
  42104. if (sphereCenter.z - sphereRadius > boxMax.z)
  42105. return false;
  42106. return true;
  42107. };
  42108. var getLowestRoot = (function () {
  42109. var result = { root: 0, found: false };
  42110. return function (a, b, c, maxR) {
  42111. result.root = 0;
  42112. result.found = false;
  42113. var determinant = b * b - 4.0 * a * c;
  42114. if (determinant < 0)
  42115. return result;
  42116. var sqrtD = Math.sqrt(determinant);
  42117. var r1 = (-b - sqrtD) / (2.0 * a);
  42118. var r2 = (-b + sqrtD) / (2.0 * a);
  42119. if (r1 > r2) {
  42120. var temp = r2;
  42121. r2 = r1;
  42122. r1 = temp;
  42123. }
  42124. if (r1 > 0 && r1 < maxR) {
  42125. result.root = r1;
  42126. result.found = true;
  42127. return result;
  42128. }
  42129. if (r2 > 0 && r2 < maxR) {
  42130. result.root = r2;
  42131. result.found = true;
  42132. return result;
  42133. }
  42134. return result;
  42135. };
  42136. })();
  42137. var Collider = (function () {
  42138. function Collider() {
  42139. this.radius = BABYLON.Vector3.One();
  42140. this.retry = 0;
  42141. this.basePointWorld = BABYLON.Vector3.Zero();
  42142. this.velocityWorld = BABYLON.Vector3.Zero();
  42143. this.normalizedVelocity = BABYLON.Vector3.Zero();
  42144. this._collisionPoint = BABYLON.Vector3.Zero();
  42145. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  42146. this._tempVector = BABYLON.Vector3.Zero();
  42147. this._tempVector2 = BABYLON.Vector3.Zero();
  42148. this._tempVector3 = BABYLON.Vector3.Zero();
  42149. this._tempVector4 = BABYLON.Vector3.Zero();
  42150. this._edge = BABYLON.Vector3.Zero();
  42151. this._baseToVertex = BABYLON.Vector3.Zero();
  42152. this._destinationPoint = BABYLON.Vector3.Zero();
  42153. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  42154. this._displacementVector = BABYLON.Vector3.Zero();
  42155. this._collisionMask = -1;
  42156. }
  42157. Object.defineProperty(Collider.prototype, "collisionMask", {
  42158. get: function () {
  42159. return this._collisionMask;
  42160. },
  42161. set: function (mask) {
  42162. this._collisionMask = !isNaN(mask) ? mask : -1;
  42163. },
  42164. enumerable: true,
  42165. configurable: true
  42166. });
  42167. // Methods
  42168. Collider.prototype._initialize = function (source, dir, e) {
  42169. this.velocity = dir;
  42170. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  42171. this.basePoint = source;
  42172. source.multiplyToRef(this.radius, this.basePointWorld);
  42173. dir.multiplyToRef(this.radius, this.velocityWorld);
  42174. this.velocityWorldLength = this.velocityWorld.length();
  42175. this.epsilon = e;
  42176. this.collisionFound = false;
  42177. };
  42178. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  42179. pa.subtractToRef(point, this._tempVector);
  42180. pb.subtractToRef(point, this._tempVector2);
  42181. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  42182. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  42183. if (d < 0)
  42184. return false;
  42185. pc.subtractToRef(point, this._tempVector3);
  42186. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  42187. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  42188. if (d < 0)
  42189. return false;
  42190. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  42191. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  42192. return d >= 0;
  42193. };
  42194. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  42195. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  42196. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  42197. if (distance > this.velocityWorldLength + max + sphereRadius) {
  42198. return false;
  42199. }
  42200. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  42201. return false;
  42202. return true;
  42203. };
  42204. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  42205. var t0;
  42206. var embeddedInPlane = false;
  42207. //defensive programming, actually not needed.
  42208. if (!trianglePlaneArray) {
  42209. trianglePlaneArray = [];
  42210. }
  42211. if (!trianglePlaneArray[faceIndex]) {
  42212. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  42213. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  42214. }
  42215. var trianglePlane = trianglePlaneArray[faceIndex];
  42216. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  42217. return;
  42218. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  42219. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  42220. if (normalDotVelocity == 0) {
  42221. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  42222. return;
  42223. embeddedInPlane = true;
  42224. t0 = 0;
  42225. }
  42226. else {
  42227. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  42228. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  42229. if (t0 > t1) {
  42230. var temp = t1;
  42231. t1 = t0;
  42232. t0 = temp;
  42233. }
  42234. if (t0 > 1.0 || t1 < 0.0)
  42235. return;
  42236. if (t0 < 0)
  42237. t0 = 0;
  42238. if (t0 > 1.0)
  42239. t0 = 1.0;
  42240. }
  42241. this._collisionPoint.copyFromFloats(0, 0, 0);
  42242. var found = false;
  42243. var t = 1.0;
  42244. if (!embeddedInPlane) {
  42245. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  42246. this.velocity.scaleToRef(t0, this._tempVector);
  42247. this._planeIntersectionPoint.addInPlace(this._tempVector);
  42248. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  42249. found = true;
  42250. t = t0;
  42251. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  42252. }
  42253. }
  42254. if (!found) {
  42255. var velocitySquaredLength = this.velocity.lengthSquared();
  42256. var a = velocitySquaredLength;
  42257. this.basePoint.subtractToRef(p1, this._tempVector);
  42258. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  42259. var c = this._tempVector.lengthSquared() - 1.0;
  42260. var lowestRoot = getLowestRoot(a, b, c, t);
  42261. if (lowestRoot.found) {
  42262. t = lowestRoot.root;
  42263. found = true;
  42264. this._collisionPoint.copyFrom(p1);
  42265. }
  42266. this.basePoint.subtractToRef(p2, this._tempVector);
  42267. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  42268. c = this._tempVector.lengthSquared() - 1.0;
  42269. lowestRoot = getLowestRoot(a, b, c, t);
  42270. if (lowestRoot.found) {
  42271. t = lowestRoot.root;
  42272. found = true;
  42273. this._collisionPoint.copyFrom(p2);
  42274. }
  42275. this.basePoint.subtractToRef(p3, this._tempVector);
  42276. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  42277. c = this._tempVector.lengthSquared() - 1.0;
  42278. lowestRoot = getLowestRoot(a, b, c, t);
  42279. if (lowestRoot.found) {
  42280. t = lowestRoot.root;
  42281. found = true;
  42282. this._collisionPoint.copyFrom(p3);
  42283. }
  42284. p2.subtractToRef(p1, this._edge);
  42285. p1.subtractToRef(this.basePoint, this._baseToVertex);
  42286. var edgeSquaredLength = this._edge.lengthSquared();
  42287. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  42288. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  42289. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  42290. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  42291. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  42292. lowestRoot = getLowestRoot(a, b, c, t);
  42293. if (lowestRoot.found) {
  42294. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  42295. if (f >= 0.0 && f <= 1.0) {
  42296. t = lowestRoot.root;
  42297. found = true;
  42298. this._edge.scaleInPlace(f);
  42299. p1.addToRef(this._edge, this._collisionPoint);
  42300. }
  42301. }
  42302. p3.subtractToRef(p2, this._edge);
  42303. p2.subtractToRef(this.basePoint, this._baseToVertex);
  42304. edgeSquaredLength = this._edge.lengthSquared();
  42305. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  42306. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  42307. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  42308. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  42309. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  42310. lowestRoot = getLowestRoot(a, b, c, t);
  42311. if (lowestRoot.found) {
  42312. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  42313. if (f >= 0.0 && f <= 1.0) {
  42314. t = lowestRoot.root;
  42315. found = true;
  42316. this._edge.scaleInPlace(f);
  42317. p2.addToRef(this._edge, this._collisionPoint);
  42318. }
  42319. }
  42320. p1.subtractToRef(p3, this._edge);
  42321. p3.subtractToRef(this.basePoint, this._baseToVertex);
  42322. edgeSquaredLength = this._edge.lengthSquared();
  42323. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  42324. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  42325. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  42326. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  42327. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  42328. lowestRoot = getLowestRoot(a, b, c, t);
  42329. if (lowestRoot.found) {
  42330. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  42331. if (f >= 0.0 && f <= 1.0) {
  42332. t = lowestRoot.root;
  42333. found = true;
  42334. this._edge.scaleInPlace(f);
  42335. p3.addToRef(this._edge, this._collisionPoint);
  42336. }
  42337. }
  42338. }
  42339. if (found) {
  42340. var distToCollision = t * this.velocity.length();
  42341. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  42342. if (!this.intersectionPoint) {
  42343. this.intersectionPoint = this._collisionPoint.clone();
  42344. }
  42345. else {
  42346. this.intersectionPoint.copyFrom(this._collisionPoint);
  42347. }
  42348. this.nearestDistance = distToCollision;
  42349. this.collisionFound = true;
  42350. }
  42351. }
  42352. };
  42353. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  42354. for (var i = indexStart; i < indexEnd; i += 3) {
  42355. var p1 = pts[indices[i] - decal];
  42356. var p2 = pts[indices[i + 1] - decal];
  42357. var p3 = pts[indices[i + 2] - decal];
  42358. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  42359. }
  42360. };
  42361. Collider.prototype._getResponse = function (pos, vel) {
  42362. pos.addToRef(vel, this._destinationPoint);
  42363. vel.scaleInPlace((this.nearestDistance / vel.length()));
  42364. this.basePoint.addToRef(vel, pos);
  42365. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  42366. this._slidePlaneNormal.normalize();
  42367. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  42368. pos.addInPlace(this._displacementVector);
  42369. this.intersectionPoint.addInPlace(this._displacementVector);
  42370. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  42371. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  42372. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  42373. };
  42374. return Collider;
  42375. }());
  42376. BABYLON.Collider = Collider;
  42377. })(BABYLON || (BABYLON = {}));
  42378. //# sourceMappingURL=babylon.collider.js.map
  42379. var BABYLON;
  42380. (function (BABYLON) {
  42381. //WebWorker code will be inserted to this variable.
  42382. BABYLON.CollisionWorker = "";
  42383. var WorkerTaskType;
  42384. (function (WorkerTaskType) {
  42385. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  42386. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  42387. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  42388. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  42389. var WorkerReplyType;
  42390. (function (WorkerReplyType) {
  42391. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  42392. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  42393. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  42394. var CollisionCoordinatorWorker = (function () {
  42395. function CollisionCoordinatorWorker() {
  42396. var _this = this;
  42397. this._scaledPosition = BABYLON.Vector3.Zero();
  42398. this._scaledVelocity = BABYLON.Vector3.Zero();
  42399. this.onMeshUpdated = function (mesh) {
  42400. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  42401. };
  42402. this.onGeometryUpdated = function (geometry) {
  42403. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  42404. };
  42405. this._afterRender = function () {
  42406. if (!_this._init)
  42407. return;
  42408. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  42409. return;
  42410. }
  42411. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  42412. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  42413. if (_this._runningUpdated > 4) {
  42414. return;
  42415. }
  42416. ++_this._runningUpdated;
  42417. var payload = {
  42418. updatedMeshes: _this._addUpdateMeshesList,
  42419. updatedGeometries: _this._addUpdateGeometriesList,
  42420. removedGeometries: _this._toRemoveGeometryArray,
  42421. removedMeshes: _this._toRemoveMeshesArray
  42422. };
  42423. var message = {
  42424. payload: payload,
  42425. taskType: WorkerTaskType.UPDATE
  42426. };
  42427. var serializable = [];
  42428. for (var id in payload.updatedGeometries) {
  42429. if (payload.updatedGeometries.hasOwnProperty(id)) {
  42430. //prepare transferables
  42431. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  42432. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  42433. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  42434. }
  42435. }
  42436. _this._worker.postMessage(message, serializable);
  42437. _this._addUpdateMeshesList = {};
  42438. _this._addUpdateGeometriesList = {};
  42439. _this._toRemoveGeometryArray = [];
  42440. _this._toRemoveMeshesArray = [];
  42441. };
  42442. this._onMessageFromWorker = function (e) {
  42443. var returnData = e.data;
  42444. if (returnData.error != WorkerReplyType.SUCCESS) {
  42445. //TODO what errors can be returned from the worker?
  42446. BABYLON.Tools.Warn("error returned from worker!");
  42447. return;
  42448. }
  42449. switch (returnData.taskType) {
  42450. case WorkerTaskType.INIT:
  42451. _this._init = true;
  42452. //Update the worked with ALL of the scene's current state
  42453. _this._scene.meshes.forEach(function (mesh) {
  42454. _this.onMeshAdded(mesh);
  42455. });
  42456. _this._scene.getGeometries().forEach(function (geometry) {
  42457. _this.onGeometryAdded(geometry);
  42458. });
  42459. break;
  42460. case WorkerTaskType.UPDATE:
  42461. _this._runningUpdated--;
  42462. break;
  42463. case WorkerTaskType.COLLIDE:
  42464. _this._runningCollisionTask = false;
  42465. var returnPayload = returnData.payload;
  42466. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  42467. return;
  42468. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  42469. //cleanup
  42470. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  42471. break;
  42472. }
  42473. };
  42474. this._collisionsCallbackArray = [];
  42475. this._init = false;
  42476. this._runningUpdated = 0;
  42477. this._runningCollisionTask = false;
  42478. this._addUpdateMeshesList = {};
  42479. this._addUpdateGeometriesList = {};
  42480. this._toRemoveGeometryArray = [];
  42481. this._toRemoveMeshesArray = [];
  42482. }
  42483. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  42484. if (!this._init)
  42485. return;
  42486. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  42487. return;
  42488. position.divideToRef(collider.radius, this._scaledPosition);
  42489. displacement.divideToRef(collider.radius, this._scaledVelocity);
  42490. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  42491. var payload = {
  42492. collider: {
  42493. position: this._scaledPosition.asArray(),
  42494. velocity: this._scaledVelocity.asArray(),
  42495. radius: collider.radius.asArray()
  42496. },
  42497. collisionId: collisionIndex,
  42498. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  42499. maximumRetry: maximumRetry
  42500. };
  42501. var message = {
  42502. payload: payload,
  42503. taskType: WorkerTaskType.COLLIDE
  42504. };
  42505. this._worker.postMessage(message);
  42506. };
  42507. CollisionCoordinatorWorker.prototype.init = function (scene) {
  42508. this._scene = scene;
  42509. this._scene.registerAfterRender(this._afterRender);
  42510. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  42511. this._worker = new Worker(workerUrl);
  42512. this._worker.onmessage = this._onMessageFromWorker;
  42513. var message = {
  42514. payload: {},
  42515. taskType: WorkerTaskType.INIT
  42516. };
  42517. this._worker.postMessage(message);
  42518. };
  42519. CollisionCoordinatorWorker.prototype.destroy = function () {
  42520. this._scene.unregisterAfterRender(this._afterRender);
  42521. this._worker.terminate();
  42522. };
  42523. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  42524. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  42525. this.onMeshUpdated(mesh);
  42526. };
  42527. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  42528. this._toRemoveMeshesArray.push(mesh.uniqueId);
  42529. };
  42530. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  42531. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  42532. geometry.onGeometryUpdated = this.onGeometryUpdated;
  42533. this.onGeometryUpdated(geometry);
  42534. };
  42535. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  42536. this._toRemoveGeometryArray.push(geometry.id);
  42537. };
  42538. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  42539. var submeshes = [];
  42540. if (mesh.subMeshes) {
  42541. submeshes = mesh.subMeshes.map(function (sm, idx) {
  42542. return {
  42543. position: idx,
  42544. verticesStart: sm.verticesStart,
  42545. verticesCount: sm.verticesCount,
  42546. indexStart: sm.indexStart,
  42547. indexCount: sm.indexCount,
  42548. hasMaterial: !!sm.getMaterial(),
  42549. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  42550. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  42551. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  42552. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  42553. };
  42554. });
  42555. }
  42556. var geometryId = null;
  42557. if (mesh instanceof BABYLON.Mesh) {
  42558. geometryId = mesh.geometry ? mesh.geometry.id : null;
  42559. }
  42560. else if (mesh instanceof BABYLON.InstancedMesh) {
  42561. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  42562. }
  42563. return {
  42564. uniqueId: mesh.uniqueId,
  42565. id: mesh.id,
  42566. name: mesh.name,
  42567. geometryId: geometryId,
  42568. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  42569. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  42570. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  42571. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  42572. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  42573. subMeshes: submeshes,
  42574. checkCollisions: mesh.checkCollisions
  42575. };
  42576. };
  42577. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  42578. return {
  42579. id: geometry.id,
  42580. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  42581. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  42582. indices: new Uint32Array(geometry.getIndices() || []),
  42583. };
  42584. };
  42585. return CollisionCoordinatorWorker;
  42586. }());
  42587. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  42588. var CollisionCoordinatorLegacy = (function () {
  42589. function CollisionCoordinatorLegacy() {
  42590. this._scaledPosition = BABYLON.Vector3.Zero();
  42591. this._scaledVelocity = BABYLON.Vector3.Zero();
  42592. this._finalPosition = BABYLON.Vector3.Zero();
  42593. }
  42594. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  42595. position.divideToRef(collider.radius, this._scaledPosition);
  42596. displacement.divideToRef(collider.radius, this._scaledVelocity);
  42597. collider.collidedMesh = null;
  42598. collider.retry = 0;
  42599. collider.initialVelocity = this._scaledVelocity;
  42600. collider.initialPosition = this._scaledPosition;
  42601. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  42602. this._finalPosition.multiplyInPlace(collider.radius);
  42603. //run the callback
  42604. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  42605. };
  42606. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  42607. this._scene = scene;
  42608. };
  42609. CollisionCoordinatorLegacy.prototype.destroy = function () {
  42610. //Legacy need no destruction method.
  42611. };
  42612. //No update in legacy mode
  42613. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  42614. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  42615. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  42616. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  42617. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  42618. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  42619. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  42620. if (excludedMesh === void 0) { excludedMesh = null; }
  42621. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  42622. if (collider.retry >= maximumRetry) {
  42623. finalPosition.copyFrom(position);
  42624. return;
  42625. }
  42626. // Check if this is a mesh else camera or -1
  42627. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  42628. collider._initialize(position, velocity, closeDistance);
  42629. // Check all meshes
  42630. for (var index = 0; index < this._scene.meshes.length; index++) {
  42631. var mesh = this._scene.meshes[index];
  42632. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  42633. mesh._checkCollision(collider);
  42634. }
  42635. }
  42636. if (!collider.collisionFound) {
  42637. position.addToRef(velocity, finalPosition);
  42638. return;
  42639. }
  42640. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  42641. collider._getResponse(position, velocity);
  42642. }
  42643. if (velocity.length() <= closeDistance) {
  42644. finalPosition.copyFrom(position);
  42645. return;
  42646. }
  42647. collider.retry++;
  42648. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  42649. };
  42650. return CollisionCoordinatorLegacy;
  42651. }());
  42652. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  42653. })(BABYLON || (BABYLON = {}));
  42654. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  42655. var BABYLON;
  42656. (function (BABYLON) {
  42657. var Particle = (function () {
  42658. function Particle(particleSystem) {
  42659. this.particleSystem = particleSystem;
  42660. this.position = BABYLON.Vector3.Zero();
  42661. this.direction = BABYLON.Vector3.Zero();
  42662. this.color = new BABYLON.Color4(0, 0, 0, 0);
  42663. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  42664. this.lifeTime = 1.0;
  42665. this.age = 0;
  42666. this.size = 0;
  42667. this.angle = 0;
  42668. this.angularSpeed = 0;
  42669. this._currentFrameCounter = 0;
  42670. this.cellIndex = 0;
  42671. if (!this.particleSystem.isAnimationSheetEnabled) {
  42672. return;
  42673. }
  42674. this.cellIndex = this.particleSystem.startSpriteCellID;
  42675. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  42676. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  42677. }
  42678. else {
  42679. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  42680. }
  42681. }
  42682. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  42683. // (ageOffset / scaledUpdateSpeed) / available cells
  42684. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  42685. this._currentFrameCounter += scaledUpdateSpeed;
  42686. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  42687. this._currentFrameCounter = 0;
  42688. this.cellIndex++;
  42689. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  42690. this.cellIndex = this.particleSystem.endSpriteCellID;
  42691. }
  42692. }
  42693. };
  42694. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  42695. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  42696. this.cellIndex++;
  42697. this._currentFrameCounter = 0;
  42698. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  42699. if (this.particleSystem.spriteCellLoop) {
  42700. this.cellIndex = this.particleSystem.startSpriteCellID;
  42701. }
  42702. else {
  42703. this.cellIndex = this.particleSystem.endSpriteCellID;
  42704. }
  42705. }
  42706. }
  42707. else {
  42708. this._currentFrameCounter++;
  42709. }
  42710. };
  42711. Particle.prototype.copyTo = function (other) {
  42712. other.position.copyFrom(this.position);
  42713. other.direction.copyFrom(this.direction);
  42714. other.color.copyFrom(this.color);
  42715. other.colorStep.copyFrom(this.colorStep);
  42716. other.lifeTime = this.lifeTime;
  42717. other.age = this.age;
  42718. other.size = this.size;
  42719. other.angle = this.angle;
  42720. other.angularSpeed = this.angularSpeed;
  42721. other.particleSystem = this.particleSystem;
  42722. other.cellIndex = this.cellIndex;
  42723. };
  42724. return Particle;
  42725. }());
  42726. BABYLON.Particle = Particle;
  42727. })(BABYLON || (BABYLON = {}));
  42728. //# sourceMappingURL=babylon.particle.js.map
  42729. var BABYLON;
  42730. (function (BABYLON) {
  42731. var randomNumber = function (min, max) {
  42732. if (min === max) {
  42733. return (min);
  42734. }
  42735. var random = Math.random();
  42736. return ((random * (max - min)) + min);
  42737. };
  42738. var ParticleSystem = (function () {
  42739. // end of sheet animation
  42740. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  42741. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  42742. if (epsilon === void 0) { epsilon = 0.01; }
  42743. var _this = this;
  42744. this.name = name;
  42745. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  42746. // Members
  42747. this.animations = [];
  42748. this.renderingGroupId = 0;
  42749. this.emitter = null;
  42750. this.emitRate = 10;
  42751. this.manualEmitCount = -1;
  42752. this.updateSpeed = 0.01;
  42753. this.targetStopDuration = 0;
  42754. this.disposeOnStop = false;
  42755. this.minEmitPower = 1;
  42756. this.maxEmitPower = 1;
  42757. this.minLifeTime = 1;
  42758. this.maxLifeTime = 1;
  42759. this.minSize = 1;
  42760. this.maxSize = 1;
  42761. this.minAngularSpeed = 0;
  42762. this.maxAngularSpeed = 0;
  42763. this.layerMask = 0x0FFFFFFF;
  42764. this.customShader = null;
  42765. this.preventAutoStart = false;
  42766. /**
  42767. * An event triggered when the system is disposed.
  42768. * @type {BABYLON.Observable}
  42769. */
  42770. this.onDisposeObservable = new BABYLON.Observable();
  42771. this.onAnimationEnd = null;
  42772. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  42773. this.forceDepthWrite = false;
  42774. this.gravity = BABYLON.Vector3.Zero();
  42775. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  42776. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  42777. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  42778. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  42779. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  42780. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  42781. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  42782. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  42783. this.particles = new Array();
  42784. this._stockParticles = new Array();
  42785. this._newPartsExcess = 0;
  42786. this._vertexBuffers = {};
  42787. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  42788. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  42789. this._scaledDirection = BABYLON.Vector3.Zero();
  42790. this._scaledGravity = BABYLON.Vector3.Zero();
  42791. this._currentRenderId = -1;
  42792. this._started = false;
  42793. this._stopped = false;
  42794. this._actualFrame = 0;
  42795. // sheet animation
  42796. this.startSpriteCellID = 0;
  42797. this.endSpriteCellID = 0;
  42798. this.spriteCellLoop = true;
  42799. this.spriteCellChangeSpeed = 0;
  42800. this.spriteCellWidth = 0;
  42801. this.spriteCellHeight = 0;
  42802. this._vertexBufferSize = 11;
  42803. this.appendParticleVertexes = null;
  42804. this.id = name;
  42805. this._capacity = capacity;
  42806. this._epsilon = epsilon;
  42807. if (_isAnimationSheetEnabled) {
  42808. this._vertexBufferSize = 12;
  42809. }
  42810. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  42811. this._customEffect = customEffect;
  42812. scene.particleSystems.push(this);
  42813. this._createIndexBuffer();
  42814. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  42815. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  42816. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  42817. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  42818. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  42819. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  42820. if (this._isAnimationSheetEnabled) {
  42821. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  42822. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  42823. }
  42824. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  42825. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  42826. this._vertexBuffers["options"] = options;
  42827. // Default behaviors
  42828. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  42829. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  42830. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  42831. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  42832. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  42833. };
  42834. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  42835. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  42836. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  42837. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  42838. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  42839. };
  42840. this.updateFunction = function (particles) {
  42841. for (var index = 0; index < particles.length; index++) {
  42842. var particle = particles[index];
  42843. particle.age += _this._scaledUpdateSpeed;
  42844. if (particle.age >= particle.lifeTime) {
  42845. _this.recycleParticle(particle);
  42846. index--;
  42847. continue;
  42848. }
  42849. else {
  42850. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  42851. particle.color.addInPlace(_this._scaledColorStep);
  42852. if (particle.color.a < 0)
  42853. particle.color.a = 0;
  42854. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  42855. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  42856. particle.position.addInPlace(_this._scaledDirection);
  42857. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  42858. particle.direction.addInPlace(_this._scaledGravity);
  42859. if (_this._isAnimationSheetEnabled) {
  42860. particle.updateCellIndex(_this._scaledUpdateSpeed);
  42861. }
  42862. }
  42863. }
  42864. };
  42865. }
  42866. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  42867. set: function (callback) {
  42868. if (this._onDisposeObserver) {
  42869. this.onDisposeObservable.remove(this._onDisposeObserver);
  42870. }
  42871. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  42872. },
  42873. enumerable: true,
  42874. configurable: true
  42875. });
  42876. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  42877. get: function () {
  42878. return this._isAnimationSheetEnabled;
  42879. },
  42880. enumerable: true,
  42881. configurable: true
  42882. });
  42883. ParticleSystem.prototype._createIndexBuffer = function () {
  42884. var indices = [];
  42885. var index = 0;
  42886. for (var count = 0; count < this._capacity; count++) {
  42887. indices.push(index);
  42888. indices.push(index + 1);
  42889. indices.push(index + 2);
  42890. indices.push(index);
  42891. indices.push(index + 2);
  42892. indices.push(index + 3);
  42893. index += 4;
  42894. }
  42895. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  42896. };
  42897. ParticleSystem.prototype.recycleParticle = function (particle) {
  42898. var lastParticle = this.particles.pop();
  42899. if (lastParticle !== particle) {
  42900. lastParticle.copyTo(particle);
  42901. this._stockParticles.push(lastParticle);
  42902. }
  42903. };
  42904. ParticleSystem.prototype.getCapacity = function () {
  42905. return this._capacity;
  42906. };
  42907. ParticleSystem.prototype.isAlive = function () {
  42908. return this._alive;
  42909. };
  42910. ParticleSystem.prototype.isStarted = function () {
  42911. return this._started;
  42912. };
  42913. ParticleSystem.prototype.start = function () {
  42914. this._started = true;
  42915. this._stopped = false;
  42916. this._actualFrame = 0;
  42917. };
  42918. ParticleSystem.prototype.stop = function () {
  42919. this._stopped = true;
  42920. };
  42921. // animation sheet
  42922. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  42923. var offset = index * this._vertexBufferSize;
  42924. this._vertexData[offset] = particle.position.x;
  42925. this._vertexData[offset + 1] = particle.position.y;
  42926. this._vertexData[offset + 2] = particle.position.z;
  42927. this._vertexData[offset + 3] = particle.color.r;
  42928. this._vertexData[offset + 4] = particle.color.g;
  42929. this._vertexData[offset + 5] = particle.color.b;
  42930. this._vertexData[offset + 6] = particle.color.a;
  42931. this._vertexData[offset + 7] = particle.angle;
  42932. this._vertexData[offset + 8] = particle.size;
  42933. this._vertexData[offset + 9] = offsetX;
  42934. this._vertexData[offset + 10] = offsetY;
  42935. };
  42936. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  42937. if (offsetX === 0)
  42938. offsetX = this._epsilon;
  42939. else if (offsetX === 1)
  42940. offsetX = 1 - this._epsilon;
  42941. if (offsetY === 0)
  42942. offsetY = this._epsilon;
  42943. else if (offsetY === 1)
  42944. offsetY = 1 - this._epsilon;
  42945. var offset = index * this._vertexBufferSize;
  42946. this._vertexData[offset] = particle.position.x;
  42947. this._vertexData[offset + 1] = particle.position.y;
  42948. this._vertexData[offset + 2] = particle.position.z;
  42949. this._vertexData[offset + 3] = particle.color.r;
  42950. this._vertexData[offset + 4] = particle.color.g;
  42951. this._vertexData[offset + 5] = particle.color.b;
  42952. this._vertexData[offset + 6] = particle.color.a;
  42953. this._vertexData[offset + 7] = particle.angle;
  42954. this._vertexData[offset + 8] = particle.size;
  42955. this._vertexData[offset + 9] = offsetX;
  42956. this._vertexData[offset + 10] = offsetY;
  42957. this._vertexData[offset + 11] = particle.cellIndex;
  42958. };
  42959. ParticleSystem.prototype._update = function (newParticles) {
  42960. // Update current
  42961. this._alive = this.particles.length > 0;
  42962. this.updateFunction(this.particles);
  42963. // Add new ones
  42964. var worldMatrix;
  42965. if (this.emitter.position) {
  42966. var emitterMesh = this.emitter;
  42967. worldMatrix = emitterMesh.getWorldMatrix();
  42968. }
  42969. else {
  42970. var emitterPosition = this.emitter;
  42971. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  42972. }
  42973. var particle;
  42974. for (var index = 0; index < newParticles; index++) {
  42975. if (this.particles.length === this._capacity) {
  42976. break;
  42977. }
  42978. if (this._stockParticles.length !== 0) {
  42979. particle = this._stockParticles.pop();
  42980. particle.age = 0;
  42981. particle.cellIndex = this.startSpriteCellID;
  42982. }
  42983. else {
  42984. particle = new BABYLON.Particle(this);
  42985. }
  42986. this.particles.push(particle);
  42987. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  42988. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  42989. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  42990. particle.size = randomNumber(this.minSize, this.maxSize);
  42991. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  42992. this.startPositionFunction(worldMatrix, particle.position, particle);
  42993. var step = randomNumber(0, 1.0);
  42994. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  42995. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  42996. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  42997. }
  42998. };
  42999. ParticleSystem.prototype._getEffect = function () {
  43000. if (this._customEffect) {
  43001. return this._customEffect;
  43002. }
  43003. ;
  43004. var defines = [];
  43005. if (this._scene.clipPlane) {
  43006. defines.push("#define CLIPPLANE");
  43007. }
  43008. if (this._isAnimationSheetEnabled) {
  43009. defines.push("#define ANIMATESHEET");
  43010. }
  43011. // Effect
  43012. var join = defines.join("\n");
  43013. if (this._cachedDefines !== join) {
  43014. this._cachedDefines = join;
  43015. var attributesNamesOrOptions;
  43016. var effectCreationOption;
  43017. if (this._isAnimationSheetEnabled) {
  43018. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  43019. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  43020. }
  43021. else {
  43022. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  43023. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  43024. }
  43025. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  43026. }
  43027. return this._effect;
  43028. };
  43029. ParticleSystem.prototype.animate = function () {
  43030. if (!this._started)
  43031. return;
  43032. var effect = this._getEffect();
  43033. // Check
  43034. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  43035. return;
  43036. if (this._currentRenderId === this._scene.getRenderId()) {
  43037. return;
  43038. }
  43039. this._currentRenderId = this._scene.getRenderId();
  43040. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  43041. // determine the number of particles we need to create
  43042. var newParticles;
  43043. if (this.manualEmitCount > -1) {
  43044. newParticles = this.manualEmitCount;
  43045. this._newPartsExcess = 0;
  43046. this.manualEmitCount = 0;
  43047. }
  43048. else {
  43049. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  43050. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  43051. }
  43052. if (this._newPartsExcess > 1.0) {
  43053. newParticles += this._newPartsExcess >> 0;
  43054. this._newPartsExcess -= this._newPartsExcess >> 0;
  43055. }
  43056. this._alive = false;
  43057. if (!this._stopped) {
  43058. this._actualFrame += this._scaledUpdateSpeed;
  43059. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  43060. this.stop();
  43061. }
  43062. else {
  43063. newParticles = 0;
  43064. }
  43065. this._update(newParticles);
  43066. // Stopped?
  43067. if (this._stopped) {
  43068. if (!this._alive) {
  43069. this._started = false;
  43070. if (this.onAnimationEnd) {
  43071. this.onAnimationEnd();
  43072. }
  43073. if (this.disposeOnStop) {
  43074. this._scene._toBeDisposed.push(this);
  43075. }
  43076. }
  43077. }
  43078. // Animation sheet
  43079. if (this._isAnimationSheetEnabled) {
  43080. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  43081. }
  43082. else {
  43083. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  43084. }
  43085. // Update VBO
  43086. var offset = 0;
  43087. for (var index = 0; index < this.particles.length; index++) {
  43088. var particle = this.particles[index];
  43089. this.appendParticleVertexes(offset, particle);
  43090. offset += 4;
  43091. }
  43092. this._vertexBuffer.update(this._vertexData);
  43093. };
  43094. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  43095. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  43096. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  43097. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  43098. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  43099. };
  43100. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  43101. this._appendParticleVertex(offset++, particle, 0, 0);
  43102. this._appendParticleVertex(offset++, particle, 1, 0);
  43103. this._appendParticleVertex(offset++, particle, 1, 1);
  43104. this._appendParticleVertex(offset++, particle, 0, 1);
  43105. };
  43106. ParticleSystem.prototype.rebuild = function () {
  43107. this._createIndexBuffer();
  43108. this._vertexBuffer._rebuild();
  43109. };
  43110. ParticleSystem.prototype.render = function () {
  43111. var effect = this._getEffect();
  43112. // Check
  43113. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  43114. return 0;
  43115. var engine = this._scene.getEngine();
  43116. // Render
  43117. engine.enableEffect(effect);
  43118. engine.setState(false);
  43119. var viewMatrix = this._scene.getViewMatrix();
  43120. effect.setTexture("diffuseSampler", this.particleTexture);
  43121. effect.setMatrix("view", viewMatrix);
  43122. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  43123. if (this._isAnimationSheetEnabled) {
  43124. var baseSize = this.particleTexture.getBaseSize();
  43125. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  43126. }
  43127. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  43128. if (this._scene.clipPlane) {
  43129. var clipPlane = this._scene.clipPlane;
  43130. var invView = viewMatrix.clone();
  43131. invView.invert();
  43132. effect.setMatrix("invView", invView);
  43133. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43134. }
  43135. // VBOs
  43136. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  43137. // Draw order
  43138. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  43139. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  43140. }
  43141. else {
  43142. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43143. }
  43144. if (this.forceDepthWrite) {
  43145. engine.setDepthWrite(true);
  43146. }
  43147. engine.draw(true, 0, this.particles.length * 6);
  43148. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  43149. return this.particles.length;
  43150. };
  43151. ParticleSystem.prototype.dispose = function () {
  43152. if (this._vertexBuffer) {
  43153. this._vertexBuffer.dispose();
  43154. this._vertexBuffer = null;
  43155. }
  43156. if (this._indexBuffer) {
  43157. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  43158. this._indexBuffer = null;
  43159. }
  43160. if (this.particleTexture) {
  43161. this.particleTexture.dispose();
  43162. this.particleTexture = null;
  43163. }
  43164. // Remove from scene
  43165. var index = this._scene.particleSystems.indexOf(this);
  43166. if (index > -1) {
  43167. this._scene.particleSystems.splice(index, 1);
  43168. }
  43169. // Callback
  43170. this.onDisposeObservable.notifyObservers(this);
  43171. this.onDisposeObservable.clear();
  43172. };
  43173. // Clone
  43174. ParticleSystem.prototype.clone = function (name, newEmitter) {
  43175. var custom = null;
  43176. var program = null;
  43177. if (this.customShader != null) {
  43178. program = this.customShader;
  43179. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  43180. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  43181. }
  43182. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  43183. result.customShader = program;
  43184. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  43185. if (newEmitter === undefined) {
  43186. newEmitter = this.emitter;
  43187. }
  43188. result.emitter = newEmitter;
  43189. if (this.particleTexture) {
  43190. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  43191. }
  43192. if (!this.preventAutoStart) {
  43193. result.start();
  43194. }
  43195. return result;
  43196. };
  43197. ParticleSystem.prototype.serialize = function () {
  43198. var serializationObject = {};
  43199. serializationObject.name = this.name;
  43200. serializationObject.id = this.id;
  43201. // Emitter
  43202. if (this.emitter.position) {
  43203. var emitterMesh = this.emitter;
  43204. serializationObject.emitterId = emitterMesh.id;
  43205. }
  43206. else {
  43207. var emitterPosition = this.emitter;
  43208. serializationObject.emitter = emitterPosition.asArray();
  43209. }
  43210. serializationObject.capacity = this.getCapacity();
  43211. if (this.particleTexture) {
  43212. serializationObject.textureName = this.particleTexture.name;
  43213. }
  43214. // Animations
  43215. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  43216. // Particle system
  43217. serializationObject.minAngularSpeed = this.minAngularSpeed;
  43218. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  43219. serializationObject.minSize = this.minSize;
  43220. serializationObject.maxSize = this.maxSize;
  43221. serializationObject.minEmitPower = this.minEmitPower;
  43222. serializationObject.maxEmitPower = this.maxEmitPower;
  43223. serializationObject.minLifeTime = this.minLifeTime;
  43224. serializationObject.maxLifeTime = this.maxLifeTime;
  43225. serializationObject.emitRate = this.emitRate;
  43226. serializationObject.minEmitBox = this.minEmitBox.asArray();
  43227. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  43228. serializationObject.gravity = this.gravity.asArray();
  43229. serializationObject.direction1 = this.direction1.asArray();
  43230. serializationObject.direction2 = this.direction2.asArray();
  43231. serializationObject.color1 = this.color1.asArray();
  43232. serializationObject.color2 = this.color2.asArray();
  43233. serializationObject.colorDead = this.colorDead.asArray();
  43234. serializationObject.updateSpeed = this.updateSpeed;
  43235. serializationObject.targetStopDuration = this.targetStopDuration;
  43236. serializationObject.textureMask = this.textureMask.asArray();
  43237. serializationObject.blendMode = this.blendMode;
  43238. serializationObject.customShader = this.customShader;
  43239. serializationObject.preventAutoStart = this.preventAutoStart;
  43240. return serializationObject;
  43241. };
  43242. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  43243. var name = parsedParticleSystem.name;
  43244. var custom = null;
  43245. var program = null;
  43246. if (parsedParticleSystem.customShader) {
  43247. program = parsedParticleSystem.customShader;
  43248. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  43249. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  43250. }
  43251. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  43252. particleSystem.customShader = program;
  43253. if (parsedParticleSystem.id) {
  43254. particleSystem.id = parsedParticleSystem.id;
  43255. }
  43256. // Auto start
  43257. if (parsedParticleSystem.preventAutoStart) {
  43258. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  43259. }
  43260. // Texture
  43261. if (parsedParticleSystem.textureName) {
  43262. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  43263. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  43264. }
  43265. // Emitter
  43266. if (parsedParticleSystem.emitterId) {
  43267. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  43268. }
  43269. else {
  43270. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  43271. }
  43272. // Animations
  43273. if (parsedParticleSystem.animations) {
  43274. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  43275. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  43276. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  43277. }
  43278. }
  43279. if (parsedParticleSystem.autoAnimate) {
  43280. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  43281. }
  43282. // Particle system
  43283. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  43284. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  43285. particleSystem.minSize = parsedParticleSystem.minSize;
  43286. particleSystem.maxSize = parsedParticleSystem.maxSize;
  43287. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  43288. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  43289. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  43290. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  43291. particleSystem.emitRate = parsedParticleSystem.emitRate;
  43292. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  43293. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  43294. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  43295. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  43296. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  43297. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  43298. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  43299. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  43300. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  43301. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  43302. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  43303. particleSystem.blendMode = parsedParticleSystem.blendMode;
  43304. if (!particleSystem.preventAutoStart) {
  43305. particleSystem.start();
  43306. }
  43307. return particleSystem;
  43308. };
  43309. // Statics
  43310. ParticleSystem.BLENDMODE_ONEONE = 0;
  43311. ParticleSystem.BLENDMODE_STANDARD = 1;
  43312. return ParticleSystem;
  43313. }());
  43314. BABYLON.ParticleSystem = ParticleSystem;
  43315. })(BABYLON || (BABYLON = {}));
  43316. //# sourceMappingURL=babylon.particleSystem.js.map
  43317. var BABYLON;
  43318. (function (BABYLON) {
  43319. var SolidParticle = (function () {
  43320. /**
  43321. * Creates a Solid Particle object.
  43322. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  43323. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  43324. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  43325. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  43326. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  43327. * `shapeId` (integer) is the model shape identifier in the SPS.
  43328. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  43329. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  43330. */
  43331. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  43332. this.idx = 0; // particle global index
  43333. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  43334. this.position = BABYLON.Vector3.Zero(); // position
  43335. this.rotation = BABYLON.Vector3.Zero(); // rotation
  43336. this.scaling = BABYLON.Vector3.One(); // scaling
  43337. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  43338. this.velocity = BABYLON.Vector3.Zero(); // velocity
  43339. this.alive = true; // alive
  43340. this.isVisible = true; // visibility
  43341. this._pos = 0; // index of this particle in the global "positions" array
  43342. this._ind = 0; // index of this particle in the global "indices" array
  43343. this.shapeId = 0; // model shape id
  43344. this.idxInShape = 0; // index of the particle in its shape id
  43345. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  43346. this.idx = particleIndex;
  43347. this._pos = positionIndex;
  43348. this._ind = indiceIndex;
  43349. this._model = model;
  43350. this.shapeId = shapeId;
  43351. this.idxInShape = idxInShape;
  43352. this._sps = sps;
  43353. if (modelBoundingInfo) {
  43354. this._modelBoundingInfo = modelBoundingInfo;
  43355. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  43356. }
  43357. }
  43358. Object.defineProperty(SolidParticle.prototype, "scale", {
  43359. /**
  43360. * legacy support, changed scale to scaling
  43361. */
  43362. get: function () {
  43363. return this.scaling;
  43364. },
  43365. set: function (scale) {
  43366. this.scaling = scale;
  43367. },
  43368. enumerable: true,
  43369. configurable: true
  43370. });
  43371. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  43372. /**
  43373. * legacy support, changed quaternion to rotationQuaternion
  43374. */
  43375. get: function () {
  43376. return this.rotationQuaternion;
  43377. },
  43378. set: function (q) {
  43379. this.rotationQuaternion = q;
  43380. },
  43381. enumerable: true,
  43382. configurable: true
  43383. });
  43384. /**
  43385. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  43386. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  43387. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  43388. */
  43389. SolidParticle.prototype.intersectsMesh = function (target) {
  43390. if (!this._boundingInfo || !target._boundingInfo) {
  43391. return false;
  43392. }
  43393. if (this._sps._bSphereOnly) {
  43394. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  43395. }
  43396. return this._boundingInfo.intersects(target._boundingInfo, false);
  43397. };
  43398. return SolidParticle;
  43399. }());
  43400. BABYLON.SolidParticle = SolidParticle;
  43401. var ModelShape = (function () {
  43402. /**
  43403. * 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.
  43404. * SPS internal tool, don't use it manually.
  43405. */
  43406. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  43407. this._indicesLength = 0; // length of the shape in the model indices array
  43408. this.shapeID = id;
  43409. this._shape = shape;
  43410. this._indicesLength = indicesLength;
  43411. this._shapeUV = shapeUV;
  43412. this._positionFunction = posFunction;
  43413. this._vertexFunction = vtxFunction;
  43414. }
  43415. return ModelShape;
  43416. }());
  43417. BABYLON.ModelShape = ModelShape;
  43418. var DepthSortedParticle = (function () {
  43419. function DepthSortedParticle() {
  43420. this.ind = 0; // index of the particle in the "indices" array
  43421. this.indicesLength = 0; // length of the particle shape in the "indices" array
  43422. this.sqDistance = 0.0; // squared distance from the particle to the camera
  43423. }
  43424. return DepthSortedParticle;
  43425. }());
  43426. BABYLON.DepthSortedParticle = DepthSortedParticle;
  43427. })(BABYLON || (BABYLON = {}));
  43428. //# sourceMappingURL=babylon.solidParticle.js.map
  43429. var BABYLON;
  43430. (function (BABYLON) {
  43431. /**
  43432. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  43433. */
  43434. var SolidParticleSystem = (function () {
  43435. /**
  43436. * Creates a SPS (Solid Particle System) object.
  43437. * `name` (String) is the SPS name, this will be the underlying mesh name.
  43438. * `scene` (Scene) is the scene in which the SPS is added.
  43439. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  43440. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  43441. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  43442. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  43443. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  43444. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  43445. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  43446. */
  43447. function SolidParticleSystem(name, scene, options) {
  43448. // public members
  43449. /**
  43450. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  43451. * Example : var p = SPS.particles[i];
  43452. */
  43453. this.particles = new Array();
  43454. /**
  43455. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  43456. */
  43457. this.nbParticles = 0;
  43458. /**
  43459. * If the particles must ever face the camera (default false). Useful for planar particles.
  43460. */
  43461. this.billboard = false;
  43462. /**
  43463. * Recompute normals when adding a shape
  43464. */
  43465. this.recomputeNormals = true;
  43466. /**
  43467. * This a counter ofr your own usage. It's not set by any SPS functions.
  43468. */
  43469. this.counter = 0;
  43470. /**
  43471. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  43472. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  43473. */
  43474. this.vars = {};
  43475. this._positions = new Array();
  43476. this._indices = new Array();
  43477. this._normals = new Array();
  43478. this._colors = new Array();
  43479. this._uvs = new Array();
  43480. this._index = 0; // indices index
  43481. this._updatable = true;
  43482. this._pickable = false;
  43483. this._isVisibilityBoxLocked = false;
  43484. this._alwaysVisible = false;
  43485. this._depthSort = false;
  43486. this._shapeCounter = 0;
  43487. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null, null);
  43488. this._color = new BABYLON.Color4(0, 0, 0, 0);
  43489. this._computeParticleColor = true;
  43490. this._computeParticleTexture = true;
  43491. this._computeParticleRotation = true;
  43492. this._computeParticleVertex = false;
  43493. this._computeBoundingBox = false;
  43494. this._depthSortParticles = true;
  43495. this._cam_axisZ = BABYLON.Vector3.Zero();
  43496. this._cam_axisY = BABYLON.Vector3.Zero();
  43497. this._cam_axisX = BABYLON.Vector3.Zero();
  43498. this._axisZ = BABYLON.Axis.Z;
  43499. this._camDir = BABYLON.Vector3.Zero();
  43500. this._camInvertedPosition = BABYLON.Vector3.Zero();
  43501. this._rotMatrix = new BABYLON.Matrix();
  43502. this._invertMatrix = new BABYLON.Matrix();
  43503. this._rotated = BABYLON.Vector3.Zero();
  43504. this._quaternion = new BABYLON.Quaternion();
  43505. this._vertex = BABYLON.Vector3.Zero();
  43506. this._normal = BABYLON.Vector3.Zero();
  43507. this._yaw = 0.0;
  43508. this._pitch = 0.0;
  43509. this._roll = 0.0;
  43510. this._halfroll = 0.0;
  43511. this._halfpitch = 0.0;
  43512. this._halfyaw = 0.0;
  43513. this._sinRoll = 0.0;
  43514. this._cosRoll = 0.0;
  43515. this._sinPitch = 0.0;
  43516. this._cosPitch = 0.0;
  43517. this._sinYaw = 0.0;
  43518. this._cosYaw = 0.0;
  43519. this._mustUnrotateFixedNormals = false;
  43520. this._minimum = BABYLON.Tmp.Vector3[0];
  43521. this._maximum = BABYLON.Tmp.Vector3[1];
  43522. this._minBbox = BABYLON.Tmp.Vector3[4];
  43523. this._maxBbox = BABYLON.Tmp.Vector3[5];
  43524. this._particlesIntersect = false;
  43525. this._depthSortFunction = function (p1, p2) {
  43526. return (p2.sqDistance - p1.sqDistance);
  43527. };
  43528. this._needs32Bits = false;
  43529. this._bSphereOnly = false;
  43530. this._bSphereRadiusFactor = 1.0;
  43531. this.name = name;
  43532. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  43533. this._camera = scene.activeCamera;
  43534. this._pickable = options ? options.isPickable : false;
  43535. this._depthSort = options ? options.enableDepthSort : false;
  43536. this._particlesIntersect = options ? options.particleIntersection : false;
  43537. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  43538. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  43539. if (options && options.updatable) {
  43540. this._updatable = options.updatable;
  43541. }
  43542. else {
  43543. this._updatable = true;
  43544. }
  43545. if (this._pickable) {
  43546. this.pickedParticles = [];
  43547. }
  43548. if (this._depthSort) {
  43549. this.depthSortedParticles = [];
  43550. }
  43551. }
  43552. /**
  43553. * Builds the SPS underlying mesh. Returns a standard Mesh.
  43554. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  43555. */
  43556. SolidParticleSystem.prototype.buildMesh = function () {
  43557. if (this.nbParticles === 0) {
  43558. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  43559. this.addShape(triangle, 1);
  43560. triangle.dispose();
  43561. }
  43562. this._positions32 = new Float32Array(this._positions);
  43563. this._uvs32 = new Float32Array(this._uvs);
  43564. this._colors32 = new Float32Array(this._colors);
  43565. if (this.recomputeNormals) {
  43566. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  43567. }
  43568. this._normals32 = new Float32Array(this._normals);
  43569. this._fixedNormal32 = new Float32Array(this._normals);
  43570. if (this._mustUnrotateFixedNormals) {
  43571. this._unrotateFixedNormals();
  43572. }
  43573. var vertexData = new BABYLON.VertexData();
  43574. if (this._depthSort) {
  43575. this._depthSortedIndices = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  43576. vertexData.indices = this._depthSortedIndices;
  43577. }
  43578. else {
  43579. vertexData.indices = this._indices;
  43580. }
  43581. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  43582. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  43583. if (this._uvs32) {
  43584. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  43585. ;
  43586. }
  43587. if (this._colors32) {
  43588. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  43589. }
  43590. var mesh = new BABYLON.Mesh(this.name, this._scene);
  43591. vertexData.applyToMesh(mesh, this._updatable);
  43592. this.mesh = mesh;
  43593. this.mesh.isPickable = this._pickable;
  43594. // free memory
  43595. this._positions = null;
  43596. this._normals = null;
  43597. this._uvs = null;
  43598. this._colors = null;
  43599. if (!this._updatable) {
  43600. this.particles.length = 0;
  43601. }
  43602. return mesh;
  43603. };
  43604. /**
  43605. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  43606. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  43607. * Thus the particles generated from `digest()` have their property `position` set yet.
  43608. * `mesh` ( Mesh ) is the mesh to be digested
  43609. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  43610. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  43611. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  43612. */
  43613. SolidParticleSystem.prototype.digest = function (mesh, options) {
  43614. var size = (options && options.facetNb) || 1;
  43615. var number = (options && options.number);
  43616. var delta = (options && options.delta) || 0;
  43617. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43618. var meshInd = mesh.getIndices();
  43619. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43620. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  43621. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43622. var f = 0; // facet counter
  43623. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  43624. // compute size from number
  43625. if (number) {
  43626. number = (number > totalFacets) ? totalFacets : number;
  43627. size = Math.round(totalFacets / number);
  43628. delta = 0;
  43629. }
  43630. else {
  43631. size = (size > totalFacets) ? totalFacets : size;
  43632. }
  43633. var facetPos = []; // submesh positions
  43634. var facetInd = []; // submesh indices
  43635. var facetUV = []; // submesh UV
  43636. var facetCol = []; // submesh colors
  43637. var barycenter = BABYLON.Tmp.Vector3[0];
  43638. var sizeO = size;
  43639. while (f < totalFacets) {
  43640. size = sizeO + Math.floor((1 + delta) * Math.random());
  43641. if (f > totalFacets - size) {
  43642. size = totalFacets - f;
  43643. }
  43644. // reset temp arrays
  43645. facetPos.length = 0;
  43646. facetInd.length = 0;
  43647. facetUV.length = 0;
  43648. facetCol.length = 0;
  43649. // iterate over "size" facets
  43650. var fi = 0;
  43651. for (var j = f * 3; j < (f + size) * 3; j++) {
  43652. facetInd.push(fi);
  43653. var i = meshInd[j];
  43654. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  43655. if (meshUV) {
  43656. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  43657. }
  43658. if (meshCol) {
  43659. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  43660. }
  43661. fi++;
  43662. }
  43663. // create a model shape for each single particle
  43664. var idx = this.nbParticles;
  43665. var shape = this._posToShape(facetPos);
  43666. var shapeUV = this._uvsToShapeUV(facetUV);
  43667. // compute the barycenter of the shape
  43668. var v;
  43669. for (v = 0; v < shape.length; v++) {
  43670. barycenter.addInPlace(shape[v]);
  43671. }
  43672. barycenter.scaleInPlace(1 / shape.length);
  43673. // shift the shape from its barycenter to the origin
  43674. for (v = 0; v < shape.length; v++) {
  43675. shape[v].subtractInPlace(barycenter);
  43676. }
  43677. var bInfo;
  43678. if (this._particlesIntersect) {
  43679. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  43680. }
  43681. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  43682. // add the particle in the SPS
  43683. var currentPos = this._positions.length;
  43684. var currentInd = this._indices.length;
  43685. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  43686. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  43687. // initialize the particle position
  43688. this.particles[this.nbParticles].position.addInPlace(barycenter);
  43689. this._index += shape.length;
  43690. idx++;
  43691. this.nbParticles++;
  43692. this._shapeCounter++;
  43693. f += size;
  43694. }
  43695. return this;
  43696. };
  43697. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  43698. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  43699. var index = 0;
  43700. var idx = 0;
  43701. for (var p = 0; p < this.particles.length; p++) {
  43702. this._particle = this.particles[p];
  43703. this._shape = this._particle._model._shape;
  43704. if (this._particle.rotationQuaternion) {
  43705. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  43706. }
  43707. else {
  43708. this._yaw = this._particle.rotation.y;
  43709. this._pitch = this._particle.rotation.x;
  43710. this._roll = this._particle.rotation.z;
  43711. this._quaternionRotationYPR();
  43712. }
  43713. this._quaternionToRotationMatrix();
  43714. this._rotMatrix.invertToRef(this._invertMatrix);
  43715. for (var pt = 0; pt < this._shape.length; pt++) {
  43716. idx = index + pt * 3;
  43717. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  43718. this._fixedNormal32[idx] = this._normal.x;
  43719. this._fixedNormal32[idx + 1] = this._normal.y;
  43720. this._fixedNormal32[idx + 2] = this._normal.z;
  43721. }
  43722. index = idx + 3;
  43723. }
  43724. };
  43725. //reset copy
  43726. SolidParticleSystem.prototype._resetCopy = function () {
  43727. this._copy.position.x = 0;
  43728. this._copy.position.y = 0;
  43729. this._copy.position.z = 0;
  43730. this._copy.rotation.x = 0;
  43731. this._copy.rotation.y = 0;
  43732. this._copy.rotation.z = 0;
  43733. this._copy.rotationQuaternion = null;
  43734. this._copy.scaling.x = 1.0;
  43735. this._copy.scaling.y = 1.0;
  43736. this._copy.scaling.z = 1.0;
  43737. this._copy.uvs.x = 0;
  43738. this._copy.uvs.y = 0;
  43739. this._copy.uvs.z = 1.0;
  43740. this._copy.uvs.w = 1.0;
  43741. this._copy.color = null;
  43742. };
  43743. // _meshBuilder : inserts the shape model in the global SPS mesh
  43744. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  43745. var i;
  43746. var u = 0;
  43747. var c = 0;
  43748. var n = 0;
  43749. this._resetCopy();
  43750. if (options && options.positionFunction) {
  43751. options.positionFunction(this._copy, idx, idxInShape);
  43752. this._mustUnrotateFixedNormals = true;
  43753. }
  43754. if (this._copy.rotationQuaternion) {
  43755. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  43756. }
  43757. else {
  43758. this._yaw = this._copy.rotation.y;
  43759. this._pitch = this._copy.rotation.x;
  43760. this._roll = this._copy.rotation.z;
  43761. this._quaternionRotationYPR();
  43762. }
  43763. this._quaternionToRotationMatrix();
  43764. for (i = 0; i < shape.length; i++) {
  43765. this._vertex.x = shape[i].x;
  43766. this._vertex.y = shape[i].y;
  43767. this._vertex.z = shape[i].z;
  43768. if (options && options.vertexFunction) {
  43769. options.vertexFunction(this._copy, this._vertex, i);
  43770. }
  43771. this._vertex.x *= this._copy.scaling.x;
  43772. this._vertex.y *= this._copy.scaling.y;
  43773. this._vertex.z *= this._copy.scaling.z;
  43774. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  43775. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  43776. if (meshUV) {
  43777. 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);
  43778. u += 2;
  43779. }
  43780. if (this._copy.color) {
  43781. this._color = this._copy.color;
  43782. }
  43783. else if (meshCol && meshCol[c] !== undefined) {
  43784. this._color.r = meshCol[c];
  43785. this._color.g = meshCol[c + 1];
  43786. this._color.b = meshCol[c + 2];
  43787. this._color.a = meshCol[c + 3];
  43788. }
  43789. else {
  43790. this._color.r = 1.0;
  43791. this._color.g = 1.0;
  43792. this._color.b = 1.0;
  43793. this._color.a = 1.0;
  43794. }
  43795. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  43796. c += 4;
  43797. if (!this.recomputeNormals && meshNor) {
  43798. this._normal.x = meshNor[n];
  43799. this._normal.y = meshNor[n + 1];
  43800. this._normal.z = meshNor[n + 2];
  43801. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  43802. normals.push(this._normal.x, this._normal.y, this._normal.z);
  43803. n += 3;
  43804. }
  43805. }
  43806. for (i = 0; i < meshInd.length; i++) {
  43807. var current_ind = p + meshInd[i];
  43808. indices.push(current_ind);
  43809. if (current_ind > 65535) {
  43810. this._needs32Bits = true;
  43811. }
  43812. }
  43813. if (this._pickable) {
  43814. var nbfaces = meshInd.length / 3;
  43815. for (i = 0; i < nbfaces; i++) {
  43816. this.pickedParticles.push({ idx: idx, faceId: i });
  43817. }
  43818. }
  43819. if (this._depthSort) {
  43820. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  43821. }
  43822. return this._copy;
  43823. };
  43824. // returns a shape array from positions array
  43825. SolidParticleSystem.prototype._posToShape = function (positions) {
  43826. var shape = [];
  43827. for (var i = 0; i < positions.length; i += 3) {
  43828. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  43829. }
  43830. return shape;
  43831. };
  43832. // returns a shapeUV array from a Vector4 uvs
  43833. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  43834. var shapeUV = [];
  43835. if (uvs) {
  43836. for (var i = 0; i < uvs.length; i++)
  43837. shapeUV.push(uvs[i]);
  43838. }
  43839. return shapeUV;
  43840. };
  43841. // adds a new particle object in the particles array
  43842. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  43843. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  43844. this.particles.push(sp);
  43845. return sp;
  43846. };
  43847. /**
  43848. * Adds some particles to the SPS from the model shape. Returns the shape id.
  43849. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  43850. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  43851. * `nb` (positive integer) the number of particles to be created from this model
  43852. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  43853. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  43854. */
  43855. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  43856. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43857. var meshInd = mesh.getIndices();
  43858. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43859. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  43860. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43861. var bbInfo;
  43862. if (this._particlesIntersect) {
  43863. bbInfo = mesh.getBoundingInfo();
  43864. }
  43865. var shape = this._posToShape(meshPos);
  43866. var shapeUV = this._uvsToShapeUV(meshUV);
  43867. var posfunc = options ? options.positionFunction : null;
  43868. var vtxfunc = options ? options.vertexFunction : null;
  43869. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  43870. // particles
  43871. var sp;
  43872. var currentCopy;
  43873. var idx = this.nbParticles;
  43874. for (var i = 0; i < nb; i++) {
  43875. var currentPos = this._positions.length;
  43876. var currentInd = this._indices.length;
  43877. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  43878. if (this._updatable) {
  43879. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  43880. sp.position.copyFrom(currentCopy.position);
  43881. sp.rotation.copyFrom(currentCopy.rotation);
  43882. if (currentCopy.rotationQuaternion) {
  43883. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  43884. }
  43885. if (currentCopy.color) {
  43886. sp.color.copyFrom(currentCopy.color);
  43887. }
  43888. sp.scaling.copyFrom(currentCopy.scaling);
  43889. sp.uvs.copyFrom(currentCopy.uvs);
  43890. }
  43891. this._index += shape.length;
  43892. idx++;
  43893. }
  43894. this.nbParticles += nb;
  43895. this._shapeCounter++;
  43896. return this._shapeCounter - 1;
  43897. };
  43898. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  43899. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  43900. this._resetCopy();
  43901. if (particle._model._positionFunction) {
  43902. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  43903. }
  43904. if (this._copy.rotationQuaternion) {
  43905. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  43906. }
  43907. else {
  43908. this._yaw = this._copy.rotation.y;
  43909. this._pitch = this._copy.rotation.x;
  43910. this._roll = this._copy.rotation.z;
  43911. this._quaternionRotationYPR();
  43912. }
  43913. this._quaternionToRotationMatrix();
  43914. this._shape = particle._model._shape;
  43915. for (var pt = 0; pt < this._shape.length; pt++) {
  43916. this._vertex.x = this._shape[pt].x;
  43917. this._vertex.y = this._shape[pt].y;
  43918. this._vertex.z = this._shape[pt].z;
  43919. if (particle._model._vertexFunction) {
  43920. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  43921. }
  43922. this._vertex.x *= this._copy.scaling.x;
  43923. this._vertex.y *= this._copy.scaling.y;
  43924. this._vertex.z *= this._copy.scaling.z;
  43925. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  43926. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  43927. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  43928. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  43929. }
  43930. particle.position.x = 0.0;
  43931. particle.position.y = 0.0;
  43932. particle.position.z = 0.0;
  43933. particle.rotation.x = 0.0;
  43934. particle.rotation.y = 0.0;
  43935. particle.rotation.z = 0.0;
  43936. particle.rotationQuaternion = null;
  43937. particle.scaling.x = 1.0;
  43938. particle.scaling.y = 1.0;
  43939. particle.scaling.z = 1.0;
  43940. };
  43941. /**
  43942. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  43943. * Returns the SPS.
  43944. */
  43945. SolidParticleSystem.prototype.rebuildMesh = function () {
  43946. for (var p = 0; p < this.particles.length; p++) {
  43947. this._rebuildParticle(this.particles[p]);
  43948. }
  43949. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  43950. return this;
  43951. };
  43952. /**
  43953. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  43954. * This method calls `updateParticle()` for each particle of the SPS.
  43955. * For an animated SPS, it is usually called within the render loop.
  43956. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  43957. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  43958. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  43959. * Returns the SPS.
  43960. */
  43961. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  43962. if (start === void 0) { start = 0; }
  43963. if (end === void 0) { end = this.nbParticles - 1; }
  43964. if (update === void 0) { update = true; }
  43965. if (!this._updatable) {
  43966. return this;
  43967. }
  43968. // custom beforeUpdate
  43969. this.beforeUpdateParticles(start, end, update);
  43970. this._cam_axisX.x = 1.0;
  43971. this._cam_axisX.y = 0.0;
  43972. this._cam_axisX.z = 0.0;
  43973. this._cam_axisY.x = 0.0;
  43974. this._cam_axisY.y = 1.0;
  43975. this._cam_axisY.z = 0.0;
  43976. this._cam_axisZ.x = 0.0;
  43977. this._cam_axisZ.y = 0.0;
  43978. this._cam_axisZ.z = 1.0;
  43979. // cases when the World Matrix is to be computed first
  43980. if (this.billboard || this._depthSort) {
  43981. this.mesh.computeWorldMatrix(true);
  43982. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  43983. }
  43984. // if the particles will always face the camera
  43985. if (this.billboard) {
  43986. // compute the camera position and un-rotate it by the current mesh rotation
  43987. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  43988. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  43989. this._cam_axisZ.normalize();
  43990. // same for camera up vector extracted from the cam view matrix
  43991. var view = this._camera.getViewMatrix(true);
  43992. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  43993. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  43994. this._cam_axisY.normalize();
  43995. this._cam_axisX.normalize();
  43996. }
  43997. // if depthSort, compute the camera global position in the mesh local system
  43998. if (this._depthSort) {
  43999. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  44000. }
  44001. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  44002. var idx = 0; // current position index in the global array positions32
  44003. var index = 0; // position start index in the global array positions32 of the current particle
  44004. var colidx = 0; // current color index in the global array colors32
  44005. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  44006. var uvidx = 0; // current uv index in the global array uvs32
  44007. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  44008. var pt = 0; // current index in the particle model shape
  44009. if (this.mesh.isFacetDataEnabled) {
  44010. this._computeBoundingBox = true;
  44011. }
  44012. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  44013. if (this._computeBoundingBox) {
  44014. if (start == 0 && end == this.nbParticles - 1) {
  44015. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  44016. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  44017. }
  44018. else {
  44019. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  44020. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  44021. }
  44022. }
  44023. // particle loop
  44024. index = this.particles[start]._pos;
  44025. var vpos = (index / 3) | 0;
  44026. colorIndex = vpos * 4;
  44027. uvIndex = vpos * 2;
  44028. for (var p = start; p <= end; p++) {
  44029. this._particle = this.particles[p];
  44030. this._shape = this._particle._model._shape;
  44031. this._shapeUV = this._particle._model._shapeUV;
  44032. // call to custom user function to update the particle properties
  44033. this.updateParticle(this._particle);
  44034. // skip the computations for inactive or already invisible particles
  44035. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  44036. // increment indexes for the next particle
  44037. pt = this._shape.length;
  44038. index += pt * 3;
  44039. colorIndex += pt * 4;
  44040. uvIndex += pt * 2;
  44041. continue;
  44042. }
  44043. if (this._particle.isVisible) {
  44044. this._particle._stillInvisible = false; // un-mark permanent invisibility
  44045. // particle rotation matrix
  44046. if (this.billboard) {
  44047. this._particle.rotation.x = 0.0;
  44048. this._particle.rotation.y = 0.0;
  44049. }
  44050. if (this._computeParticleRotation || this.billboard) {
  44051. if (this._particle.rotationQuaternion) {
  44052. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  44053. }
  44054. else {
  44055. this._yaw = this._particle.rotation.y;
  44056. this._pitch = this._particle.rotation.x;
  44057. this._roll = this._particle.rotation.z;
  44058. this._quaternionRotationYPR();
  44059. }
  44060. this._quaternionToRotationMatrix();
  44061. }
  44062. // camera-particle distance for depth sorting
  44063. if (this._depthSort && this._depthSortParticles) {
  44064. var dsp = this.depthSortedParticles[p];
  44065. dsp.ind = this._particle._ind;
  44066. dsp.indicesLength = this._particle._model._indicesLength;
  44067. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  44068. }
  44069. // particle vertex loop
  44070. for (pt = 0; pt < this._shape.length; pt++) {
  44071. idx = index + pt * 3;
  44072. colidx = colorIndex + pt * 4;
  44073. uvidx = uvIndex + pt * 2;
  44074. this._vertex.x = this._shape[pt].x;
  44075. this._vertex.y = this._shape[pt].y;
  44076. this._vertex.z = this._shape[pt].z;
  44077. if (this._computeParticleVertex) {
  44078. this.updateParticleVertex(this._particle, this._vertex, pt);
  44079. }
  44080. // positions
  44081. this._vertex.x *= this._particle.scaling.x;
  44082. this._vertex.y *= this._particle.scaling.y;
  44083. this._vertex.z *= this._particle.scaling.z;
  44084. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  44085. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  44086. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  44087. 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;
  44088. 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;
  44089. 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;
  44090. if (this._computeBoundingBox) {
  44091. if (this._positions32[idx] < this._minimum.x) {
  44092. this._minimum.x = this._positions32[idx];
  44093. }
  44094. if (this._positions32[idx] > this._maximum.x) {
  44095. this._maximum.x = this._positions32[idx];
  44096. }
  44097. if (this._positions32[idx + 1] < this._minimum.y) {
  44098. this._minimum.y = this._positions32[idx + 1];
  44099. }
  44100. if (this._positions32[idx + 1] > this._maximum.y) {
  44101. this._maximum.y = this._positions32[idx + 1];
  44102. }
  44103. if (this._positions32[idx + 2] < this._minimum.z) {
  44104. this._minimum.z = this._positions32[idx + 2];
  44105. }
  44106. if (this._positions32[idx + 2] > this._maximum.z) {
  44107. this._maximum.z = this._positions32[idx + 2];
  44108. }
  44109. }
  44110. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  44111. if (!this._computeParticleVertex) {
  44112. this._normal.x = this._fixedNormal32[idx];
  44113. this._normal.y = this._fixedNormal32[idx + 1];
  44114. this._normal.z = this._fixedNormal32[idx + 2];
  44115. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  44116. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  44117. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  44118. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  44119. 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;
  44120. 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;
  44121. }
  44122. if (this._computeParticleColor) {
  44123. this._colors32[colidx] = this._particle.color.r;
  44124. this._colors32[colidx + 1] = this._particle.color.g;
  44125. this._colors32[colidx + 2] = this._particle.color.b;
  44126. this._colors32[colidx + 3] = this._particle.color.a;
  44127. }
  44128. if (this._computeParticleTexture) {
  44129. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  44130. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  44131. }
  44132. }
  44133. }
  44134. else {
  44135. this._particle._stillInvisible = true; // mark the particle as invisible
  44136. for (pt = 0; pt < this._shape.length; pt++) {
  44137. idx = index + pt * 3;
  44138. colidx = colorIndex + pt * 4;
  44139. uvidx = uvIndex + pt * 2;
  44140. this._positions32[idx] = 0.0;
  44141. this._positions32[idx + 1] = 0.0;
  44142. this._positions32[idx + 2] = 0.0;
  44143. this._normals32[idx] = 0.0;
  44144. this._normals32[idx + 1] = 0.0;
  44145. this._normals32[idx + 2] = 0.0;
  44146. if (this._computeParticleColor) {
  44147. this._colors32[colidx] = this._particle.color.r;
  44148. this._colors32[colidx + 1] = this._particle.color.g;
  44149. this._colors32[colidx + 2] = this._particle.color.b;
  44150. this._colors32[colidx + 3] = this._particle.color.a;
  44151. }
  44152. if (this._computeParticleTexture) {
  44153. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  44154. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  44155. }
  44156. }
  44157. }
  44158. // if the particle intersections must be computed : update the bbInfo
  44159. if (this._particlesIntersect) {
  44160. var bInfo = this._particle._boundingInfo;
  44161. var bBox = bInfo.boundingBox;
  44162. var bSphere = bInfo.boundingSphere;
  44163. if (!this._bSphereOnly) {
  44164. // place, scale and rotate the particle bbox within the SPS local system, then update it
  44165. for (var b = 0; b < bBox.vectors.length; b++) {
  44166. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  44167. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  44168. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  44169. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  44170. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  44171. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  44172. 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;
  44173. 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;
  44174. 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;
  44175. }
  44176. bBox._update(this.mesh._worldMatrix);
  44177. }
  44178. // place and scale the particle bouding sphere in the SPS local system, then update it
  44179. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  44180. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  44181. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  44182. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  44183. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  44184. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  44185. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  44186. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  44187. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  44188. 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));
  44189. bSphere._update(this.mesh._worldMatrix);
  44190. }
  44191. // increment indexes for the next particle
  44192. index = idx + 3;
  44193. colorIndex = colidx + 4;
  44194. uvIndex = uvidx + 2;
  44195. }
  44196. // if the VBO must be updated
  44197. if (update) {
  44198. if (this._computeParticleColor) {
  44199. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  44200. }
  44201. if (this._computeParticleTexture) {
  44202. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  44203. }
  44204. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  44205. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  44206. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  44207. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  44208. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  44209. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  44210. for (var i = 0; i < this._normals32.length; i++) {
  44211. this._fixedNormal32[i] = this._normals32[i];
  44212. }
  44213. }
  44214. if (!this.mesh.areNormalsFrozen) {
  44215. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  44216. }
  44217. }
  44218. if (this._depthSort && this._depthSortParticles) {
  44219. this.depthSortedParticles.sort(this._depthSortFunction);
  44220. var dspl = this.depthSortedParticles.length;
  44221. var sorted = 0;
  44222. var lind = 0;
  44223. var sind = 0;
  44224. var sid = 0;
  44225. for (sorted = 0; sorted < dspl; sorted++) {
  44226. lind = this.depthSortedParticles[sorted].indicesLength;
  44227. sind = this.depthSortedParticles[sorted].ind;
  44228. for (var i = 0; i < lind; i++) {
  44229. this._depthSortedIndices[sid] = this._indices[sind + i];
  44230. sid++;
  44231. }
  44232. }
  44233. this.mesh.updateIndices(this._depthSortedIndices);
  44234. }
  44235. }
  44236. if (this._computeBoundingBox) {
  44237. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  44238. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  44239. }
  44240. this.afterUpdateParticles(start, end, update);
  44241. return this;
  44242. };
  44243. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  44244. this._halfroll = this._roll * 0.5;
  44245. this._halfpitch = this._pitch * 0.5;
  44246. this._halfyaw = this._yaw * 0.5;
  44247. this._sinRoll = Math.sin(this._halfroll);
  44248. this._cosRoll = Math.cos(this._halfroll);
  44249. this._sinPitch = Math.sin(this._halfpitch);
  44250. this._cosPitch = Math.cos(this._halfpitch);
  44251. this._sinYaw = Math.sin(this._halfyaw);
  44252. this._cosYaw = Math.cos(this._halfyaw);
  44253. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  44254. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  44255. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  44256. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  44257. };
  44258. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  44259. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  44260. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  44261. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  44262. this._rotMatrix.m[3] = 0;
  44263. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  44264. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  44265. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  44266. this._rotMatrix.m[7] = 0;
  44267. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  44268. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  44269. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  44270. this._rotMatrix.m[11] = 0;
  44271. this._rotMatrix.m[12] = 0;
  44272. this._rotMatrix.m[13] = 0;
  44273. this._rotMatrix.m[14] = 0;
  44274. this._rotMatrix.m[15] = 1.0;
  44275. };
  44276. /**
  44277. * Disposes the SPS.
  44278. * Returns nothing.
  44279. */
  44280. SolidParticleSystem.prototype.dispose = function () {
  44281. this.mesh.dispose();
  44282. this.vars = null;
  44283. // drop references to internal big arrays for the GC
  44284. this._positions = null;
  44285. this._indices = null;
  44286. this._normals = null;
  44287. this._uvs = null;
  44288. this._colors = null;
  44289. this._positions32 = null;
  44290. this._normals32 = null;
  44291. this._fixedNormal32 = null;
  44292. this._uvs32 = null;
  44293. this._colors32 = null;
  44294. this.pickedParticles = null;
  44295. };
  44296. /**
  44297. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  44298. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  44299. * Returns the SPS.
  44300. */
  44301. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  44302. if (!this._isVisibilityBoxLocked) {
  44303. this.mesh.refreshBoundingInfo();
  44304. }
  44305. return this;
  44306. };
  44307. /**
  44308. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  44309. * @param size the size (float) of the visibility box
  44310. * note : this doesn't lock the SPS mesh bounding box.
  44311. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  44312. */
  44313. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  44314. var vis = size / 2;
  44315. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  44316. };
  44317. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  44318. // getter and setter
  44319. get: function () {
  44320. return this._alwaysVisible;
  44321. },
  44322. /**
  44323. * Sets the SPS as always visible or not
  44324. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  44325. */
  44326. set: function (val) {
  44327. this._alwaysVisible = val;
  44328. this.mesh.alwaysSelectAsActiveMesh = val;
  44329. },
  44330. enumerable: true,
  44331. configurable: true
  44332. });
  44333. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  44334. get: function () {
  44335. return this._isVisibilityBoxLocked;
  44336. },
  44337. /**
  44338. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  44339. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  44340. */
  44341. set: function (val) {
  44342. this._isVisibilityBoxLocked = val;
  44343. this.mesh.getBoundingInfo().isLocked = val;
  44344. },
  44345. enumerable: true,
  44346. configurable: true
  44347. });
  44348. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  44349. // getters
  44350. get: function () {
  44351. return this._computeParticleRotation;
  44352. },
  44353. // Optimizer setters
  44354. /**
  44355. * Tells to `setParticles()` to compute the particle rotations or not.
  44356. * Default value : true. The SPS is faster when it's set to false.
  44357. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  44358. */
  44359. set: function (val) {
  44360. this._computeParticleRotation = val;
  44361. },
  44362. enumerable: true,
  44363. configurable: true
  44364. });
  44365. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  44366. get: function () {
  44367. return this._computeParticleColor;
  44368. },
  44369. /**
  44370. * Tells to `setParticles()` to compute the particle colors or not.
  44371. * Default value : true. The SPS is faster when it's set to false.
  44372. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  44373. */
  44374. set: function (val) {
  44375. this._computeParticleColor = val;
  44376. },
  44377. enumerable: true,
  44378. configurable: true
  44379. });
  44380. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  44381. get: function () {
  44382. return this._computeParticleTexture;
  44383. },
  44384. /**
  44385. * Tells to `setParticles()` to compute the particle textures or not.
  44386. * Default value : true. The SPS is faster when it's set to false.
  44387. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  44388. */
  44389. set: function (val) {
  44390. this._computeParticleTexture = val;
  44391. },
  44392. enumerable: true,
  44393. configurable: true
  44394. });
  44395. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  44396. get: function () {
  44397. return this._computeParticleVertex;
  44398. },
  44399. /**
  44400. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  44401. * Default value : false. The SPS is faster when it's set to false.
  44402. * Note : the particle custom vertex positions aren't stored values.
  44403. */
  44404. set: function (val) {
  44405. this._computeParticleVertex = val;
  44406. },
  44407. enumerable: true,
  44408. configurable: true
  44409. });
  44410. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  44411. get: function () {
  44412. return this._computeBoundingBox;
  44413. },
  44414. /**
  44415. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  44416. */
  44417. set: function (val) {
  44418. this._computeBoundingBox = val;
  44419. },
  44420. enumerable: true,
  44421. configurable: true
  44422. });
  44423. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  44424. get: function () {
  44425. return this._depthSortParticles;
  44426. },
  44427. /**
  44428. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  44429. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  44430. * Default : `true`
  44431. */
  44432. set: function (val) {
  44433. this._depthSortParticles = val;
  44434. },
  44435. enumerable: true,
  44436. configurable: true
  44437. });
  44438. // =======================================================================
  44439. // Particle behavior logic
  44440. // these following methods may be overwritten by the user to fit his needs
  44441. /**
  44442. * This function does nothing. It may be overwritten to set all the particle first values.
  44443. * The SPS doesn't call this function, you may have to call it by your own.
  44444. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  44445. */
  44446. SolidParticleSystem.prototype.initParticles = function () {
  44447. };
  44448. /**
  44449. * This function does nothing. It may be overwritten to recycle a particle.
  44450. * The SPS doesn't call this function, you may have to call it by your own.
  44451. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  44452. */
  44453. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  44454. return particle;
  44455. };
  44456. /**
  44457. * Updates a particle : this function should be overwritten by the user.
  44458. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  44459. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  44460. * ex : just set a particle position or velocity and recycle conditions
  44461. */
  44462. SolidParticleSystem.prototype.updateParticle = function (particle) {
  44463. return particle;
  44464. };
  44465. /**
  44466. * Updates a vertex of a particle : it can be overwritten by the user.
  44467. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  44468. * @param particle the current particle
  44469. * @param vertex the current index of the current particle
  44470. * @param pt the index of the current vertex in the particle shape
  44471. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  44472. * ex : just set a vertex particle position
  44473. */
  44474. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  44475. return vertex;
  44476. };
  44477. /**
  44478. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  44479. * This does nothing and may be overwritten by the user.
  44480. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  44481. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  44482. * @param update the boolean update value actually passed to setParticles()
  44483. */
  44484. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  44485. };
  44486. /**
  44487. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  44488. * This will be passed three parameters.
  44489. * This does nothing and may be overwritten by the user.
  44490. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  44491. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  44492. * @param update the boolean update value actually passed to setParticles()
  44493. */
  44494. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  44495. };
  44496. return SolidParticleSystem;
  44497. }());
  44498. BABYLON.SolidParticleSystem = SolidParticleSystem;
  44499. })(BABYLON || (BABYLON = {}));
  44500. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  44501. /// <reference path="babylon.mesh.ts" />
  44502. var BABYLON;
  44503. (function (BABYLON) {
  44504. var GroundMesh = (function (_super) {
  44505. __extends(GroundMesh, _super);
  44506. function GroundMesh(name, scene) {
  44507. var _this = _super.call(this, name, scene) || this;
  44508. _this.generateOctree = false;
  44509. return _this;
  44510. }
  44511. GroundMesh.prototype.getClassName = function () {
  44512. return "GroundMesh";
  44513. };
  44514. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  44515. get: function () {
  44516. return Math.min(this._subdivisionsX, this._subdivisionsY);
  44517. },
  44518. enumerable: true,
  44519. configurable: true
  44520. });
  44521. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  44522. get: function () {
  44523. return this._subdivisionsX;
  44524. },
  44525. enumerable: true,
  44526. configurable: true
  44527. });
  44528. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  44529. get: function () {
  44530. return this._subdivisionsY;
  44531. },
  44532. enumerable: true,
  44533. configurable: true
  44534. });
  44535. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  44536. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  44537. this._subdivisionsX = chunksCount;
  44538. this._subdivisionsY = chunksCount;
  44539. this.subdivide(chunksCount);
  44540. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  44541. };
  44542. /**
  44543. * Returns a height (y) value in the Worl system :
  44544. * the ground altitude at the coordinates (x, z) expressed in the World system.
  44545. * Returns the ground y position if (x, z) are outside the ground surface.
  44546. */
  44547. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  44548. var world = this.getWorldMatrix();
  44549. var invMat = BABYLON.Tmp.Matrix[5];
  44550. world.invertToRef(invMat);
  44551. var tmpVect = BABYLON.Tmp.Vector3[8];
  44552. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  44553. x = tmpVect.x;
  44554. z = tmpVect.z;
  44555. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  44556. return this.position.y;
  44557. }
  44558. if (!this._heightQuads || this._heightQuads.length == 0) {
  44559. this._initHeightQuads();
  44560. this._computeHeightQuads();
  44561. }
  44562. var facet = this._getFacetAt(x, z);
  44563. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  44564. // return y in the World system
  44565. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  44566. return tmpVect.y;
  44567. };
  44568. /**
  44569. * Returns a normalized vector (Vector3) orthogonal to the ground
  44570. * at the ground coordinates (x, z) expressed in the World system.
  44571. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  44572. */
  44573. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  44574. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  44575. this.getNormalAtCoordinatesToRef(x, z, normal);
  44576. return normal;
  44577. };
  44578. /**
  44579. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  44580. * at the ground coordinates (x, z) expressed in the World system.
  44581. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  44582. * Returns the GroundMesh.
  44583. */
  44584. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  44585. var world = this.getWorldMatrix();
  44586. var tmpMat = BABYLON.Tmp.Matrix[5];
  44587. world.invertToRef(tmpMat);
  44588. var tmpVect = BABYLON.Tmp.Vector3[8];
  44589. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  44590. x = tmpVect.x;
  44591. z = tmpVect.z;
  44592. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  44593. return this;
  44594. }
  44595. if (!this._heightQuads || this._heightQuads.length == 0) {
  44596. this._initHeightQuads();
  44597. this._computeHeightQuads();
  44598. }
  44599. var facet = this._getFacetAt(x, z);
  44600. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  44601. return this;
  44602. };
  44603. /**
  44604. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  44605. * if the ground has been updated.
  44606. * This can be used in the render loop.
  44607. * Returns the GroundMesh.
  44608. */
  44609. GroundMesh.prototype.updateCoordinateHeights = function () {
  44610. if (!this._heightQuads || this._heightQuads.length == 0) {
  44611. this._initHeightQuads();
  44612. }
  44613. this._computeHeightQuads();
  44614. return this;
  44615. };
  44616. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  44617. GroundMesh.prototype._getFacetAt = function (x, z) {
  44618. // retrieve col and row from x, z coordinates in the ground local system
  44619. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  44620. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  44621. var quad = this._heightQuads[row * this._subdivisionsX + col];
  44622. var facet;
  44623. if (z < quad.slope.x * x + quad.slope.y) {
  44624. facet = quad.facet1;
  44625. }
  44626. else {
  44627. facet = quad.facet2;
  44628. }
  44629. return facet;
  44630. };
  44631. // Creates and populates the heightMap array with "facet" elements :
  44632. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  44633. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  44634. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  44635. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  44636. // Returns the GroundMesh.
  44637. GroundMesh.prototype._initHeightQuads = function () {
  44638. var subdivisionsX = this._subdivisionsX;
  44639. var subdivisionsY = this._subdivisionsY;
  44640. this._heightQuads = new Array();
  44641. for (var row = 0; row < subdivisionsY; row++) {
  44642. for (var col = 0; col < subdivisionsX; col++) {
  44643. 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) };
  44644. this._heightQuads[row * subdivisionsX + col] = quad;
  44645. }
  44646. }
  44647. return this;
  44648. };
  44649. // Compute each quad element values and update the the heightMap array :
  44650. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  44651. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  44652. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  44653. // Returns the GroundMesh.
  44654. GroundMesh.prototype._computeHeightQuads = function () {
  44655. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44656. var v1 = BABYLON.Tmp.Vector3[3];
  44657. var v2 = BABYLON.Tmp.Vector3[2];
  44658. var v3 = BABYLON.Tmp.Vector3[1];
  44659. var v4 = BABYLON.Tmp.Vector3[0];
  44660. var v1v2 = BABYLON.Tmp.Vector3[4];
  44661. var v1v3 = BABYLON.Tmp.Vector3[5];
  44662. var v1v4 = BABYLON.Tmp.Vector3[6];
  44663. var norm1 = BABYLON.Tmp.Vector3[7];
  44664. var norm2 = BABYLON.Tmp.Vector3[8];
  44665. var i = 0;
  44666. var j = 0;
  44667. var k = 0;
  44668. var cd = 0; // 2D slope coefficient : z = cd * x + h
  44669. var h = 0;
  44670. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  44671. var d2 = 0;
  44672. var subdivisionsX = this._subdivisionsX;
  44673. var subdivisionsY = this._subdivisionsY;
  44674. for (var row = 0; row < subdivisionsY; row++) {
  44675. for (var col = 0; col < subdivisionsX; col++) {
  44676. i = col * 3;
  44677. j = row * (subdivisionsX + 1) * 3;
  44678. k = (row + 1) * (subdivisionsX + 1) * 3;
  44679. v1.x = positions[j + i];
  44680. v1.y = positions[j + i + 1];
  44681. v1.z = positions[j + i + 2];
  44682. v2.x = positions[j + i + 3];
  44683. v2.y = positions[j + i + 4];
  44684. v2.z = positions[j + i + 5];
  44685. v3.x = positions[k + i];
  44686. v3.y = positions[k + i + 1];
  44687. v3.z = positions[k + i + 2];
  44688. v4.x = positions[k + i + 3];
  44689. v4.y = positions[k + i + 4];
  44690. v4.z = positions[k + i + 5];
  44691. // 2D slope V1V4
  44692. cd = (v4.z - v1.z) / (v4.x - v1.x);
  44693. h = v1.z - cd * v1.x; // v1 belongs to the slope
  44694. // facet equations :
  44695. // we compute each facet normal vector
  44696. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  44697. // we compute the value d by applying the equation to v1 which belongs to the plane
  44698. // then we store the facet equation in a Vector4
  44699. v2.subtractToRef(v1, v1v2);
  44700. v3.subtractToRef(v1, v1v3);
  44701. v4.subtractToRef(v1, v1v4);
  44702. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  44703. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  44704. norm1.normalize();
  44705. norm2.normalize();
  44706. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  44707. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  44708. var quad = this._heightQuads[row * subdivisionsX + col];
  44709. quad.slope.copyFromFloats(cd, h);
  44710. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  44711. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  44712. }
  44713. }
  44714. return this;
  44715. };
  44716. GroundMesh.prototype.serialize = function (serializationObject) {
  44717. _super.prototype.serialize.call(this, serializationObject);
  44718. serializationObject.subdivisionsX = this._subdivisionsX;
  44719. serializationObject.subdivisionsY = this._subdivisionsY;
  44720. serializationObject.minX = this._minX;
  44721. serializationObject.maxX = this._maxX;
  44722. serializationObject.minZ = this._minZ;
  44723. serializationObject.maxZ = this._maxZ;
  44724. serializationObject.width = this._width;
  44725. serializationObject.height = this._height;
  44726. };
  44727. GroundMesh.Parse = function (parsedMesh, scene) {
  44728. var result = new GroundMesh(parsedMesh.name, scene);
  44729. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  44730. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  44731. result._minX = parsedMesh.minX;
  44732. result._maxX = parsedMesh.maxX;
  44733. result._minZ = parsedMesh.minZ;
  44734. result._maxZ = parsedMesh.maxZ;
  44735. result._width = parsedMesh.width;
  44736. result._height = parsedMesh.height;
  44737. return result;
  44738. };
  44739. return GroundMesh;
  44740. }(BABYLON.Mesh));
  44741. BABYLON.GroundMesh = GroundMesh;
  44742. })(BABYLON || (BABYLON = {}));
  44743. //# sourceMappingURL=babylon.groundMesh.js.map
  44744. var BABYLON;
  44745. (function (BABYLON) {
  44746. /**
  44747. * Creates an instance based on a source mesh.
  44748. */
  44749. var InstancedMesh = (function (_super) {
  44750. __extends(InstancedMesh, _super);
  44751. function InstancedMesh(name, source) {
  44752. var _this = _super.call(this, name, source.getScene()) || this;
  44753. source.instances.push(_this);
  44754. _this._sourceMesh = source;
  44755. _this.position.copyFrom(source.position);
  44756. _this.rotation.copyFrom(source.rotation);
  44757. _this.scaling.copyFrom(source.scaling);
  44758. if (source.rotationQuaternion) {
  44759. _this.rotationQuaternion = source.rotationQuaternion.clone();
  44760. }
  44761. _this.infiniteDistance = source.infiniteDistance;
  44762. _this.setPivotMatrix(source.getPivotMatrix());
  44763. _this.refreshBoundingInfo();
  44764. _this._syncSubMeshes();
  44765. return _this;
  44766. }
  44767. /**
  44768. * Returns the string "InstancedMesh".
  44769. */
  44770. InstancedMesh.prototype.getClassName = function () {
  44771. return "InstancedMesh";
  44772. };
  44773. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  44774. // Methods
  44775. get: function () {
  44776. return this._sourceMesh.receiveShadows;
  44777. },
  44778. enumerable: true,
  44779. configurable: true
  44780. });
  44781. Object.defineProperty(InstancedMesh.prototype, "material", {
  44782. get: function () {
  44783. return this._sourceMesh.material;
  44784. },
  44785. enumerable: true,
  44786. configurable: true
  44787. });
  44788. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  44789. get: function () {
  44790. return this._sourceMesh.visibility;
  44791. },
  44792. enumerable: true,
  44793. configurable: true
  44794. });
  44795. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  44796. get: function () {
  44797. return this._sourceMesh.skeleton;
  44798. },
  44799. enumerable: true,
  44800. configurable: true
  44801. });
  44802. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  44803. get: function () {
  44804. return this._sourceMesh.renderingGroupId;
  44805. },
  44806. enumerable: true,
  44807. configurable: true
  44808. });
  44809. /**
  44810. * Returns the total number of vertices (integer).
  44811. */
  44812. InstancedMesh.prototype.getTotalVertices = function () {
  44813. return this._sourceMesh.getTotalVertices();
  44814. };
  44815. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  44816. get: function () {
  44817. return this._sourceMesh;
  44818. },
  44819. enumerable: true,
  44820. configurable: true
  44821. });
  44822. /**
  44823. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  44824. */
  44825. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  44826. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  44827. };
  44828. /**
  44829. * Sets the vertex data of the mesh geometry for the requested `kind`.
  44830. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  44831. * The `data` are either a numeric array either a Float32Array.
  44832. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  44833. * 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).
  44834. * Note that a new underlying VertexBuffer object is created each call.
  44835. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  44836. *
  44837. * Possible `kind` values :
  44838. * - BABYLON.VertexBuffer.PositionKind
  44839. * - BABYLON.VertexBuffer.UVKind
  44840. * - BABYLON.VertexBuffer.UV2Kind
  44841. * - BABYLON.VertexBuffer.UV3Kind
  44842. * - BABYLON.VertexBuffer.UV4Kind
  44843. * - BABYLON.VertexBuffer.UV5Kind
  44844. * - BABYLON.VertexBuffer.UV6Kind
  44845. * - BABYLON.VertexBuffer.ColorKind
  44846. * - BABYLON.VertexBuffer.MatricesIndicesKind
  44847. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  44848. * - BABYLON.VertexBuffer.MatricesWeightsKind
  44849. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  44850. *
  44851. * Returns the Mesh.
  44852. */
  44853. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  44854. if (this.sourceMesh) {
  44855. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  44856. }
  44857. return this.sourceMesh;
  44858. };
  44859. /**
  44860. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  44861. * If the mesh has no geometry, it is simply returned as it is.
  44862. * The `data` are either a numeric array either a Float32Array.
  44863. * No new underlying VertexBuffer object is created.
  44864. * 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.
  44865. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  44866. *
  44867. * Possible `kind` values :
  44868. * - BABYLON.VertexBuffer.PositionKind
  44869. * - BABYLON.VertexBuffer.UVKind
  44870. * - BABYLON.VertexBuffer.UV2Kind
  44871. * - BABYLON.VertexBuffer.UV3Kind
  44872. * - BABYLON.VertexBuffer.UV4Kind
  44873. * - BABYLON.VertexBuffer.UV5Kind
  44874. * - BABYLON.VertexBuffer.UV6Kind
  44875. * - BABYLON.VertexBuffer.ColorKind
  44876. * - BABYLON.VertexBuffer.MatricesIndicesKind
  44877. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  44878. * - BABYLON.VertexBuffer.MatricesWeightsKind
  44879. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  44880. *
  44881. * Returns the Mesh.
  44882. */
  44883. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  44884. if (this.sourceMesh) {
  44885. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  44886. }
  44887. return this.sourceMesh;
  44888. };
  44889. /**
  44890. * Sets the mesh indices.
  44891. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  44892. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  44893. * This method creates a new index buffer each call.
  44894. * Returns the Mesh.
  44895. */
  44896. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  44897. if (this.sourceMesh) {
  44898. this.sourceMesh.setIndices(indices, totalVertices);
  44899. }
  44900. return this.sourceMesh;
  44901. };
  44902. /**
  44903. * Boolean : True if the mesh owns the requested kind of data.
  44904. */
  44905. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  44906. return this._sourceMesh.isVerticesDataPresent(kind);
  44907. };
  44908. /**
  44909. * Returns an array of indices (IndicesArray).
  44910. */
  44911. InstancedMesh.prototype.getIndices = function () {
  44912. return this._sourceMesh.getIndices();
  44913. };
  44914. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  44915. get: function () {
  44916. return this._sourceMesh._positions;
  44917. },
  44918. enumerable: true,
  44919. configurable: true
  44920. });
  44921. /**
  44922. * Sets a new updated BoundingInfo to the mesh.
  44923. * Returns the mesh.
  44924. */
  44925. InstancedMesh.prototype.refreshBoundingInfo = function () {
  44926. var meshBB = this._sourceMesh.getBoundingInfo();
  44927. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  44928. this._updateBoundingInfo();
  44929. return this;
  44930. };
  44931. InstancedMesh.prototype._preActivate = function () {
  44932. if (this._currentLOD) {
  44933. this._currentLOD._preActivate();
  44934. }
  44935. return this;
  44936. };
  44937. InstancedMesh.prototype._activate = function (renderId) {
  44938. if (this._currentLOD) {
  44939. this._currentLOD._registerInstanceForRenderId(this, renderId);
  44940. }
  44941. return this;
  44942. };
  44943. /**
  44944. * Returns the current associated LOD AbstractMesh.
  44945. */
  44946. InstancedMesh.prototype.getLOD = function (camera) {
  44947. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  44948. if (this._currentLOD === this.sourceMesh) {
  44949. return this;
  44950. }
  44951. return this._currentLOD;
  44952. };
  44953. InstancedMesh.prototype._syncSubMeshes = function () {
  44954. this.releaseSubMeshes();
  44955. if (this._sourceMesh.subMeshes) {
  44956. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  44957. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  44958. }
  44959. }
  44960. return this;
  44961. };
  44962. InstancedMesh.prototype._generatePointsArray = function () {
  44963. return this._sourceMesh._generatePointsArray();
  44964. };
  44965. /**
  44966. * Creates a new InstancedMesh from the current mesh.
  44967. * - name (string) : the cloned mesh name
  44968. * - newParent (optional Node) : the optional Node to parent the clone to.
  44969. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  44970. *
  44971. * Returns the clone.
  44972. */
  44973. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  44974. var result = this._sourceMesh.createInstance(name);
  44975. // Deep copy
  44976. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  44977. // Bounding info
  44978. this.refreshBoundingInfo();
  44979. // Parent
  44980. if (newParent) {
  44981. result.parent = newParent;
  44982. }
  44983. if (!doNotCloneChildren) {
  44984. // Children
  44985. for (var index = 0; index < this.getScene().meshes.length; index++) {
  44986. var mesh = this.getScene().meshes[index];
  44987. if (mesh.parent === this) {
  44988. mesh.clone(mesh.name, result);
  44989. }
  44990. }
  44991. }
  44992. result.computeWorldMatrix(true);
  44993. return result;
  44994. };
  44995. /**
  44996. * Disposes the InstancedMesh.
  44997. * Returns nothing.
  44998. */
  44999. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  45000. // Remove from mesh
  45001. var index = this._sourceMesh.instances.indexOf(this);
  45002. this._sourceMesh.instances.splice(index, 1);
  45003. _super.prototype.dispose.call(this, doNotRecurse);
  45004. };
  45005. return InstancedMesh;
  45006. }(BABYLON.AbstractMesh));
  45007. BABYLON.InstancedMesh = InstancedMesh;
  45008. })(BABYLON || (BABYLON = {}));
  45009. //# sourceMappingURL=babylon.instancedMesh.js.map
  45010. /// <reference path="babylon.mesh.ts" />
  45011. var BABYLON;
  45012. (function (BABYLON) {
  45013. var LinesMesh = (function (_super) {
  45014. __extends(LinesMesh, _super);
  45015. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  45016. if (parent === void 0) { parent = null; }
  45017. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  45018. _this.useVertexColor = useVertexColor;
  45019. _this.color = new BABYLON.Color3(1, 1, 1);
  45020. _this.alpha = 1;
  45021. if (source) {
  45022. _this.color = source.color.clone();
  45023. _this.alpha = source.alpha;
  45024. _this.useVertexColor = source.useVertexColor;
  45025. }
  45026. _this._intersectionThreshold = 0.1;
  45027. var options = {
  45028. attributes: [BABYLON.VertexBuffer.PositionKind],
  45029. uniforms: ["world", "viewProjection"],
  45030. needAlphaBlending: false,
  45031. };
  45032. if (!useVertexColor) {
  45033. options.uniforms.push("color");
  45034. options.needAlphaBlending = true;
  45035. }
  45036. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  45037. return _this;
  45038. }
  45039. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  45040. /**
  45041. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  45042. * This margin is expressed in world space coordinates, so its value may vary.
  45043. * Default value is 0.1
  45044. * @returns the intersection Threshold value.
  45045. */
  45046. get: function () {
  45047. return this._intersectionThreshold;
  45048. },
  45049. /**
  45050. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  45051. * This margin is expressed in world space coordinates, so its value may vary.
  45052. * @param value the new threshold to apply
  45053. */
  45054. set: function (value) {
  45055. if (this._intersectionThreshold === value) {
  45056. return;
  45057. }
  45058. this._intersectionThreshold = value;
  45059. if (this.geometry) {
  45060. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  45061. }
  45062. },
  45063. enumerable: true,
  45064. configurable: true
  45065. });
  45066. /**
  45067. * Returns the string "LineMesh"
  45068. */
  45069. LinesMesh.prototype.getClassName = function () {
  45070. return "LinesMesh";
  45071. };
  45072. Object.defineProperty(LinesMesh.prototype, "material", {
  45073. get: function () {
  45074. return this._colorShader;
  45075. },
  45076. enumerable: true,
  45077. configurable: true
  45078. });
  45079. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  45080. get: function () {
  45081. return false;
  45082. },
  45083. enumerable: true,
  45084. configurable: true
  45085. });
  45086. LinesMesh.prototype.createInstance = function (name) {
  45087. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  45088. return null;
  45089. };
  45090. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  45091. // VBOs
  45092. this._geometry._bind(this._colorShader.getEffect());
  45093. // Color
  45094. if (!this.useVertexColor) {
  45095. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  45096. }
  45097. return this;
  45098. };
  45099. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  45100. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  45101. return this;
  45102. }
  45103. var engine = this.getScene().getEngine();
  45104. // Draw order
  45105. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  45106. return this;
  45107. };
  45108. LinesMesh.prototype.dispose = function (doNotRecurse) {
  45109. this._colorShader.dispose();
  45110. _super.prototype.dispose.call(this, doNotRecurse);
  45111. };
  45112. /**
  45113. * Returns a new LineMesh object cloned from the current one.
  45114. */
  45115. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  45116. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  45117. };
  45118. return LinesMesh;
  45119. }(BABYLON.Mesh));
  45120. BABYLON.LinesMesh = LinesMesh;
  45121. })(BABYLON || (BABYLON = {}));
  45122. //# sourceMappingURL=babylon.linesMesh.js.map
  45123. var BABYLON;
  45124. (function (BABYLON) {
  45125. var ShaderMaterial = (function (_super) {
  45126. __extends(ShaderMaterial, _super);
  45127. function ShaderMaterial(name, scene, shaderPath, options) {
  45128. var _this = _super.call(this, name, scene) || this;
  45129. _this._textures = {};
  45130. _this._textureArrays = {};
  45131. _this._floats = {};
  45132. _this._floatsArrays = {};
  45133. _this._colors3 = {};
  45134. _this._colors3Arrays = {};
  45135. _this._colors4 = {};
  45136. _this._vectors2 = {};
  45137. _this._vectors3 = {};
  45138. _this._vectors4 = {};
  45139. _this._matrices = {};
  45140. _this._matrices3x3 = {};
  45141. _this._matrices2x2 = {};
  45142. _this._vectors3Arrays = {};
  45143. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  45144. _this._shaderPath = shaderPath;
  45145. options.needAlphaBlending = options.needAlphaBlending || false;
  45146. options.needAlphaTesting = options.needAlphaTesting || false;
  45147. options.attributes = options.attributes || ["position", "normal", "uv"];
  45148. options.uniforms = options.uniforms || ["worldViewProjection"];
  45149. options.uniformBuffers = options.uniformBuffers || [];
  45150. options.samplers = options.samplers || [];
  45151. options.defines = options.defines || [];
  45152. _this._options = options;
  45153. return _this;
  45154. }
  45155. ShaderMaterial.prototype.getClassName = function () {
  45156. return "ShaderMaterial";
  45157. };
  45158. ShaderMaterial.prototype.needAlphaBlending = function () {
  45159. return this._options.needAlphaBlending;
  45160. };
  45161. ShaderMaterial.prototype.needAlphaTesting = function () {
  45162. return this._options.needAlphaTesting;
  45163. };
  45164. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  45165. if (this._options.uniforms.indexOf(uniformName) === -1) {
  45166. this._options.uniforms.push(uniformName);
  45167. }
  45168. };
  45169. ShaderMaterial.prototype.setTexture = function (name, texture) {
  45170. if (this._options.samplers.indexOf(name) === -1) {
  45171. this._options.samplers.push(name);
  45172. }
  45173. this._textures[name] = texture;
  45174. return this;
  45175. };
  45176. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  45177. if (this._options.samplers.indexOf(name) === -1) {
  45178. this._options.samplers.push(name);
  45179. }
  45180. this._checkUniform(name);
  45181. this._textureArrays[name] = textures;
  45182. return this;
  45183. };
  45184. ShaderMaterial.prototype.setFloat = function (name, value) {
  45185. this._checkUniform(name);
  45186. this._floats[name] = value;
  45187. return this;
  45188. };
  45189. ShaderMaterial.prototype.setFloats = function (name, value) {
  45190. this._checkUniform(name);
  45191. this._floatsArrays[name] = value;
  45192. return this;
  45193. };
  45194. ShaderMaterial.prototype.setColor3 = function (name, value) {
  45195. this._checkUniform(name);
  45196. this._colors3[name] = value;
  45197. return this;
  45198. };
  45199. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  45200. this._checkUniform(name);
  45201. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  45202. color.toArray(arr, arr.length);
  45203. return arr;
  45204. }, []);
  45205. return this;
  45206. };
  45207. ShaderMaterial.prototype.setColor4 = function (name, value) {
  45208. this._checkUniform(name);
  45209. this._colors4[name] = value;
  45210. return this;
  45211. };
  45212. ShaderMaterial.prototype.setVector2 = function (name, value) {
  45213. this._checkUniform(name);
  45214. this._vectors2[name] = value;
  45215. return this;
  45216. };
  45217. ShaderMaterial.prototype.setVector3 = function (name, value) {
  45218. this._checkUniform(name);
  45219. this._vectors3[name] = value;
  45220. return this;
  45221. };
  45222. ShaderMaterial.prototype.setVector4 = function (name, value) {
  45223. this._checkUniform(name);
  45224. this._vectors4[name] = value;
  45225. return this;
  45226. };
  45227. ShaderMaterial.prototype.setMatrix = function (name, value) {
  45228. this._checkUniform(name);
  45229. this._matrices[name] = value;
  45230. return this;
  45231. };
  45232. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  45233. this._checkUniform(name);
  45234. this._matrices3x3[name] = value;
  45235. return this;
  45236. };
  45237. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  45238. this._checkUniform(name);
  45239. this._matrices2x2[name] = value;
  45240. return this;
  45241. };
  45242. ShaderMaterial.prototype.setArray3 = function (name, value) {
  45243. this._checkUniform(name);
  45244. this._vectors3Arrays[name] = value;
  45245. return this;
  45246. };
  45247. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  45248. if (!mesh) {
  45249. return true;
  45250. }
  45251. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  45252. return false;
  45253. }
  45254. return false;
  45255. };
  45256. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  45257. var scene = this.getScene();
  45258. var engine = scene.getEngine();
  45259. if (!this.checkReadyOnEveryCall) {
  45260. if (this._renderId === scene.getRenderId()) {
  45261. if (this._checkCache(scene, mesh, useInstances)) {
  45262. return true;
  45263. }
  45264. }
  45265. }
  45266. // Instances
  45267. var defines = [];
  45268. var attribs = [];
  45269. var fallbacks = new BABYLON.EffectFallbacks();
  45270. if (useInstances) {
  45271. defines.push("#define INSTANCES");
  45272. }
  45273. for (var index = 0; index < this._options.defines.length; index++) {
  45274. defines.push(this._options.defines[index]);
  45275. }
  45276. for (var index = 0; index < this._options.attributes.length; index++) {
  45277. attribs.push(this._options.attributes[index]);
  45278. }
  45279. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  45280. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45281. defines.push("#define VERTEXCOLOR");
  45282. }
  45283. // Bones
  45284. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  45285. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  45286. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  45287. if (mesh.numBoneInfluencers > 4) {
  45288. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  45289. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  45290. }
  45291. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45292. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45293. fallbacks.addCPUSkinningFallback(0, mesh);
  45294. if (this._options.uniforms.indexOf("mBones") === -1) {
  45295. this._options.uniforms.push("mBones");
  45296. }
  45297. }
  45298. else {
  45299. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45300. }
  45301. // Textures
  45302. for (var name in this._textures) {
  45303. if (!this._textures[name].isReady()) {
  45304. return false;
  45305. }
  45306. }
  45307. // Alpha test
  45308. if (engine.getAlphaTesting()) {
  45309. defines.push("#define ALPHATEST");
  45310. }
  45311. var previousEffect = this._effect;
  45312. var join = defines.join("\n");
  45313. this._effect = engine.createEffect(this._shaderPath, {
  45314. attributes: attribs,
  45315. uniformsNames: this._options.uniforms,
  45316. uniformBuffersNames: this._options.uniformBuffers,
  45317. samplers: this._options.samplers,
  45318. defines: join,
  45319. fallbacks: fallbacks,
  45320. onCompiled: this.onCompiled,
  45321. onError: this.onError
  45322. }, engine);
  45323. if (!this._effect.isReady()) {
  45324. return false;
  45325. }
  45326. if (previousEffect !== this._effect) {
  45327. scene.resetCachedMaterial();
  45328. }
  45329. this._renderId = scene.getRenderId();
  45330. return true;
  45331. };
  45332. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  45333. var scene = this.getScene();
  45334. if (this._options.uniforms.indexOf("world") !== -1) {
  45335. this._effect.setMatrix("world", world);
  45336. }
  45337. if (this._options.uniforms.indexOf("worldView") !== -1) {
  45338. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  45339. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  45340. }
  45341. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  45342. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  45343. }
  45344. };
  45345. ShaderMaterial.prototype.bind = function (world, mesh) {
  45346. // Std values
  45347. this.bindOnlyWorldMatrix(world);
  45348. if (this.getScene().getCachedMaterial() !== this) {
  45349. if (this._options.uniforms.indexOf("view") !== -1) {
  45350. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  45351. }
  45352. if (this._options.uniforms.indexOf("projection") !== -1) {
  45353. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  45354. }
  45355. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  45356. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  45357. }
  45358. // Bones
  45359. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  45360. var name;
  45361. // Texture
  45362. for (name in this._textures) {
  45363. this._effect.setTexture(name, this._textures[name]);
  45364. }
  45365. // Texture arrays
  45366. for (name in this._textureArrays) {
  45367. this._effect.setTextureArray(name, this._textureArrays[name]);
  45368. }
  45369. // Float
  45370. for (name in this._floats) {
  45371. this._effect.setFloat(name, this._floats[name]);
  45372. }
  45373. // Float s
  45374. for (name in this._floatsArrays) {
  45375. this._effect.setArray(name, this._floatsArrays[name]);
  45376. }
  45377. // Color3
  45378. for (name in this._colors3) {
  45379. this._effect.setColor3(name, this._colors3[name]);
  45380. }
  45381. for (name in this._colors3Arrays) {
  45382. this._effect.setArray3(name, this._colors3Arrays[name]);
  45383. }
  45384. // Color4
  45385. for (name in this._colors4) {
  45386. var color = this._colors4[name];
  45387. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  45388. }
  45389. // Vector2
  45390. for (name in this._vectors2) {
  45391. this._effect.setVector2(name, this._vectors2[name]);
  45392. }
  45393. // Vector3
  45394. for (name in this._vectors3) {
  45395. this._effect.setVector3(name, this._vectors3[name]);
  45396. }
  45397. // Vector4
  45398. for (name in this._vectors4) {
  45399. this._effect.setVector4(name, this._vectors4[name]);
  45400. }
  45401. // Matrix
  45402. for (name in this._matrices) {
  45403. this._effect.setMatrix(name, this._matrices[name]);
  45404. }
  45405. // Matrix 3x3
  45406. for (name in this._matrices3x3) {
  45407. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  45408. }
  45409. // Matrix 2x2
  45410. for (name in this._matrices2x2) {
  45411. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  45412. }
  45413. // Vector3Array
  45414. for (name in this._vectors3Arrays) {
  45415. this._effect.setArray3(name, this._vectors3Arrays[name]);
  45416. }
  45417. }
  45418. this._afterBind(mesh);
  45419. };
  45420. ShaderMaterial.prototype.getActiveTextures = function () {
  45421. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45422. for (var name in this._textures) {
  45423. activeTextures.push(this._textures[name]);
  45424. }
  45425. for (var name in this._textureArrays) {
  45426. var array = this._textureArrays[name];
  45427. for (var index = 0; index < array.length; index++) {
  45428. activeTextures.push(array[index]);
  45429. }
  45430. }
  45431. return activeTextures;
  45432. };
  45433. ShaderMaterial.prototype.hasTexture = function (texture) {
  45434. if (_super.prototype.hasTexture.call(this, texture)) {
  45435. return true;
  45436. }
  45437. for (var name in this._textures) {
  45438. if (this._textures[name] === texture) {
  45439. return true;
  45440. }
  45441. }
  45442. for (var name in this._textureArrays) {
  45443. var array = this._textureArrays[name];
  45444. for (var index = 0; index < array.length; index++) {
  45445. if (array[index] === texture) {
  45446. return true;
  45447. }
  45448. }
  45449. }
  45450. return false;
  45451. };
  45452. ShaderMaterial.prototype.clone = function (name) {
  45453. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  45454. return newShaderMaterial;
  45455. };
  45456. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45457. if (forceDisposeTextures) {
  45458. var name;
  45459. for (name in this._textures) {
  45460. this._textures[name].dispose();
  45461. }
  45462. for (name in this._textureArrays) {
  45463. var array = this._textureArrays[name];
  45464. for (var index = 0; index < array.length; index++) {
  45465. array[index].dispose();
  45466. }
  45467. }
  45468. }
  45469. this._textures = {};
  45470. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45471. };
  45472. ShaderMaterial.prototype.serialize = function () {
  45473. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45474. serializationObject.customType = "BABYLON.ShaderMaterial";
  45475. serializationObject.options = this._options;
  45476. serializationObject.shaderPath = this._shaderPath;
  45477. var name;
  45478. // Texture
  45479. serializationObject.textures = {};
  45480. for (name in this._textures) {
  45481. serializationObject.textures[name] = this._textures[name].serialize();
  45482. }
  45483. // Texture arrays
  45484. serializationObject.textureArrays = {};
  45485. for (name in this._textureArrays) {
  45486. serializationObject.textureArrays[name] = [];
  45487. var array = this._textureArrays[name];
  45488. for (var index = 0; index < array.length; index++) {
  45489. serializationObject.textureArrays[name].push(array[index].serialize());
  45490. }
  45491. }
  45492. // Float
  45493. serializationObject.floats = {};
  45494. for (name in this._floats) {
  45495. serializationObject.floats[name] = this._floats[name];
  45496. }
  45497. // Float s
  45498. serializationObject.floatArrays = {};
  45499. for (name in this._floatsArrays) {
  45500. serializationObject.floatArrays[name] = this._floatsArrays[name];
  45501. }
  45502. // Color3
  45503. serializationObject.colors3 = {};
  45504. for (name in this._colors3) {
  45505. serializationObject.colors3[name] = this._colors3[name].asArray();
  45506. }
  45507. // Color3 array
  45508. serializationObject.colors3Arrays = {};
  45509. for (name in this._colors3Arrays) {
  45510. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  45511. }
  45512. // Color4
  45513. serializationObject.colors4 = {};
  45514. for (name in this._colors4) {
  45515. serializationObject.colors4[name] = this._colors4[name].asArray();
  45516. }
  45517. // Vector2
  45518. serializationObject.vectors2 = {};
  45519. for (name in this._vectors2) {
  45520. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  45521. }
  45522. // Vector3
  45523. serializationObject.vectors3 = {};
  45524. for (name in this._vectors3) {
  45525. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  45526. }
  45527. // Vector4
  45528. serializationObject.vectors4 = {};
  45529. for (name in this._vectors4) {
  45530. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  45531. }
  45532. // Matrix
  45533. serializationObject.matrices = {};
  45534. for (name in this._matrices) {
  45535. serializationObject.matrices[name] = this._matrices[name].asArray();
  45536. }
  45537. // Matrix 3x3
  45538. serializationObject.matrices3x3 = {};
  45539. for (name in this._matrices3x3) {
  45540. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  45541. }
  45542. // Matrix 2x2
  45543. serializationObject.matrices2x2 = {};
  45544. for (name in this._matrices2x2) {
  45545. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  45546. }
  45547. // Vector3Array
  45548. serializationObject.vectors3Arrays = {};
  45549. for (name in this._vectors3Arrays) {
  45550. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  45551. }
  45552. return serializationObject;
  45553. };
  45554. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  45555. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  45556. var name;
  45557. // Texture
  45558. for (name in source.textures) {
  45559. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  45560. }
  45561. // Texture arrays
  45562. for (name in source.textureArrays) {
  45563. var array = source.textureArrays[name];
  45564. var textureArray = new Array();
  45565. for (var index = 0; index < array.length; index++) {
  45566. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  45567. }
  45568. material.setTextureArray(name, textureArray);
  45569. }
  45570. // Float
  45571. for (name in source.floats) {
  45572. material.setFloat(name, source.floats[name]);
  45573. }
  45574. // Float s
  45575. for (name in source.floatsArrays) {
  45576. material.setFloats(name, source.floatsArrays[name]);
  45577. }
  45578. // Color3
  45579. for (name in source.colors3) {
  45580. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  45581. }
  45582. // Color3 arrays
  45583. for (name in source.colors3Arrays) {
  45584. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  45585. if (i % 3 === 0) {
  45586. arr.push([num]);
  45587. }
  45588. else {
  45589. arr[arr.length - 1].push(num);
  45590. }
  45591. return arr;
  45592. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  45593. material.setColor3Array(name, colors);
  45594. }
  45595. // Color4
  45596. for (name in source.colors4) {
  45597. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  45598. }
  45599. // Vector2
  45600. for (name in source.vectors2) {
  45601. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  45602. }
  45603. // Vector3
  45604. for (name in source.vectors3) {
  45605. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  45606. }
  45607. // Vector4
  45608. for (name in source.vectors4) {
  45609. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  45610. }
  45611. // Matrix
  45612. for (name in source.matrices) {
  45613. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  45614. }
  45615. // Matrix 3x3
  45616. for (name in source.matrices3x3) {
  45617. material.setMatrix3x3(name, source.matrices3x3[name]);
  45618. }
  45619. // Matrix 2x2
  45620. for (name in source.matrices2x2) {
  45621. material.setMatrix2x2(name, source.matrices2x2[name]);
  45622. }
  45623. // Vector3Array
  45624. for (name in source.vectors3Arrays) {
  45625. material.setArray3(name, source.vectors3Arrays[name]);
  45626. }
  45627. return material;
  45628. };
  45629. return ShaderMaterial;
  45630. }(BABYLON.Material));
  45631. BABYLON.ShaderMaterial = ShaderMaterial;
  45632. })(BABYLON || (BABYLON = {}));
  45633. //# sourceMappingURL=babylon.shaderMaterial.js.map
  45634. var BABYLON;
  45635. (function (BABYLON) {
  45636. var MeshBuilder = (function () {
  45637. function MeshBuilder() {
  45638. }
  45639. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  45640. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  45641. return BABYLON.Mesh.DOUBLESIDE;
  45642. }
  45643. if (orientation === undefined || orientation === null) {
  45644. return BABYLON.Mesh.FRONTSIDE;
  45645. }
  45646. return orientation;
  45647. };
  45648. /**
  45649. * Creates a box mesh.
  45650. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  45651. * The parameter `size` sets the size (float) of each box side (default 1).
  45652. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  45653. * 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).
  45654. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  45655. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45656. * 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).
  45657. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45658. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45659. */
  45660. MeshBuilder.CreateBox = function (name, options, scene) {
  45661. var box = new BABYLON.Mesh(name, scene);
  45662. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45663. box._originalBuilderSideOrientation = options.sideOrientation;
  45664. var vertexData = BABYLON.VertexData.CreateBox(options);
  45665. vertexData.applyToMesh(box, options.updatable);
  45666. return box;
  45667. };
  45668. /**
  45669. * Creates a sphere mesh.
  45670. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  45671. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  45672. * 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`).
  45673. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  45674. * 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
  45675. * 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).
  45676. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45677. * 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).
  45678. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45679. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45680. */
  45681. MeshBuilder.CreateSphere = function (name, options, scene) {
  45682. var sphere = new BABYLON.Mesh(name, scene);
  45683. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45684. sphere._originalBuilderSideOrientation = options.sideOrientation;
  45685. var vertexData = BABYLON.VertexData.CreateSphere(options);
  45686. vertexData.applyToMesh(sphere, options.updatable);
  45687. return sphere;
  45688. };
  45689. /**
  45690. * Creates a plane polygonal mesh. By default, this is a disc.
  45691. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  45692. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  45693. * 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.
  45694. * 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
  45695. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45696. * 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).
  45697. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45698. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45699. */
  45700. MeshBuilder.CreateDisc = function (name, options, scene) {
  45701. var disc = new BABYLON.Mesh(name, scene);
  45702. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45703. disc._originalBuilderSideOrientation = options.sideOrientation;
  45704. var vertexData = BABYLON.VertexData.CreateDisc(options);
  45705. vertexData.applyToMesh(disc, options.updatable);
  45706. return disc;
  45707. };
  45708. /**
  45709. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  45710. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  45711. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  45712. * 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`).
  45713. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  45714. * 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.
  45715. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45716. * 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).
  45717. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45718. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45719. */
  45720. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  45721. var sphere = new BABYLON.Mesh(name, scene);
  45722. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45723. sphere._originalBuilderSideOrientation = options.sideOrientation;
  45724. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  45725. vertexData.applyToMesh(sphere, options.updatable);
  45726. return sphere;
  45727. };
  45728. ;
  45729. /**
  45730. * Creates a ribbon mesh.
  45731. * 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.
  45732. *
  45733. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  45734. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  45735. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  45736. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  45737. * 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.
  45738. * 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.
  45739. * 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
  45740. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45741. * 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).
  45742. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45743. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  45744. * 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.
  45745. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  45746. * 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
  45747. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  45748. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  45749. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45750. */
  45751. MeshBuilder.CreateRibbon = function (name, options, scene) {
  45752. var pathArray = options.pathArray;
  45753. var closeArray = options.closeArray;
  45754. var closePath = options.closePath;
  45755. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45756. var instance = options.instance;
  45757. var updatable = options.updatable;
  45758. if (instance) {
  45759. // positionFunction : ribbon case
  45760. // only pathArray and sideOrientation parameters are taken into account for positions update
  45761. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  45762. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  45763. var positionFunction = function (positions) {
  45764. var minlg = pathArray[0].length;
  45765. var i = 0;
  45766. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  45767. for (var si = 1; si <= ns; si++) {
  45768. for (var p = 0; p < pathArray.length; p++) {
  45769. var path = pathArray[p];
  45770. var l = path.length;
  45771. minlg = (minlg < l) ? minlg : l;
  45772. var j = 0;
  45773. while (j < minlg) {
  45774. positions[i] = path[j].x;
  45775. positions[i + 1] = path[j].y;
  45776. positions[i + 2] = path[j].z;
  45777. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  45778. BABYLON.Tmp.Vector3[0].x = path[j].x;
  45779. }
  45780. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  45781. BABYLON.Tmp.Vector3[1].x = path[j].x;
  45782. }
  45783. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  45784. BABYLON.Tmp.Vector3[0].y = path[j].y;
  45785. }
  45786. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  45787. BABYLON.Tmp.Vector3[1].y = path[j].y;
  45788. }
  45789. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  45790. BABYLON.Tmp.Vector3[0].z = path[j].z;
  45791. }
  45792. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  45793. BABYLON.Tmp.Vector3[1].z = path[j].z;
  45794. }
  45795. j++;
  45796. i += 3;
  45797. }
  45798. if (instance._closePath) {
  45799. positions[i] = path[0].x;
  45800. positions[i + 1] = path[0].y;
  45801. positions[i + 2] = path[0].z;
  45802. i += 3;
  45803. }
  45804. }
  45805. }
  45806. };
  45807. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45808. positionFunction(positions);
  45809. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  45810. instance._boundingInfo.update(instance._worldMatrix);
  45811. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  45812. if (options.colors) {
  45813. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45814. for (var c = 0; c < options.colors.length; c++) {
  45815. colors[c * 4] = options.colors[c].r;
  45816. colors[c * 4 + 1] = options.colors[c].g;
  45817. colors[c * 4 + 2] = options.colors[c].b;
  45818. colors[c * 4 + 3] = options.colors[c].a;
  45819. }
  45820. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  45821. }
  45822. if (options.uvs) {
  45823. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45824. for (var i = 0; i < options.uvs.length; i++) {
  45825. uvs[i * 2] = options.uvs[i].x;
  45826. uvs[i * 2 + 1] = options.uvs[i].y;
  45827. }
  45828. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  45829. }
  45830. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  45831. var indices = instance.getIndices();
  45832. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45833. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  45834. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  45835. if (instance._closePath) {
  45836. var indexFirst = 0;
  45837. var indexLast = 0;
  45838. for (var p = 0; p < pathArray.length; p++) {
  45839. indexFirst = instance._idx[p] * 3;
  45840. if (p + 1 < pathArray.length) {
  45841. indexLast = (instance._idx[p + 1] - 1) * 3;
  45842. }
  45843. else {
  45844. indexLast = normals.length - 3;
  45845. }
  45846. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  45847. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  45848. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  45849. normals[indexLast] = normals[indexFirst];
  45850. normals[indexLast + 1] = normals[indexFirst + 1];
  45851. normals[indexLast + 2] = normals[indexFirst + 2];
  45852. }
  45853. }
  45854. if (!(instance.areNormalsFrozen)) {
  45855. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  45856. }
  45857. }
  45858. return instance;
  45859. }
  45860. else {
  45861. var ribbon = new BABYLON.Mesh(name, scene);
  45862. ribbon._originalBuilderSideOrientation = sideOrientation;
  45863. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  45864. if (closePath) {
  45865. ribbon._idx = vertexData._idx;
  45866. }
  45867. ribbon._closePath = closePath;
  45868. ribbon._closeArray = closeArray;
  45869. vertexData.applyToMesh(ribbon, updatable);
  45870. return ribbon;
  45871. }
  45872. };
  45873. /**
  45874. * Creates a cylinder or a cone mesh.
  45875. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  45876. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  45877. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  45878. * 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.
  45879. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  45880. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  45881. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  45882. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  45883. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  45884. * 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).
  45885. * 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
  45886. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  45887. * 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
  45888. * 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.
  45889. * If `enclose` is false, a ring surface is one element.
  45890. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  45891. * 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
  45892. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45893. * 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).
  45894. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45895. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45896. */
  45897. MeshBuilder.CreateCylinder = function (name, options, scene) {
  45898. var cylinder = new BABYLON.Mesh(name, scene);
  45899. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45900. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  45901. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  45902. vertexData.applyToMesh(cylinder, options.updatable);
  45903. return cylinder;
  45904. };
  45905. /**
  45906. * Creates a torus mesh.
  45907. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  45908. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  45909. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  45910. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  45911. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45912. * 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).
  45913. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45914. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45915. */
  45916. MeshBuilder.CreateTorus = function (name, options, scene) {
  45917. var torus = new BABYLON.Mesh(name, scene);
  45918. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45919. torus._originalBuilderSideOrientation = options.sideOrientation;
  45920. var vertexData = BABYLON.VertexData.CreateTorus(options);
  45921. vertexData.applyToMesh(torus, options.updatable);
  45922. return torus;
  45923. };
  45924. /**
  45925. * Creates a torus knot mesh.
  45926. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  45927. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  45928. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  45929. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  45930. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  45931. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45932. * 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).
  45933. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45934. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45935. */
  45936. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  45937. var torusKnot = new BABYLON.Mesh(name, scene);
  45938. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45939. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  45940. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  45941. vertexData.applyToMesh(torusKnot, options.updatable);
  45942. return torusKnot;
  45943. };
  45944. /**
  45945. * Creates a line system mesh.
  45946. * A line system is a pool of many lines gathered in a single mesh.
  45947. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  45948. * 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.
  45949. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  45950. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  45951. * 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
  45952. * 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
  45953. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  45954. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45955. */
  45956. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  45957. var instance = options.instance;
  45958. var lines = options.lines;
  45959. if (instance) {
  45960. var positionFunction = function (positions) {
  45961. var i = 0;
  45962. for (var l = 0; l < lines.length; l++) {
  45963. var points = lines[l];
  45964. for (var p = 0; p < points.length; p++) {
  45965. positions[i] = points[p].x;
  45966. positions[i + 1] = points[p].y;
  45967. positions[i + 2] = points[p].z;
  45968. i += 3;
  45969. }
  45970. }
  45971. };
  45972. instance.updateMeshPositions(positionFunction, false);
  45973. return instance;
  45974. }
  45975. // line system creation
  45976. var lineSystem = new BABYLON.LinesMesh(name, scene);
  45977. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  45978. vertexData.applyToMesh(lineSystem, options.updatable);
  45979. return lineSystem;
  45980. };
  45981. /**
  45982. * Creates a line mesh.
  45983. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  45984. * 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.
  45985. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  45986. * The parameter `points` is an array successive Vector3.
  45987. * 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
  45988. * When updating an instance, remember that only point positions can change, not the number of points.
  45989. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45990. */
  45991. MeshBuilder.CreateLines = function (name, options, scene) {
  45992. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  45993. return lines;
  45994. };
  45995. /**
  45996. * Creates a dashed line mesh.
  45997. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  45998. * 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.
  45999. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  46000. * The parameter `points` is an array successive Vector3.
  46001. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  46002. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  46003. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  46004. * 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
  46005. * When updating an instance, remember that only point positions can change, not the number of points.
  46006. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46007. */
  46008. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  46009. var points = options.points;
  46010. var instance = options.instance;
  46011. var gapSize = options.gapSize || 1;
  46012. var dashSize = options.dashSize || 3;
  46013. if (instance) {
  46014. var positionFunction = function (positions) {
  46015. var curvect = BABYLON.Vector3.Zero();
  46016. var nbSeg = positions.length / 6;
  46017. var lg = 0;
  46018. var nb = 0;
  46019. var shft = 0;
  46020. var dashshft = 0;
  46021. var curshft = 0;
  46022. var p = 0;
  46023. var i = 0;
  46024. var j = 0;
  46025. for (i = 0; i < points.length - 1; i++) {
  46026. points[i + 1].subtractToRef(points[i], curvect);
  46027. lg += curvect.length();
  46028. }
  46029. shft = lg / nbSeg;
  46030. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  46031. for (i = 0; i < points.length - 1; i++) {
  46032. points[i + 1].subtractToRef(points[i], curvect);
  46033. nb = Math.floor(curvect.length() / shft);
  46034. curvect.normalize();
  46035. j = 0;
  46036. while (j < nb && p < positions.length) {
  46037. curshft = shft * j;
  46038. positions[p] = points[i].x + curshft * curvect.x;
  46039. positions[p + 1] = points[i].y + curshft * curvect.y;
  46040. positions[p + 2] = points[i].z + curshft * curvect.z;
  46041. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  46042. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  46043. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  46044. p += 6;
  46045. j++;
  46046. }
  46047. }
  46048. while (p < positions.length) {
  46049. positions[p] = points[i].x;
  46050. positions[p + 1] = points[i].y;
  46051. positions[p + 2] = points[i].z;
  46052. p += 3;
  46053. }
  46054. };
  46055. instance.updateMeshPositions(positionFunction, false);
  46056. return instance;
  46057. }
  46058. // dashed lines creation
  46059. var dashedLines = new BABYLON.LinesMesh(name, scene);
  46060. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  46061. vertexData.applyToMesh(dashedLines, options.updatable);
  46062. dashedLines.dashSize = dashSize;
  46063. dashedLines.gapSize = gapSize;
  46064. return dashedLines;
  46065. };
  46066. /**
  46067. * Creates an extruded shape mesh.
  46068. * 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.
  46069. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  46070. *
  46071. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  46072. * 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
  46073. * extruded along the Z axis.
  46074. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  46075. * 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.
  46076. * The parameter `scale` (float, default 1) is the value to scale the shape.
  46077. * 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
  46078. * 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
  46079. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  46080. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46081. * 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).
  46082. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46083. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  46084. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46085. */
  46086. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  46087. var path = options.path;
  46088. var shape = options.shape;
  46089. var scale = options.scale || 1;
  46090. var rotation = options.rotation || 0;
  46091. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  46092. var updatable = options.updatable;
  46093. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46094. var instance = options.instance;
  46095. var invertUV = options.invertUV || false;
  46096. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  46097. };
  46098. /**
  46099. * Creates an custom extruded shape mesh.
  46100. * 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.
  46101. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  46102. *
  46103. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  46104. * 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
  46105. * extruded along the Z axis.
  46106. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  46107. * 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
  46108. * and the distance of this point from the begining of the path :
  46109. * ```javascript
  46110. * var rotationFunction = function(i, distance) {
  46111. * // do things
  46112. * return rotationValue; }
  46113. * ```
  46114. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  46115. * 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
  46116. * and the distance of this point from the begining of the path :
  46117. * ```javascript
  46118. * var scaleFunction = function(i, distance) {
  46119. * // do things
  46120. * return scaleValue;}
  46121. * ```
  46122. * It must returns a float value that will be the scale value applied to the shape on each path point.
  46123. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  46124. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  46125. * 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
  46126. * 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
  46127. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  46128. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46129. * 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).
  46130. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46131. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  46132. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46133. */
  46134. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  46135. var path = options.path;
  46136. var shape = options.shape;
  46137. var scaleFunction = options.scaleFunction || (function () { return 1; });
  46138. var rotationFunction = options.rotationFunction || (function () { return 0; });
  46139. var ribbonCloseArray = options.ribbonCloseArray || false;
  46140. var ribbonClosePath = options.ribbonClosePath || false;
  46141. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  46142. var updatable = options.updatable;
  46143. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46144. var instance = options.instance;
  46145. var invertUV = options.invertUV || false;
  46146. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  46147. };
  46148. /**
  46149. * Creates lathe mesh.
  46150. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  46151. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  46152. *
  46153. * 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
  46154. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  46155. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  46156. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  46157. * 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.
  46158. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  46159. * 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
  46160. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46161. * 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).
  46162. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46163. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  46164. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46165. */
  46166. MeshBuilder.CreateLathe = function (name, options, scene) {
  46167. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  46168. var closed = (options.closed === undefined) ? true : options.closed;
  46169. var shape = options.shape;
  46170. var radius = options.radius || 1;
  46171. var tessellation = options.tessellation || 64;
  46172. var updatable = options.updatable;
  46173. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46174. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  46175. var pi2 = Math.PI * 2;
  46176. var paths = new Array();
  46177. var invertUV = options.invertUV || false;
  46178. var i = 0;
  46179. var p = 0;
  46180. var step = pi2 / tessellation * arc;
  46181. var rotated;
  46182. var path = new Array();
  46183. ;
  46184. for (i = 0; i <= tessellation; i++) {
  46185. var path = [];
  46186. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  46187. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  46188. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  46189. }
  46190. for (p = 0; p < shape.length; p++) {
  46191. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  46192. path.push(rotated);
  46193. }
  46194. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  46195. 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));
  46196. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  46197. }
  46198. paths.push(path);
  46199. }
  46200. // lathe ribbon
  46201. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  46202. return lathe;
  46203. };
  46204. /**
  46205. * Creates a plane mesh.
  46206. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  46207. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  46208. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  46209. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  46210. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46211. * 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).
  46212. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46213. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46214. */
  46215. MeshBuilder.CreatePlane = function (name, options, scene) {
  46216. var plane = new BABYLON.Mesh(name, scene);
  46217. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46218. plane._originalBuilderSideOrientation = options.sideOrientation;
  46219. var vertexData = BABYLON.VertexData.CreatePlane(options);
  46220. vertexData.applyToMesh(plane, options.updatable);
  46221. if (options.sourcePlane) {
  46222. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  46223. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  46224. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  46225. plane.rotate(vectorProduct, product);
  46226. }
  46227. return plane;
  46228. };
  46229. /**
  46230. * Creates a ground mesh.
  46231. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  46232. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  46233. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  46234. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46235. */
  46236. MeshBuilder.CreateGround = function (name, options, scene) {
  46237. var ground = new BABYLON.GroundMesh(name, scene);
  46238. ground._setReady(false);
  46239. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  46240. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  46241. ground._width = options.width || 1;
  46242. ground._height = options.height || 1;
  46243. ground._maxX = ground._width / 2;
  46244. ground._maxZ = ground._height / 2;
  46245. ground._minX = -ground._maxX;
  46246. ground._minZ = -ground._maxZ;
  46247. var vertexData = BABYLON.VertexData.CreateGround(options);
  46248. vertexData.applyToMesh(ground, options.updatable);
  46249. ground._setReady(true);
  46250. return ground;
  46251. };
  46252. /**
  46253. * Creates a tiled ground mesh.
  46254. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  46255. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  46256. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  46257. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  46258. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  46259. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  46260. * numbers of subdivisions on the ground width and height of each tile.
  46261. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46262. */
  46263. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  46264. var tiledGround = new BABYLON.Mesh(name, scene);
  46265. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  46266. vertexData.applyToMesh(tiledGround, options.updatable);
  46267. return tiledGround;
  46268. };
  46269. /**
  46270. * Creates a ground mesh from a height map.
  46271. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  46272. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  46273. * The parameter `url` sets the URL of the height map image resource.
  46274. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  46275. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  46276. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  46277. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  46278. * 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.
  46279. * 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).
  46280. * This function is passed the newly built mesh :
  46281. * ```javascript
  46282. * function(mesh) { // do things
  46283. * return; }
  46284. * ```
  46285. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46286. */
  46287. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  46288. var width = options.width || 10.0;
  46289. var height = options.height || 10.0;
  46290. var subdivisions = options.subdivisions || 1 | 0;
  46291. var minHeight = options.minHeight || 0.0;
  46292. var maxHeight = options.maxHeight || 1.0;
  46293. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  46294. var updatable = options.updatable;
  46295. var onReady = options.onReady;
  46296. var ground = new BABYLON.GroundMesh(name, scene);
  46297. ground._subdivisionsX = subdivisions;
  46298. ground._subdivisionsY = subdivisions;
  46299. ground._width = width;
  46300. ground._height = height;
  46301. ground._maxX = ground._width / 2.0;
  46302. ground._maxZ = ground._height / 2.0;
  46303. ground._minX = -ground._maxX;
  46304. ground._minZ = -ground._maxZ;
  46305. ground._setReady(false);
  46306. var onload = function (img) {
  46307. // Getting height map data
  46308. var canvas = document.createElement("canvas");
  46309. var context = canvas.getContext("2d");
  46310. var bufferWidth = img.width;
  46311. var bufferHeight = img.height;
  46312. canvas.width = bufferWidth;
  46313. canvas.height = bufferHeight;
  46314. context.drawImage(img, 0, 0);
  46315. // Create VertexData from map data
  46316. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  46317. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  46318. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  46319. width: width, height: height,
  46320. subdivisions: subdivisions,
  46321. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  46322. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  46323. });
  46324. vertexData.applyToMesh(ground, updatable);
  46325. ground._setReady(true);
  46326. //execute ready callback, if set
  46327. if (onReady) {
  46328. onReady(ground);
  46329. }
  46330. };
  46331. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  46332. return ground;
  46333. };
  46334. /**
  46335. * Creates a polygon mesh.
  46336. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  46337. * 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.
  46338. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46339. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46340. * 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).
  46341. * Remember you can only change the shape positions, not their number when updating a polygon.
  46342. */
  46343. MeshBuilder.CreatePolygon = function (name, options, scene) {
  46344. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46345. var shape = options.shape;
  46346. var holes = options.holes || [];
  46347. var depth = options.depth || 0;
  46348. var contours = [];
  46349. var hole = [];
  46350. for (var i = 0; i < shape.length; i++) {
  46351. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  46352. }
  46353. var epsilon = 0.00000001;
  46354. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  46355. contours.pop();
  46356. }
  46357. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  46358. for (var hNb = 0; hNb < holes.length; hNb++) {
  46359. hole = [];
  46360. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  46361. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  46362. }
  46363. polygonTriangulation.addHole(hole);
  46364. }
  46365. var polygon = polygonTriangulation.build(options.updatable, depth);
  46366. polygon._originalBuilderSideOrientation = options.sideOrientation;
  46367. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  46368. vertexData.applyToMesh(polygon, options.updatable);
  46369. return polygon;
  46370. };
  46371. ;
  46372. /**
  46373. * Creates an extruded polygon mesh, with depth in the Y direction.
  46374. * 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).
  46375. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  46376. */
  46377. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  46378. return MeshBuilder.CreatePolygon(name, options, scene);
  46379. };
  46380. ;
  46381. /**
  46382. * Creates a tube mesh.
  46383. * 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.
  46384. *
  46385. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  46386. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  46387. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  46388. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  46389. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  46390. * 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.
  46391. * It must return a radius value (positive float) :
  46392. * ```javascript
  46393. * var radiusFunction = function(i, distance) {
  46394. * // do things
  46395. * return radius; }
  46396. * ```
  46397. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  46398. * 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
  46399. * 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
  46400. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46401. * 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).
  46402. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46403. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  46404. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46405. */
  46406. MeshBuilder.CreateTube = function (name, options, scene) {
  46407. var path = options.path;
  46408. var instance = options.instance;
  46409. var radius = 1.0;
  46410. if (instance) {
  46411. radius = instance.radius;
  46412. }
  46413. if (options.radius !== undefined) {
  46414. radius = options.radius;
  46415. }
  46416. ;
  46417. var tessellation = options.tessellation || 64 | 0;
  46418. var radiusFunction = options.radiusFunction;
  46419. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  46420. var invertUV = options.invertUV || false;
  46421. var updatable = options.updatable;
  46422. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46423. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  46424. // tube geometry
  46425. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  46426. var tangents = path3D.getTangents();
  46427. var normals = path3D.getNormals();
  46428. var distances = path3D.getDistances();
  46429. var pi2 = Math.PI * 2;
  46430. var step = pi2 / tessellation * arc;
  46431. var returnRadius = function () { return radius; };
  46432. var radiusFunctionFinal = radiusFunction || returnRadius;
  46433. var circlePath;
  46434. var rad;
  46435. var normal;
  46436. var rotated;
  46437. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  46438. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  46439. for (var i = 0; i < path.length; i++) {
  46440. rad = radiusFunctionFinal(i, distances[i]); // current radius
  46441. circlePath = Array(); // current circle array
  46442. normal = normals[i]; // current normal
  46443. for (var t = 0; t < tessellation; t++) {
  46444. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  46445. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  46446. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  46447. rotated.scaleInPlace(rad).addInPlace(path[i]);
  46448. circlePath[t] = rotated;
  46449. }
  46450. circlePaths[index] = circlePath;
  46451. index++;
  46452. }
  46453. // cap
  46454. var capPath = function (nbPoints, pathIndex) {
  46455. var pointCap = Array();
  46456. for (var i = 0; i < nbPoints; i++) {
  46457. pointCap.push(path[pathIndex]);
  46458. }
  46459. return pointCap;
  46460. };
  46461. switch (cap) {
  46462. case BABYLON.Mesh.NO_CAP:
  46463. break;
  46464. case BABYLON.Mesh.CAP_START:
  46465. circlePaths[0] = capPath(tessellation, 0);
  46466. circlePaths[1] = circlePaths[2].slice(0);
  46467. break;
  46468. case BABYLON.Mesh.CAP_END:
  46469. circlePaths[index] = circlePaths[index - 1].slice(0);
  46470. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  46471. break;
  46472. case BABYLON.Mesh.CAP_ALL:
  46473. circlePaths[0] = capPath(tessellation, 0);
  46474. circlePaths[1] = circlePaths[2].slice(0);
  46475. circlePaths[index] = circlePaths[index - 1].slice(0);
  46476. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  46477. break;
  46478. default:
  46479. break;
  46480. }
  46481. return circlePaths;
  46482. };
  46483. var path3D;
  46484. var pathArray;
  46485. if (instance) {
  46486. var arc = options.arc || instance.arc;
  46487. path3D = (instance.path3D).update(path);
  46488. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  46489. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  46490. instance.path3D = path3D;
  46491. instance.pathArray = pathArray;
  46492. instance.arc = arc;
  46493. instance.radius = radius;
  46494. return instance;
  46495. }
  46496. // tube creation
  46497. path3D = new BABYLON.Path3D(path);
  46498. var newPathArray = new Array();
  46499. cap = (cap < 0 || cap > 3) ? 0 : cap;
  46500. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  46501. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  46502. tube.pathArray = pathArray;
  46503. tube.path3D = path3D;
  46504. tube.tessellation = tessellation;
  46505. tube.cap = cap;
  46506. tube.arc = options.arc;
  46507. tube.radius = radius;
  46508. return tube;
  46509. };
  46510. /**
  46511. * Creates a polyhedron mesh.
  46512. *
  46513. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  46514. * 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
  46515. * to choose the wanted type.
  46516. * The parameter `size` (positive float, default 1) sets the polygon size.
  46517. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  46518. * 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`.
  46519. * 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
  46520. * 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)`).
  46521. * 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
  46522. * 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.
  46523. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46524. * 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).
  46525. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46526. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46527. */
  46528. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  46529. var polyhedron = new BABYLON.Mesh(name, scene);
  46530. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46531. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  46532. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  46533. vertexData.applyToMesh(polyhedron, options.updatable);
  46534. return polyhedron;
  46535. };
  46536. /**
  46537. * Creates a decal mesh.
  46538. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  46539. * 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.
  46540. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  46541. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  46542. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  46543. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  46544. */
  46545. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  46546. var indices = sourceMesh.getIndices();
  46547. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46548. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46549. var position = options.position || BABYLON.Vector3.Zero();
  46550. var normal = options.normal || BABYLON.Vector3.Up();
  46551. var size = options.size || BABYLON.Vector3.One();
  46552. var angle = options.angle || 0;
  46553. // Getting correct rotation
  46554. if (!normal) {
  46555. var target = new BABYLON.Vector3(0, 0, 1);
  46556. var camera = sourceMesh.getScene().activeCamera;
  46557. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  46558. normal = camera.globalPosition.subtract(cameraWorldTarget);
  46559. }
  46560. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  46561. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  46562. var pitch = Math.atan2(normal.y, len);
  46563. // Matrix
  46564. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  46565. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  46566. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  46567. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  46568. var vertexData = new BABYLON.VertexData();
  46569. vertexData.indices = [];
  46570. vertexData.positions = [];
  46571. vertexData.normals = [];
  46572. vertexData.uvs = [];
  46573. var currentVertexDataIndex = 0;
  46574. var extractDecalVector3 = function (indexId) {
  46575. var vertexId = indices[indexId];
  46576. var result = new BABYLON.PositionNormalVertex();
  46577. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  46578. // Send vector to decal local world
  46579. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  46580. // Get normal
  46581. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  46582. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  46583. return result;
  46584. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  46585. var clip = function (vertices, axis) {
  46586. if (vertices.length === 0) {
  46587. return vertices;
  46588. }
  46589. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  46590. var clipVertices = function (v0, v1) {
  46591. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  46592. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  46593. };
  46594. var result = new Array();
  46595. for (var index = 0; index < vertices.length; index += 3) {
  46596. var v1Out;
  46597. var v2Out;
  46598. var v3Out;
  46599. var total = 0;
  46600. var nV1, nV2, nV3, nV4;
  46601. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  46602. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  46603. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  46604. v1Out = d1 > 0;
  46605. v2Out = d2 > 0;
  46606. v3Out = d3 > 0;
  46607. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  46608. switch (total) {
  46609. case 0:
  46610. result.push(vertices[index]);
  46611. result.push(vertices[index + 1]);
  46612. result.push(vertices[index + 2]);
  46613. break;
  46614. case 1:
  46615. if (v1Out) {
  46616. nV1 = vertices[index + 1];
  46617. nV2 = vertices[index + 2];
  46618. nV3 = clipVertices(vertices[index], nV1);
  46619. nV4 = clipVertices(vertices[index], nV2);
  46620. }
  46621. if (v2Out) {
  46622. nV1 = vertices[index];
  46623. nV2 = vertices[index + 2];
  46624. nV3 = clipVertices(vertices[index + 1], nV1);
  46625. nV4 = clipVertices(vertices[index + 1], nV2);
  46626. result.push(nV3);
  46627. result.push(nV2.clone());
  46628. result.push(nV1.clone());
  46629. result.push(nV2.clone());
  46630. result.push(nV3.clone());
  46631. result.push(nV4);
  46632. break;
  46633. }
  46634. if (v3Out) {
  46635. nV1 = vertices[index];
  46636. nV2 = vertices[index + 1];
  46637. nV3 = clipVertices(vertices[index + 2], nV1);
  46638. nV4 = clipVertices(vertices[index + 2], nV2);
  46639. }
  46640. result.push(nV1.clone());
  46641. result.push(nV2.clone());
  46642. result.push(nV3);
  46643. result.push(nV4);
  46644. result.push(nV3.clone());
  46645. result.push(nV2.clone());
  46646. break;
  46647. case 2:
  46648. if (!v1Out) {
  46649. nV1 = vertices[index].clone();
  46650. nV2 = clipVertices(nV1, vertices[index + 1]);
  46651. nV3 = clipVertices(nV1, vertices[index + 2]);
  46652. result.push(nV1);
  46653. result.push(nV2);
  46654. result.push(nV3);
  46655. }
  46656. if (!v2Out) {
  46657. nV1 = vertices[index + 1].clone();
  46658. nV2 = clipVertices(nV1, vertices[index + 2]);
  46659. nV3 = clipVertices(nV1, vertices[index]);
  46660. result.push(nV1);
  46661. result.push(nV2);
  46662. result.push(nV3);
  46663. }
  46664. if (!v3Out) {
  46665. nV1 = vertices[index + 2].clone();
  46666. nV2 = clipVertices(nV1, vertices[index]);
  46667. nV3 = clipVertices(nV1, vertices[index + 1]);
  46668. result.push(nV1);
  46669. result.push(nV2);
  46670. result.push(nV3);
  46671. }
  46672. break;
  46673. case 3:
  46674. break;
  46675. }
  46676. }
  46677. return result;
  46678. };
  46679. for (var index = 0; index < indices.length; index += 3) {
  46680. var faceVertices = new Array();
  46681. faceVertices.push(extractDecalVector3(index));
  46682. faceVertices.push(extractDecalVector3(index + 1));
  46683. faceVertices.push(extractDecalVector3(index + 2));
  46684. // Clip
  46685. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  46686. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  46687. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  46688. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  46689. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  46690. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  46691. if (faceVertices.length === 0) {
  46692. continue;
  46693. }
  46694. // Add UVs and get back to world
  46695. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  46696. var vertex = faceVertices[vIndex];
  46697. //TODO check for Int32Array | Uint32Array | Uint16Array
  46698. vertexData.indices.push(currentVertexDataIndex);
  46699. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  46700. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  46701. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  46702. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  46703. currentVertexDataIndex++;
  46704. }
  46705. }
  46706. // Return mesh
  46707. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  46708. vertexData.applyToMesh(decal);
  46709. decal.position = position.clone();
  46710. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  46711. return decal;
  46712. };
  46713. // Privates
  46714. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  46715. // extrusion geometry
  46716. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  46717. var tangents = path3D.getTangents();
  46718. var normals = path3D.getNormals();
  46719. var binormals = path3D.getBinormals();
  46720. var distances = path3D.getDistances();
  46721. var angle = 0;
  46722. var returnScale = function () { return scale; };
  46723. var returnRotation = function () { return rotation; };
  46724. var rotate = custom ? rotateFunction : returnRotation;
  46725. var scl = custom ? scaleFunction : returnScale;
  46726. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  46727. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  46728. for (var i = 0; i < curve.length; i++) {
  46729. var shapePath = new Array();
  46730. var angleStep = rotate(i, distances[i]);
  46731. var scaleRatio = scl(i, distances[i]);
  46732. for (var p = 0; p < shape.length; p++) {
  46733. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  46734. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  46735. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  46736. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  46737. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  46738. shapePath[p] = rotated;
  46739. }
  46740. shapePaths[index] = shapePath;
  46741. angle += angleStep;
  46742. index++;
  46743. }
  46744. // cap
  46745. var capPath = function (shapePath) {
  46746. var pointCap = Array();
  46747. var barycenter = BABYLON.Vector3.Zero();
  46748. var i;
  46749. for (i = 0; i < shapePath.length; i++) {
  46750. barycenter.addInPlace(shapePath[i]);
  46751. }
  46752. barycenter.scaleInPlace(1.0 / shapePath.length);
  46753. for (i = 0; i < shapePath.length; i++) {
  46754. pointCap.push(barycenter);
  46755. }
  46756. return pointCap;
  46757. };
  46758. switch (cap) {
  46759. case BABYLON.Mesh.NO_CAP:
  46760. break;
  46761. case BABYLON.Mesh.CAP_START:
  46762. shapePaths[0] = capPath(shapePaths[2]);
  46763. shapePaths[1] = shapePaths[2];
  46764. break;
  46765. case BABYLON.Mesh.CAP_END:
  46766. shapePaths[index] = shapePaths[index - 1];
  46767. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  46768. break;
  46769. case BABYLON.Mesh.CAP_ALL:
  46770. shapePaths[0] = capPath(shapePaths[2]);
  46771. shapePaths[1] = shapePaths[2];
  46772. shapePaths[index] = shapePaths[index - 1];
  46773. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  46774. break;
  46775. default:
  46776. break;
  46777. }
  46778. return shapePaths;
  46779. };
  46780. var path3D;
  46781. var pathArray;
  46782. if (instance) {
  46783. path3D = (instance.path3D).update(curve);
  46784. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  46785. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  46786. return instance;
  46787. }
  46788. // extruded shape creation
  46789. path3D = new BABYLON.Path3D(curve);
  46790. var newShapePaths = new Array();
  46791. cap = (cap < 0 || cap > 3) ? 0 : cap;
  46792. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  46793. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  46794. extrudedGeneric.pathArray = pathArray;
  46795. extrudedGeneric.path3D = path3D;
  46796. extrudedGeneric.cap = cap;
  46797. return extrudedGeneric;
  46798. };
  46799. return MeshBuilder;
  46800. }());
  46801. BABYLON.MeshBuilder = MeshBuilder;
  46802. })(BABYLON || (BABYLON = {}));
  46803. //# sourceMappingURL=babylon.meshBuilder.js.map
  46804. var BABYLON;
  46805. (function (BABYLON) {
  46806. var AudioEngine = (function () {
  46807. function AudioEngine() {
  46808. this._audioContext = null;
  46809. this._audioContextInitialized = false;
  46810. this.canUseWebAudio = false;
  46811. this.WarnedWebAudioUnsupported = false;
  46812. this.unlocked = false;
  46813. this.isMP3supported = false;
  46814. this.isOGGsupported = false;
  46815. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  46816. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  46817. this.canUseWebAudio = true;
  46818. }
  46819. var audioElem = document.createElement('audio');
  46820. try {
  46821. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  46822. this.isMP3supported = true;
  46823. }
  46824. }
  46825. catch (e) {
  46826. // protect error during capability check.
  46827. }
  46828. try {
  46829. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  46830. this.isOGGsupported = true;
  46831. }
  46832. }
  46833. catch (e) {
  46834. // protect error during capability check.
  46835. }
  46836. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  46837. this._unlockiOSaudio();
  46838. }
  46839. else {
  46840. this.unlocked = true;
  46841. }
  46842. }
  46843. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  46844. get: function () {
  46845. if (!this._audioContextInitialized) {
  46846. this._initializeAudioContext();
  46847. }
  46848. return this._audioContext;
  46849. },
  46850. enumerable: true,
  46851. configurable: true
  46852. });
  46853. AudioEngine.prototype._unlockiOSaudio = function () {
  46854. var _this = this;
  46855. var unlockaudio = function () {
  46856. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  46857. var source = _this.audioContext.createBufferSource();
  46858. source.buffer = buffer;
  46859. source.connect(_this.audioContext.destination);
  46860. source.start(0);
  46861. setTimeout(function () {
  46862. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  46863. _this.unlocked = true;
  46864. window.removeEventListener('touchend', unlockaudio, false);
  46865. if (_this.onAudioUnlocked) {
  46866. _this.onAudioUnlocked();
  46867. }
  46868. }
  46869. }, 0);
  46870. };
  46871. window.addEventListener('touchend', unlockaudio, false);
  46872. };
  46873. AudioEngine.prototype._initializeAudioContext = function () {
  46874. try {
  46875. if (this.canUseWebAudio) {
  46876. this._audioContext = new AudioContext();
  46877. // create a global volume gain node
  46878. this.masterGain = this._audioContext.createGain();
  46879. this.masterGain.gain.value = 1;
  46880. this.masterGain.connect(this._audioContext.destination);
  46881. this._audioContextInitialized = true;
  46882. }
  46883. }
  46884. catch (e) {
  46885. this.canUseWebAudio = false;
  46886. BABYLON.Tools.Error("Web Audio: " + e.message);
  46887. }
  46888. };
  46889. AudioEngine.prototype.dispose = function () {
  46890. if (this.canUseWebAudio && this._audioContextInitialized) {
  46891. if (this._connectedAnalyser) {
  46892. this._connectedAnalyser.stopDebugCanvas();
  46893. this._connectedAnalyser.dispose();
  46894. this.masterGain.disconnect();
  46895. this.masterGain.connect(this._audioContext.destination);
  46896. this._connectedAnalyser = null;
  46897. }
  46898. this.masterGain.gain.value = 1;
  46899. }
  46900. this.WarnedWebAudioUnsupported = false;
  46901. };
  46902. AudioEngine.prototype.getGlobalVolume = function () {
  46903. if (this.canUseWebAudio && this._audioContextInitialized) {
  46904. return this.masterGain.gain.value;
  46905. }
  46906. else {
  46907. return -1;
  46908. }
  46909. };
  46910. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  46911. if (this.canUseWebAudio && this._audioContextInitialized) {
  46912. this.masterGain.gain.value = newVolume;
  46913. }
  46914. };
  46915. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  46916. if (this._connectedAnalyser) {
  46917. this._connectedAnalyser.stopDebugCanvas();
  46918. }
  46919. if (this.canUseWebAudio && this._audioContextInitialized) {
  46920. this._connectedAnalyser = analyser;
  46921. this.masterGain.disconnect();
  46922. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  46923. }
  46924. };
  46925. return AudioEngine;
  46926. }());
  46927. BABYLON.AudioEngine = AudioEngine;
  46928. })(BABYLON || (BABYLON = {}));
  46929. //# sourceMappingURL=babylon.audioEngine.js.map
  46930. var BABYLON;
  46931. (function (BABYLON) {
  46932. var Sound = (function () {
  46933. /**
  46934. * Create a sound and attach it to a scene
  46935. * @param name Name of your sound
  46936. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  46937. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  46938. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  46939. */
  46940. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  46941. var _this = this;
  46942. this.autoplay = false;
  46943. this.loop = false;
  46944. this.useCustomAttenuation = false;
  46945. this.spatialSound = false;
  46946. this.refDistance = 1;
  46947. this.rolloffFactor = 1;
  46948. this.maxDistance = 100;
  46949. this.distanceModel = "linear";
  46950. this._panningModel = "equalpower";
  46951. this._playbackRate = 1;
  46952. this._streaming = false;
  46953. this._startTime = 0;
  46954. this._startOffset = 0;
  46955. this._position = BABYLON.Vector3.Zero();
  46956. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  46957. this._volume = 1;
  46958. this._isLoaded = false;
  46959. this._isReadyToPlay = false;
  46960. this.isPlaying = false;
  46961. this.isPaused = false;
  46962. this._isDirectional = false;
  46963. // Used if you'd like to create a directional sound.
  46964. // If not set, the sound will be omnidirectional
  46965. this._coneInnerAngle = 360;
  46966. this._coneOuterAngle = 360;
  46967. this._coneOuterGain = 0;
  46968. this._isOutputConnected = false;
  46969. this._urlType = "Unknown";
  46970. this.name = name;
  46971. this._scene = scene;
  46972. this._readyToPlayCallback = readyToPlayCallback;
  46973. // Default custom attenuation function is a linear attenuation
  46974. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  46975. if (currentDistance < maxDistance) {
  46976. return currentVolume * (1 - currentDistance / maxDistance);
  46977. }
  46978. else {
  46979. return 0;
  46980. }
  46981. };
  46982. if (options) {
  46983. this.autoplay = options.autoplay || false;
  46984. this.loop = options.loop || false;
  46985. // if volume === 0, we need another way to check this option
  46986. if (options.volume !== undefined) {
  46987. this._volume = options.volume;
  46988. }
  46989. this.spatialSound = options.spatialSound || false;
  46990. this.maxDistance = options.maxDistance || 100;
  46991. this.useCustomAttenuation = options.useCustomAttenuation || false;
  46992. this.rolloffFactor = options.rolloffFactor || 1;
  46993. this.refDistance = options.refDistance || 1;
  46994. this.distanceModel = options.distanceModel || "linear";
  46995. this._playbackRate = options.playbackRate || 1;
  46996. this._streaming = options.streaming || false;
  46997. }
  46998. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  46999. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  47000. this._soundGain.gain.value = this._volume;
  47001. this._inputAudioNode = this._soundGain;
  47002. this._ouputAudioNode = this._soundGain;
  47003. if (this.spatialSound) {
  47004. this._createSpatialParameters();
  47005. }
  47006. this._scene.mainSoundTrack.AddSound(this);
  47007. var validParameter = true;
  47008. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  47009. if (urlOrArrayBuffer) {
  47010. if (typeof (urlOrArrayBuffer) === "string")
  47011. this._urlType = "String";
  47012. if (Array.isArray(urlOrArrayBuffer))
  47013. this._urlType = "Array";
  47014. if (urlOrArrayBuffer instanceof ArrayBuffer)
  47015. this._urlType = "ArrayBuffer";
  47016. var urls = [];
  47017. var codecSupportedFound = false;
  47018. switch (this._urlType) {
  47019. case "ArrayBuffer":
  47020. if (urlOrArrayBuffer.byteLength > 0) {
  47021. codecSupportedFound = true;
  47022. this._soundLoaded(urlOrArrayBuffer);
  47023. }
  47024. break;
  47025. case "String":
  47026. urls.push(urlOrArrayBuffer);
  47027. case "Array":
  47028. if (urls.length === 0)
  47029. urls = urlOrArrayBuffer;
  47030. // If we found a supported format, we load it immediately and stop the loop
  47031. for (var i = 0; i < urls.length; i++) {
  47032. var url = urls[i];
  47033. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  47034. codecSupportedFound = true;
  47035. }
  47036. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  47037. codecSupportedFound = true;
  47038. }
  47039. if (url.indexOf(".wav", url.length - 4) !== -1) {
  47040. codecSupportedFound = true;
  47041. }
  47042. if (url.indexOf("blob:") !== -1) {
  47043. codecSupportedFound = true;
  47044. }
  47045. if (codecSupportedFound) {
  47046. // Loading sound using XHR2
  47047. if (!this._streaming) {
  47048. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  47049. }
  47050. else {
  47051. this._htmlAudioElement = new Audio(url);
  47052. this._htmlAudioElement.controls = false;
  47053. this._htmlAudioElement.loop = this.loop;
  47054. this._htmlAudioElement.crossOrigin = "anonymous";
  47055. this._htmlAudioElement.preload = "auto";
  47056. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  47057. _this._isReadyToPlay = true;
  47058. if (_this.autoplay) {
  47059. _this.play();
  47060. }
  47061. if (_this._readyToPlayCallback) {
  47062. _this._readyToPlayCallback();
  47063. }
  47064. });
  47065. document.body.appendChild(this._htmlAudioElement);
  47066. }
  47067. break;
  47068. }
  47069. }
  47070. break;
  47071. default:
  47072. validParameter = false;
  47073. break;
  47074. }
  47075. if (!validParameter) {
  47076. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  47077. }
  47078. else {
  47079. if (!codecSupportedFound) {
  47080. this._isReadyToPlay = true;
  47081. // Simulating a ready to play event to avoid breaking code path
  47082. if (this._readyToPlayCallback) {
  47083. window.setTimeout(function () {
  47084. _this._readyToPlayCallback();
  47085. }, 1000);
  47086. }
  47087. }
  47088. }
  47089. }
  47090. }
  47091. else {
  47092. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  47093. this._scene.mainSoundTrack.AddSound(this);
  47094. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  47095. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  47096. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  47097. }
  47098. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  47099. if (this._readyToPlayCallback) {
  47100. window.setTimeout(function () {
  47101. _this._readyToPlayCallback();
  47102. }, 1000);
  47103. }
  47104. }
  47105. }
  47106. Sound.prototype.dispose = function () {
  47107. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  47108. if (this.isPlaying) {
  47109. this.stop();
  47110. }
  47111. this._isReadyToPlay = false;
  47112. if (this.soundTrackId === -1) {
  47113. this._scene.mainSoundTrack.RemoveSound(this);
  47114. }
  47115. else {
  47116. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  47117. }
  47118. if (this._soundGain) {
  47119. this._soundGain.disconnect();
  47120. this._soundGain = null;
  47121. }
  47122. if (this._soundPanner) {
  47123. this._soundPanner.disconnect();
  47124. this._soundPanner = null;
  47125. }
  47126. if (this._soundSource) {
  47127. this._soundSource.disconnect();
  47128. this._soundSource = null;
  47129. }
  47130. this._audioBuffer = null;
  47131. if (this._htmlAudioElement) {
  47132. this._htmlAudioElement.pause();
  47133. this._htmlAudioElement.src = "";
  47134. document.body.removeChild(this._htmlAudioElement);
  47135. }
  47136. if (this._connectedMesh) {
  47137. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  47138. this._connectedMesh = null;
  47139. }
  47140. }
  47141. };
  47142. Sound.prototype.isReady = function () {
  47143. return this._isReadyToPlay;
  47144. };
  47145. Sound.prototype._soundLoaded = function (audioData) {
  47146. var _this = this;
  47147. this._isLoaded = true;
  47148. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  47149. _this._audioBuffer = buffer;
  47150. _this._isReadyToPlay = true;
  47151. if (_this.autoplay) {
  47152. _this.play();
  47153. }
  47154. if (_this._readyToPlayCallback) {
  47155. _this._readyToPlayCallback();
  47156. }
  47157. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  47158. };
  47159. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  47160. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47161. this._audioBuffer = audioBuffer;
  47162. this._isReadyToPlay = true;
  47163. }
  47164. };
  47165. Sound.prototype.updateOptions = function (options) {
  47166. if (options) {
  47167. this.loop = options.loop || this.loop;
  47168. this.maxDistance = options.maxDistance || this.maxDistance;
  47169. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  47170. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  47171. this.refDistance = options.refDistance || this.refDistance;
  47172. this.distanceModel = options.distanceModel || this.distanceModel;
  47173. this._playbackRate = options.playbackRate || this._playbackRate;
  47174. this._updateSpatialParameters();
  47175. if (this.isPlaying) {
  47176. if (this._streaming) {
  47177. this._htmlAudioElement.playbackRate = this._playbackRate;
  47178. }
  47179. else {
  47180. this._soundSource.playbackRate.value = this._playbackRate;
  47181. }
  47182. }
  47183. }
  47184. };
  47185. Sound.prototype._createSpatialParameters = function () {
  47186. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47187. if (this._scene.headphone) {
  47188. this._panningModel = "HRTF";
  47189. }
  47190. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  47191. this._updateSpatialParameters();
  47192. this._soundPanner.connect(this._ouputAudioNode);
  47193. this._inputAudioNode = this._soundPanner;
  47194. }
  47195. };
  47196. Sound.prototype._updateSpatialParameters = function () {
  47197. if (this.spatialSound) {
  47198. if (this.useCustomAttenuation) {
  47199. // Tricks to disable in a way embedded Web Audio attenuation
  47200. this._soundPanner.distanceModel = "linear";
  47201. this._soundPanner.maxDistance = Number.MAX_VALUE;
  47202. this._soundPanner.refDistance = 1;
  47203. this._soundPanner.rolloffFactor = 1;
  47204. this._soundPanner.panningModel = this._panningModel;
  47205. }
  47206. else {
  47207. this._soundPanner.distanceModel = this.distanceModel;
  47208. this._soundPanner.maxDistance = this.maxDistance;
  47209. this._soundPanner.refDistance = this.refDistance;
  47210. this._soundPanner.rolloffFactor = this.rolloffFactor;
  47211. this._soundPanner.panningModel = this._panningModel;
  47212. }
  47213. }
  47214. };
  47215. Sound.prototype.switchPanningModelToHRTF = function () {
  47216. this._panningModel = "HRTF";
  47217. this._switchPanningModel();
  47218. };
  47219. Sound.prototype.switchPanningModelToEqualPower = function () {
  47220. this._panningModel = "equalpower";
  47221. this._switchPanningModel();
  47222. };
  47223. Sound.prototype._switchPanningModel = function () {
  47224. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  47225. this._soundPanner.panningModel = this._panningModel;
  47226. }
  47227. };
  47228. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  47229. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47230. if (this._isOutputConnected) {
  47231. this._ouputAudioNode.disconnect();
  47232. }
  47233. this._ouputAudioNode.connect(soundTrackAudioNode);
  47234. this._isOutputConnected = true;
  47235. }
  47236. };
  47237. /**
  47238. * Transform this sound into a directional source
  47239. * @param coneInnerAngle Size of the inner cone in degree
  47240. * @param coneOuterAngle Size of the outer cone in degree
  47241. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  47242. */
  47243. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  47244. if (coneOuterAngle < coneInnerAngle) {
  47245. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  47246. return;
  47247. }
  47248. this._coneInnerAngle = coneInnerAngle;
  47249. this._coneOuterAngle = coneOuterAngle;
  47250. this._coneOuterGain = coneOuterGain;
  47251. this._isDirectional = true;
  47252. if (this.isPlaying && this.loop) {
  47253. this.stop();
  47254. this.play();
  47255. }
  47256. };
  47257. Sound.prototype.setPosition = function (newPosition) {
  47258. this._position = newPosition;
  47259. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  47260. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  47261. }
  47262. };
  47263. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  47264. this._localDirection = newLocalDirection;
  47265. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  47266. this._updateDirection();
  47267. }
  47268. };
  47269. Sound.prototype._updateDirection = function () {
  47270. var mat = this._connectedMesh.getWorldMatrix();
  47271. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  47272. direction.normalize();
  47273. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  47274. };
  47275. Sound.prototype.updateDistanceFromListener = function () {
  47276. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  47277. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  47278. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  47279. }
  47280. };
  47281. Sound.prototype.setAttenuationFunction = function (callback) {
  47282. this._customAttenuationFunction = callback;
  47283. };
  47284. /**
  47285. * Play the sound
  47286. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  47287. * @param offset (optional) Start the sound setting it at a specific time
  47288. */
  47289. Sound.prototype.play = function (time, offset) {
  47290. var _this = this;
  47291. if (this._isReadyToPlay && this._scene.audioEnabled) {
  47292. try {
  47293. if (this._startOffset < 0) {
  47294. time = -this._startOffset;
  47295. this._startOffset = 0;
  47296. }
  47297. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  47298. if (!this._soundSource || !this._streamingSource) {
  47299. if (this.spatialSound) {
  47300. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  47301. if (this._isDirectional) {
  47302. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  47303. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  47304. this._soundPanner.coneOuterGain = this._coneOuterGain;
  47305. if (this._connectedMesh) {
  47306. this._updateDirection();
  47307. }
  47308. else {
  47309. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  47310. }
  47311. }
  47312. }
  47313. }
  47314. if (this._streaming) {
  47315. if (!this._streamingSource) {
  47316. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  47317. this._htmlAudioElement.onended = function () { _this._onended(); };
  47318. this._htmlAudioElement.playbackRate = this._playbackRate;
  47319. }
  47320. this._streamingSource.disconnect();
  47321. this._streamingSource.connect(this._inputAudioNode);
  47322. this._htmlAudioElement.play();
  47323. }
  47324. else {
  47325. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  47326. this._soundSource.buffer = this._audioBuffer;
  47327. this._soundSource.connect(this._inputAudioNode);
  47328. this._soundSource.loop = this.loop;
  47329. this._soundSource.playbackRate.value = this._playbackRate;
  47330. this._soundSource.onended = function () { _this._onended(); };
  47331. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  47332. }
  47333. this._startTime = startTime;
  47334. this.isPlaying = true;
  47335. this.isPaused = false;
  47336. }
  47337. catch (ex) {
  47338. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  47339. }
  47340. }
  47341. };
  47342. Sound.prototype._onended = function () {
  47343. this.isPlaying = false;
  47344. if (this.onended) {
  47345. this.onended();
  47346. }
  47347. };
  47348. /**
  47349. * Stop the sound
  47350. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  47351. */
  47352. Sound.prototype.stop = function (time) {
  47353. if (this.isPlaying) {
  47354. if (this._streaming) {
  47355. this._htmlAudioElement.pause();
  47356. // Test needed for Firefox or it will generate an Invalid State Error
  47357. if (this._htmlAudioElement.currentTime > 0) {
  47358. this._htmlAudioElement.currentTime = 0;
  47359. }
  47360. }
  47361. else {
  47362. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  47363. this._soundSource.stop(stopTime);
  47364. this._soundSource.onended = null;
  47365. if (!this.isPaused) {
  47366. this._startOffset = 0;
  47367. }
  47368. }
  47369. this.isPlaying = false;
  47370. }
  47371. };
  47372. Sound.prototype.pause = function () {
  47373. if (this.isPlaying) {
  47374. this.isPaused = true;
  47375. if (this._streaming) {
  47376. this._htmlAudioElement.pause();
  47377. }
  47378. else {
  47379. this.stop(0);
  47380. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  47381. }
  47382. }
  47383. };
  47384. Sound.prototype.setVolume = function (newVolume, time) {
  47385. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47386. if (time) {
  47387. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  47388. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  47389. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  47390. }
  47391. else {
  47392. this._soundGain.gain.value = newVolume;
  47393. }
  47394. }
  47395. this._volume = newVolume;
  47396. };
  47397. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  47398. this._playbackRate = newPlaybackRate;
  47399. if (this.isPlaying) {
  47400. if (this._streaming) {
  47401. this._htmlAudioElement.playbackRate = this._playbackRate;
  47402. }
  47403. else {
  47404. this._soundSource.playbackRate.value = this._playbackRate;
  47405. }
  47406. }
  47407. };
  47408. Sound.prototype.getVolume = function () {
  47409. return this._volume;
  47410. };
  47411. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  47412. var _this = this;
  47413. if (this._connectedMesh) {
  47414. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  47415. this._registerFunc = null;
  47416. }
  47417. this._connectedMesh = meshToConnectTo;
  47418. if (!this.spatialSound) {
  47419. this.spatialSound = true;
  47420. this._createSpatialParameters();
  47421. if (this.isPlaying && this.loop) {
  47422. this.stop();
  47423. this.play();
  47424. }
  47425. }
  47426. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  47427. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  47428. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  47429. };
  47430. Sound.prototype.detachFromMesh = function () {
  47431. if (this._connectedMesh) {
  47432. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  47433. this._registerFunc = null;
  47434. this._connectedMesh = null;
  47435. }
  47436. };
  47437. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  47438. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  47439. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  47440. this._updateDirection();
  47441. }
  47442. };
  47443. Sound.prototype.clone = function () {
  47444. var _this = this;
  47445. if (!this._streaming) {
  47446. var setBufferAndRun = function () {
  47447. if (_this._isReadyToPlay) {
  47448. clonedSound._audioBuffer = _this.getAudioBuffer();
  47449. clonedSound._isReadyToPlay = true;
  47450. if (clonedSound.autoplay) {
  47451. clonedSound.play();
  47452. }
  47453. }
  47454. else {
  47455. window.setTimeout(setBufferAndRun, 300);
  47456. }
  47457. };
  47458. var currentOptions = {
  47459. autoplay: this.autoplay, loop: this.loop,
  47460. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  47461. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  47462. refDistance: this.refDistance, distanceModel: this.distanceModel
  47463. };
  47464. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  47465. if (this.useCustomAttenuation) {
  47466. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  47467. }
  47468. clonedSound.setPosition(this._position);
  47469. clonedSound.setPlaybackRate(this._playbackRate);
  47470. setBufferAndRun();
  47471. return clonedSound;
  47472. }
  47473. else {
  47474. return null;
  47475. }
  47476. };
  47477. Sound.prototype.getAudioBuffer = function () {
  47478. return this._audioBuffer;
  47479. };
  47480. Sound.prototype.serialize = function () {
  47481. var serializationObject = {
  47482. name: this.name,
  47483. url: this.name,
  47484. autoplay: this.autoplay,
  47485. loop: this.loop,
  47486. volume: this._volume,
  47487. spatialSound: this.spatialSound,
  47488. maxDistance: this.maxDistance,
  47489. rolloffFactor: this.rolloffFactor,
  47490. refDistance: this.refDistance,
  47491. distanceModel: this.distanceModel,
  47492. playbackRate: this._playbackRate,
  47493. panningModel: this._panningModel,
  47494. soundTrackId: this.soundTrackId
  47495. };
  47496. if (this.spatialSound) {
  47497. if (this._connectedMesh)
  47498. serializationObject.connectedMeshId = this._connectedMesh.id;
  47499. serializationObject.position = this._position.asArray();
  47500. serializationObject.refDistance = this.refDistance;
  47501. serializationObject.distanceModel = this.distanceModel;
  47502. serializationObject.isDirectional = this._isDirectional;
  47503. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  47504. serializationObject.coneInnerAngle = this._coneInnerAngle;
  47505. serializationObject.coneOuterAngle = this._coneOuterAngle;
  47506. serializationObject.coneOuterGain = this._coneOuterGain;
  47507. }
  47508. return serializationObject;
  47509. };
  47510. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  47511. var soundName = parsedSound.name;
  47512. var soundUrl;
  47513. if (parsedSound.url) {
  47514. soundUrl = rootUrl + parsedSound.url;
  47515. }
  47516. else {
  47517. soundUrl = rootUrl + soundName;
  47518. }
  47519. var options = {
  47520. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  47521. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  47522. rolloffFactor: parsedSound.rolloffFactor,
  47523. refDistance: parsedSound.refDistance,
  47524. distanceModel: parsedSound.distanceModel,
  47525. playbackRate: parsedSound.playbackRate
  47526. };
  47527. var newSound;
  47528. if (!sourceSound) {
  47529. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  47530. scene._addPendingData(newSound);
  47531. }
  47532. else {
  47533. var setBufferAndRun = function () {
  47534. if (sourceSound._isReadyToPlay) {
  47535. newSound._audioBuffer = sourceSound.getAudioBuffer();
  47536. newSound._isReadyToPlay = true;
  47537. if (newSound.autoplay) {
  47538. newSound.play();
  47539. }
  47540. }
  47541. else {
  47542. window.setTimeout(setBufferAndRun, 300);
  47543. }
  47544. };
  47545. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  47546. setBufferAndRun();
  47547. }
  47548. if (parsedSound.position) {
  47549. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  47550. newSound.setPosition(soundPosition);
  47551. }
  47552. if (parsedSound.isDirectional) {
  47553. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  47554. if (parsedSound.localDirectionToMesh) {
  47555. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  47556. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  47557. }
  47558. }
  47559. if (parsedSound.connectedMeshId) {
  47560. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  47561. if (connectedMesh) {
  47562. newSound.attachToMesh(connectedMesh);
  47563. }
  47564. }
  47565. return newSound;
  47566. };
  47567. return Sound;
  47568. }());
  47569. BABYLON.Sound = Sound;
  47570. })(BABYLON || (BABYLON = {}));
  47571. //# sourceMappingURL=babylon.sound.js.map
  47572. var BABYLON;
  47573. (function (BABYLON) {
  47574. var SoundTrack = (function () {
  47575. function SoundTrack(scene, options) {
  47576. this.id = -1;
  47577. this._isMainTrack = false;
  47578. this._isInitialized = false;
  47579. this._scene = scene;
  47580. this.soundCollection = new Array();
  47581. this._options = options;
  47582. if (!this._isMainTrack) {
  47583. this._scene.soundTracks.push(this);
  47584. this.id = this._scene.soundTracks.length - 1;
  47585. }
  47586. }
  47587. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  47588. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47589. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  47590. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  47591. if (this._options) {
  47592. if (this._options.volume) {
  47593. this._outputAudioNode.gain.value = this._options.volume;
  47594. }
  47595. if (this._options.mainTrack) {
  47596. this._isMainTrack = this._options.mainTrack;
  47597. }
  47598. }
  47599. this._isInitialized = true;
  47600. }
  47601. };
  47602. SoundTrack.prototype.dispose = function () {
  47603. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47604. if (this._connectedAnalyser) {
  47605. this._connectedAnalyser.stopDebugCanvas();
  47606. }
  47607. while (this.soundCollection.length) {
  47608. this.soundCollection[0].dispose();
  47609. }
  47610. if (this._outputAudioNode) {
  47611. this._outputAudioNode.disconnect();
  47612. }
  47613. this._outputAudioNode = null;
  47614. }
  47615. };
  47616. SoundTrack.prototype.AddSound = function (sound) {
  47617. if (!this._isInitialized) {
  47618. this._initializeSoundTrackAudioGraph();
  47619. }
  47620. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47621. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  47622. }
  47623. if (sound.soundTrackId) {
  47624. if (sound.soundTrackId === -1) {
  47625. this._scene.mainSoundTrack.RemoveSound(sound);
  47626. }
  47627. else {
  47628. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  47629. }
  47630. }
  47631. this.soundCollection.push(sound);
  47632. sound.soundTrackId = this.id;
  47633. };
  47634. SoundTrack.prototype.RemoveSound = function (sound) {
  47635. var index = this.soundCollection.indexOf(sound);
  47636. if (index !== -1) {
  47637. this.soundCollection.splice(index, 1);
  47638. }
  47639. };
  47640. SoundTrack.prototype.setVolume = function (newVolume) {
  47641. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47642. this._outputAudioNode.gain.value = newVolume;
  47643. }
  47644. };
  47645. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  47646. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47647. for (var i = 0; i < this.soundCollection.length; i++) {
  47648. this.soundCollection[i].switchPanningModelToHRTF();
  47649. }
  47650. }
  47651. };
  47652. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  47653. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47654. for (var i = 0; i < this.soundCollection.length; i++) {
  47655. this.soundCollection[i].switchPanningModelToEqualPower();
  47656. }
  47657. }
  47658. };
  47659. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  47660. if (this._connectedAnalyser) {
  47661. this._connectedAnalyser.stopDebugCanvas();
  47662. }
  47663. this._connectedAnalyser = analyser;
  47664. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47665. this._outputAudioNode.disconnect();
  47666. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  47667. }
  47668. };
  47669. return SoundTrack;
  47670. }());
  47671. BABYLON.SoundTrack = SoundTrack;
  47672. })(BABYLON || (BABYLON = {}));
  47673. //# sourceMappingURL=babylon.soundtrack.js.map
  47674. var BABYLON;
  47675. (function (BABYLON) {
  47676. var Analyser = (function () {
  47677. function Analyser(scene) {
  47678. this.SMOOTHING = 0.75;
  47679. this.FFT_SIZE = 512;
  47680. this.BARGRAPHAMPLITUDE = 256;
  47681. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  47682. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  47683. this._scene = scene;
  47684. this._audioEngine = BABYLON.Engine.audioEngine;
  47685. if (this._audioEngine.canUseWebAudio) {
  47686. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  47687. this._webAudioAnalyser.minDecibels = -140;
  47688. this._webAudioAnalyser.maxDecibels = 0;
  47689. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  47690. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  47691. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  47692. }
  47693. }
  47694. Analyser.prototype.getFrequencyBinCount = function () {
  47695. if (this._audioEngine.canUseWebAudio) {
  47696. return this._webAudioAnalyser.frequencyBinCount;
  47697. }
  47698. else {
  47699. return 0;
  47700. }
  47701. };
  47702. Analyser.prototype.getByteFrequencyData = function () {
  47703. if (this._audioEngine.canUseWebAudio) {
  47704. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47705. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47706. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  47707. }
  47708. return this._byteFreqs;
  47709. };
  47710. Analyser.prototype.getByteTimeDomainData = function () {
  47711. if (this._audioEngine.canUseWebAudio) {
  47712. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47713. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47714. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  47715. }
  47716. return this._byteTime;
  47717. };
  47718. Analyser.prototype.getFloatFrequencyData = function () {
  47719. if (this._audioEngine.canUseWebAudio) {
  47720. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47721. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47722. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  47723. }
  47724. return this._floatFreqs;
  47725. };
  47726. Analyser.prototype.drawDebugCanvas = function () {
  47727. var _this = this;
  47728. if (this._audioEngine.canUseWebAudio) {
  47729. if (!this._debugCanvas) {
  47730. this._debugCanvas = document.createElement("canvas");
  47731. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  47732. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  47733. this._debugCanvas.style.position = "absolute";
  47734. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  47735. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  47736. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  47737. document.body.appendChild(this._debugCanvas);
  47738. this._registerFunc = function () {
  47739. _this.drawDebugCanvas();
  47740. };
  47741. this._scene.registerBeforeRender(this._registerFunc);
  47742. }
  47743. if (this._registerFunc) {
  47744. var workingArray = this.getByteFrequencyData();
  47745. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  47746. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  47747. // Draw the frequency domain chart.
  47748. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  47749. var value = workingArray[i];
  47750. var percent = value / this.BARGRAPHAMPLITUDE;
  47751. var height = this.DEBUGCANVASSIZE.height * percent;
  47752. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  47753. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  47754. var hue = i / this.getFrequencyBinCount() * 360;
  47755. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  47756. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  47757. }
  47758. }
  47759. }
  47760. };
  47761. Analyser.prototype.stopDebugCanvas = function () {
  47762. if (this._debugCanvas) {
  47763. this._scene.unregisterBeforeRender(this._registerFunc);
  47764. this._registerFunc = null;
  47765. document.body.removeChild(this._debugCanvas);
  47766. this._debugCanvas = null;
  47767. this._debugCanvasContext = null;
  47768. }
  47769. };
  47770. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  47771. if (this._audioEngine.canUseWebAudio) {
  47772. inputAudioNode.connect(this._webAudioAnalyser);
  47773. this._webAudioAnalyser.connect(outputAudioNode);
  47774. }
  47775. };
  47776. Analyser.prototype.dispose = function () {
  47777. if (this._audioEngine.canUseWebAudio) {
  47778. this._webAudioAnalyser.disconnect();
  47779. }
  47780. };
  47781. return Analyser;
  47782. }());
  47783. BABYLON.Analyser = Analyser;
  47784. })(BABYLON || (BABYLON = {}));
  47785. //# sourceMappingURL=babylon.analyser.js.map
  47786. var BABYLON;
  47787. (function (BABYLON) {
  47788. var CubeTexture = (function (_super) {
  47789. __extends(CubeTexture, _super);
  47790. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  47791. if (onLoad === void 0) { onLoad = null; }
  47792. if (onError === void 0) { onError = null; }
  47793. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  47794. if (prefiltered === void 0) { prefiltered = false; }
  47795. if (forcedExtension === void 0) { forcedExtension = null; }
  47796. var _this = _super.call(this, scene) || this;
  47797. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  47798. _this.name = rootUrl;
  47799. _this.url = rootUrl;
  47800. _this._noMipmap = noMipmap;
  47801. _this.hasAlpha = false;
  47802. _this._format = format;
  47803. _this._prefiltered = prefiltered;
  47804. _this.isCube = true;
  47805. _this._textureMatrix = BABYLON.Matrix.Identity();
  47806. if (prefiltered) {
  47807. _this.gammaSpace = false;
  47808. }
  47809. if (!rootUrl && !files) {
  47810. return _this;
  47811. }
  47812. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  47813. if (!files) {
  47814. if (!extensions) {
  47815. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  47816. }
  47817. files = [];
  47818. for (var index = 0; index < extensions.length; index++) {
  47819. files.push(rootUrl + extensions[index]);
  47820. }
  47821. _this._extensions = extensions;
  47822. }
  47823. _this._files = files;
  47824. if (!_this._texture) {
  47825. if (!scene.useDelayedTextureLoading) {
  47826. if (prefiltered) {
  47827. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  47828. }
  47829. else {
  47830. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  47831. }
  47832. }
  47833. else {
  47834. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  47835. }
  47836. }
  47837. else if (onLoad) {
  47838. if (_this._texture.isReady) {
  47839. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  47840. }
  47841. else {
  47842. _this._texture.onLoadedObservable.add(onLoad);
  47843. }
  47844. }
  47845. return _this;
  47846. }
  47847. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  47848. return new CubeTexture("", scene, null, noMipmap, files);
  47849. };
  47850. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  47851. if (forcedExtension === void 0) { forcedExtension = null; }
  47852. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  47853. };
  47854. // Methods
  47855. CubeTexture.prototype.delayLoad = function () {
  47856. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  47857. return;
  47858. }
  47859. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  47860. this._texture = this._getFromCache(this.url, this._noMipmap);
  47861. if (!this._texture) {
  47862. if (this._prefiltered) {
  47863. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  47864. }
  47865. else {
  47866. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  47867. }
  47868. }
  47869. };
  47870. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  47871. return this._textureMatrix;
  47872. };
  47873. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  47874. this._textureMatrix = value;
  47875. };
  47876. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  47877. var texture = BABYLON.SerializationHelper.Parse(function () {
  47878. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  47879. }, parsedTexture, scene);
  47880. // Animations
  47881. if (parsedTexture.animations) {
  47882. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  47883. var parsedAnimation = parsedTexture.animations[animationIndex];
  47884. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  47885. }
  47886. }
  47887. return texture;
  47888. };
  47889. CubeTexture.prototype.clone = function () {
  47890. var _this = this;
  47891. return BABYLON.SerializationHelper.Clone(function () {
  47892. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  47893. }, this);
  47894. };
  47895. return CubeTexture;
  47896. }(BABYLON.BaseTexture));
  47897. BABYLON.CubeTexture = CubeTexture;
  47898. })(BABYLON || (BABYLON = {}));
  47899. //# sourceMappingURL=babylon.cubeTexture.js.map
  47900. var BABYLON;
  47901. (function (BABYLON) {
  47902. var RenderTargetTexture = (function (_super) {
  47903. __extends(RenderTargetTexture, _super);
  47904. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  47905. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  47906. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  47907. if (isCube === void 0) { isCube = false; }
  47908. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47909. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  47910. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  47911. if (isMulti === void 0) { isMulti = false; }
  47912. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  47913. _this.isCube = isCube;
  47914. /**
  47915. * Use this list to define the list of mesh you want to render.
  47916. */
  47917. _this.renderList = new Array();
  47918. _this.renderParticles = true;
  47919. _this.renderSprites = false;
  47920. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  47921. _this.ignoreCameraViewport = false;
  47922. // Events
  47923. /**
  47924. * An event triggered when the texture is unbind.
  47925. * @type {BABYLON.Observable}
  47926. */
  47927. _this.onBeforeBindObservable = new BABYLON.Observable();
  47928. /**
  47929. * An event triggered when the texture is unbind.
  47930. * @type {BABYLON.Observable}
  47931. */
  47932. _this.onAfterUnbindObservable = new BABYLON.Observable();
  47933. /**
  47934. * An event triggered before rendering the texture
  47935. * @type {BABYLON.Observable}
  47936. */
  47937. _this.onBeforeRenderObservable = new BABYLON.Observable();
  47938. /**
  47939. * An event triggered after rendering the texture
  47940. * @type {BABYLON.Observable}
  47941. */
  47942. _this.onAfterRenderObservable = new BABYLON.Observable();
  47943. /**
  47944. * An event triggered after the texture clear
  47945. * @type {BABYLON.Observable}
  47946. */
  47947. _this.onClearObservable = new BABYLON.Observable();
  47948. _this._currentRefreshId = -1;
  47949. _this._refreshRate = 1;
  47950. _this._samples = 1;
  47951. scene = _this.getScene();
  47952. _this.name = name;
  47953. _this.isRenderTarget = true;
  47954. _this._size = size;
  47955. _this._generateMipMaps = generateMipMaps;
  47956. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  47957. // Rendering groups
  47958. _this._renderingManager = new BABYLON.RenderingManager(scene);
  47959. if (isMulti) {
  47960. return _this;
  47961. }
  47962. _this._renderTargetOptions = {
  47963. generateMipMaps: generateMipMaps,
  47964. type: type,
  47965. samplingMode: samplingMode,
  47966. generateDepthBuffer: generateDepthBuffer,
  47967. generateStencilBuffer: generateStencilBuffer
  47968. };
  47969. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  47970. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47971. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47972. }
  47973. if (isCube) {
  47974. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  47975. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  47976. _this._textureMatrix = BABYLON.Matrix.Identity();
  47977. }
  47978. else {
  47979. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  47980. }
  47981. return _this;
  47982. }
  47983. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  47984. get: function () {
  47985. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  47986. },
  47987. enumerable: true,
  47988. configurable: true
  47989. });
  47990. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  47991. get: function () {
  47992. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  47993. },
  47994. enumerable: true,
  47995. configurable: true
  47996. });
  47997. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  47998. get: function () {
  47999. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  48000. },
  48001. enumerable: true,
  48002. configurable: true
  48003. });
  48004. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  48005. set: function (callback) {
  48006. if (this._onAfterUnbindObserver) {
  48007. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  48008. }
  48009. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  48010. },
  48011. enumerable: true,
  48012. configurable: true
  48013. });
  48014. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  48015. set: function (callback) {
  48016. if (this._onBeforeRenderObserver) {
  48017. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  48018. }
  48019. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  48020. },
  48021. enumerable: true,
  48022. configurable: true
  48023. });
  48024. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  48025. set: function (callback) {
  48026. if (this._onAfterRenderObserver) {
  48027. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  48028. }
  48029. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  48030. },
  48031. enumerable: true,
  48032. configurable: true
  48033. });
  48034. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  48035. set: function (callback) {
  48036. if (this._onClearObserver) {
  48037. this.onClearObservable.remove(this._onClearObserver);
  48038. }
  48039. this._onClearObserver = this.onClearObservable.add(callback);
  48040. },
  48041. enumerable: true,
  48042. configurable: true
  48043. });
  48044. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  48045. get: function () {
  48046. return this._renderTargetOptions;
  48047. },
  48048. enumerable: true,
  48049. configurable: true
  48050. });
  48051. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  48052. get: function () {
  48053. return this._samples;
  48054. },
  48055. set: function (value) {
  48056. if (this._samples === value) {
  48057. return;
  48058. }
  48059. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  48060. },
  48061. enumerable: true,
  48062. configurable: true
  48063. });
  48064. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  48065. this._currentRefreshId = -1;
  48066. };
  48067. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  48068. get: function () {
  48069. return this._refreshRate;
  48070. },
  48071. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  48072. set: function (value) {
  48073. this._refreshRate = value;
  48074. this.resetRefreshCounter();
  48075. },
  48076. enumerable: true,
  48077. configurable: true
  48078. });
  48079. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  48080. if (!this._postProcessManager) {
  48081. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  48082. this._postProcesses = new Array();
  48083. }
  48084. this._postProcesses.push(postProcess);
  48085. this._postProcesses[0].autoClear = false;
  48086. };
  48087. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  48088. if (!this._postProcesses) {
  48089. return;
  48090. }
  48091. if (dispose) {
  48092. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  48093. var postProcess = _a[_i];
  48094. postProcess.dispose();
  48095. postProcess = null;
  48096. }
  48097. }
  48098. this._postProcesses = [];
  48099. };
  48100. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  48101. if (!this._postProcesses) {
  48102. return;
  48103. }
  48104. var index = this._postProcesses.indexOf(postProcess);
  48105. if (index === -1) {
  48106. return;
  48107. }
  48108. this._postProcesses.splice(index, 1);
  48109. if (this._postProcesses.length > 0) {
  48110. this._postProcesses[0].autoClear = false;
  48111. }
  48112. };
  48113. RenderTargetTexture.prototype._shouldRender = function () {
  48114. if (this._currentRefreshId === -1) {
  48115. this._currentRefreshId = 1;
  48116. return true;
  48117. }
  48118. if (this.refreshRate === this._currentRefreshId) {
  48119. this._currentRefreshId = 1;
  48120. return true;
  48121. }
  48122. this._currentRefreshId++;
  48123. return false;
  48124. };
  48125. RenderTargetTexture.prototype.getRenderSize = function () {
  48126. return this._size;
  48127. };
  48128. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  48129. get: function () {
  48130. return true;
  48131. },
  48132. enumerable: true,
  48133. configurable: true
  48134. });
  48135. RenderTargetTexture.prototype.scale = function (ratio) {
  48136. var newSize = this._size * ratio;
  48137. this.resize(newSize);
  48138. };
  48139. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  48140. if (this.isCube) {
  48141. return this._textureMatrix;
  48142. }
  48143. return _super.prototype.getReflectionTextureMatrix.call(this);
  48144. };
  48145. RenderTargetTexture.prototype.resize = function (size) {
  48146. this.releaseInternalTexture();
  48147. if (this.isCube) {
  48148. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  48149. }
  48150. else {
  48151. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  48152. }
  48153. this._size = size;
  48154. };
  48155. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  48156. var scene = this.getScene();
  48157. var engine = scene.getEngine();
  48158. if (this.useCameraPostProcesses !== undefined) {
  48159. useCameraPostProcess = this.useCameraPostProcesses;
  48160. }
  48161. if (this._waitingRenderList) {
  48162. this.renderList = [];
  48163. for (var index = 0; index < this._waitingRenderList.length; index++) {
  48164. var id = this._waitingRenderList[index];
  48165. this.renderList.push(scene.getMeshByID(id));
  48166. }
  48167. delete this._waitingRenderList;
  48168. }
  48169. // Is predicate defined?
  48170. if (this.renderListPredicate) {
  48171. this.renderList.splice(0); // Clear previous renderList
  48172. var sceneMeshes = this.getScene().meshes;
  48173. for (var index = 0; index < sceneMeshes.length; index++) {
  48174. var mesh = sceneMeshes[index];
  48175. if (this.renderListPredicate(mesh)) {
  48176. this.renderList.push(mesh);
  48177. }
  48178. }
  48179. }
  48180. this.onBeforeBindObservable.notifyObservers(this);
  48181. // Set custom projection.
  48182. // Needs to be before binding to prevent changing the aspect ratio.
  48183. var camera;
  48184. if (this.activeCamera) {
  48185. camera = this.activeCamera;
  48186. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  48187. if (this.activeCamera !== scene.activeCamera) {
  48188. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  48189. }
  48190. }
  48191. else {
  48192. camera = scene.activeCamera;
  48193. engine.setViewport(scene.activeCamera.viewport, this._size, this._size);
  48194. }
  48195. // Prepare renderingManager
  48196. this._renderingManager.reset();
  48197. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  48198. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  48199. var sceneRenderId = scene.getRenderId();
  48200. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  48201. var mesh = currentRenderList[meshIndex];
  48202. if (mesh) {
  48203. if (!mesh.isReady()) {
  48204. // Reset _currentRefreshId
  48205. this.resetRefreshCounter();
  48206. continue;
  48207. }
  48208. mesh._preActivateForIntermediateRendering(sceneRenderId);
  48209. var isMasked = void 0;
  48210. if (!this.renderList) {
  48211. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  48212. }
  48213. else {
  48214. isMasked = false;
  48215. }
  48216. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  48217. mesh._activate(sceneRenderId);
  48218. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  48219. var subMesh = mesh.subMeshes[subIndex];
  48220. scene._activeIndices.addCount(subMesh.indexCount, false);
  48221. this._renderingManager.dispatch(subMesh);
  48222. }
  48223. }
  48224. }
  48225. }
  48226. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  48227. var particleSystem = scene.particleSystems[particleIndex];
  48228. var emitter = particleSystem.emitter;
  48229. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  48230. continue;
  48231. }
  48232. if (currentRenderList.indexOf(emitter) >= 0) {
  48233. this._renderingManager.dispatchParticles(particleSystem);
  48234. }
  48235. }
  48236. if (this.isCube) {
  48237. for (var face = 0; face < 6; face++) {
  48238. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  48239. scene.incrementRenderId();
  48240. scene.resetCachedMaterial();
  48241. }
  48242. }
  48243. else {
  48244. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  48245. }
  48246. this.onAfterUnbindObservable.notifyObservers(this);
  48247. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  48248. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  48249. }
  48250. engine.setViewport(scene.activeCamera.viewport);
  48251. scene.resetCachedMaterial();
  48252. };
  48253. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  48254. var _this = this;
  48255. var scene = this.getScene();
  48256. var engine = scene.getEngine();
  48257. // Bind
  48258. if (this._postProcessManager) {
  48259. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  48260. }
  48261. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  48262. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  48263. }
  48264. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  48265. // Clear
  48266. if (this.onClearObservable.hasObservers()) {
  48267. this.onClearObservable.notifyObservers(engine);
  48268. }
  48269. else {
  48270. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  48271. }
  48272. if (!this._doNotChangeAspectRatio) {
  48273. scene.updateTransformMatrix(true);
  48274. }
  48275. // Render
  48276. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  48277. if (this._postProcessManager) {
  48278. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  48279. }
  48280. else if (useCameraPostProcess) {
  48281. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  48282. }
  48283. if (!this._doNotChangeAspectRatio) {
  48284. scene.updateTransformMatrix(true);
  48285. }
  48286. // Dump ?
  48287. if (dumpForDebug) {
  48288. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  48289. }
  48290. // Unbind
  48291. if (!this.isCube || faceIndex === 5) {
  48292. if (this.isCube) {
  48293. if (faceIndex === 5) {
  48294. engine.generateMipMapsForCubemap(this._texture);
  48295. }
  48296. }
  48297. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  48298. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  48299. });
  48300. }
  48301. else {
  48302. this.onAfterRenderObservable.notifyObservers(faceIndex);
  48303. }
  48304. };
  48305. /**
  48306. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  48307. * This allowed control for front to back rendering or reversly depending of the special needs.
  48308. *
  48309. * @param renderingGroupId The rendering group id corresponding to its index
  48310. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  48311. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  48312. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  48313. */
  48314. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  48315. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  48316. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  48317. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  48318. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  48319. };
  48320. /**
  48321. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  48322. *
  48323. * @param renderingGroupId The rendering group id corresponding to its index
  48324. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  48325. */
  48326. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  48327. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  48328. };
  48329. RenderTargetTexture.prototype.clone = function () {
  48330. var textureSize = this.getSize();
  48331. 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);
  48332. // Base texture
  48333. newTexture.hasAlpha = this.hasAlpha;
  48334. newTexture.level = this.level;
  48335. // RenderTarget Texture
  48336. newTexture.coordinatesMode = this.coordinatesMode;
  48337. newTexture.renderList = this.renderList.slice(0);
  48338. return newTexture;
  48339. };
  48340. RenderTargetTexture.prototype.serialize = function () {
  48341. if (!this.name) {
  48342. return null;
  48343. }
  48344. var serializationObject = _super.prototype.serialize.call(this);
  48345. serializationObject.renderTargetSize = this.getRenderSize();
  48346. serializationObject.renderList = [];
  48347. for (var index = 0; index < this.renderList.length; index++) {
  48348. serializationObject.renderList.push(this.renderList[index].id);
  48349. }
  48350. return serializationObject;
  48351. };
  48352. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  48353. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  48354. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  48355. };
  48356. RenderTargetTexture.prototype.dispose = function () {
  48357. if (this._postProcessManager) {
  48358. this._postProcessManager.dispose();
  48359. this._postProcessManager = null;
  48360. }
  48361. this.clearPostProcesses(true);
  48362. this.renderList = null;
  48363. // Remove from custom render targets
  48364. var scene = this.getScene();
  48365. var index = scene.customRenderTargets.indexOf(this);
  48366. if (index >= 0) {
  48367. scene.customRenderTargets.splice(index, 1);
  48368. }
  48369. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  48370. var camera = _a[_i];
  48371. index = camera.customRenderTargets.indexOf(this);
  48372. if (index >= 0) {
  48373. camera.customRenderTargets.splice(index, 1);
  48374. }
  48375. }
  48376. _super.prototype.dispose.call(this);
  48377. };
  48378. RenderTargetTexture.prototype._rebuild = function () {
  48379. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  48380. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  48381. }
  48382. if (this._postProcessManager) {
  48383. this._postProcessManager._rebuild();
  48384. }
  48385. };
  48386. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  48387. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  48388. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  48389. return RenderTargetTexture;
  48390. }(BABYLON.Texture));
  48391. BABYLON.RenderTargetTexture = RenderTargetTexture;
  48392. })(BABYLON || (BABYLON = {}));
  48393. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  48394. var BABYLON;
  48395. (function (BABYLON) {
  48396. ;
  48397. var MultiRenderTarget = (function (_super) {
  48398. __extends(MultiRenderTarget, _super);
  48399. function MultiRenderTarget(name, size, count, scene, options) {
  48400. var _this = this;
  48401. options = options || {};
  48402. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  48403. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  48404. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  48405. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  48406. if (!_this.isSupported) {
  48407. _this.dispose();
  48408. return;
  48409. }
  48410. var types = [];
  48411. var samplingModes = [];
  48412. for (var i = 0; i < count; i++) {
  48413. if (options.types && options.types[i]) {
  48414. types.push(options.types[i]);
  48415. }
  48416. else {
  48417. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  48418. }
  48419. if (options.samplingModes && options.samplingModes[i]) {
  48420. samplingModes.push(options.samplingModes[i]);
  48421. }
  48422. else {
  48423. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  48424. }
  48425. }
  48426. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  48427. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  48428. _this._count = count;
  48429. _this._size = size;
  48430. _this._multiRenderTargetOptions = {
  48431. samplingModes: samplingModes,
  48432. generateMipMaps: generateMipMaps,
  48433. generateDepthBuffer: generateDepthBuffer,
  48434. generateStencilBuffer: generateStencilBuffer,
  48435. generateDepthTexture: generateDepthTexture,
  48436. types: types,
  48437. textureCount: count
  48438. };
  48439. _this._createInternalTextures();
  48440. _this._createTextures();
  48441. return _this;
  48442. }
  48443. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  48444. get: function () {
  48445. var engine = this.getScene().getEngine();
  48446. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  48447. },
  48448. enumerable: true,
  48449. configurable: true
  48450. });
  48451. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  48452. get: function () {
  48453. return this._textures;
  48454. },
  48455. enumerable: true,
  48456. configurable: true
  48457. });
  48458. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  48459. get: function () {
  48460. return this._textures[this._textures.length - 1];
  48461. },
  48462. enumerable: true,
  48463. configurable: true
  48464. });
  48465. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  48466. set: function (wrap) {
  48467. if (this._textures) {
  48468. for (var i = 0; i < this._textures.length; i++) {
  48469. this._textures[i].wrapU = wrap;
  48470. }
  48471. }
  48472. },
  48473. enumerable: true,
  48474. configurable: true
  48475. });
  48476. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  48477. set: function (wrap) {
  48478. if (this._textures) {
  48479. for (var i = 0; i < this._textures.length; i++) {
  48480. this._textures[i].wrapV = wrap;
  48481. }
  48482. }
  48483. },
  48484. enumerable: true,
  48485. configurable: true
  48486. });
  48487. MultiRenderTarget.prototype._rebuild = function () {
  48488. this.releaseInternalTextures();
  48489. this._createInternalTextures();
  48490. for (var i = 0; i < this._internalTextures.length; i++) {
  48491. var texture = this._textures[i];
  48492. texture._texture = this._internalTextures[i];
  48493. }
  48494. // Keeps references to frame buffer and stencil/depth buffer
  48495. this._texture = this._internalTextures[0];
  48496. };
  48497. MultiRenderTarget.prototype._createInternalTextures = function () {
  48498. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  48499. };
  48500. MultiRenderTarget.prototype._createTextures = function () {
  48501. this._textures = [];
  48502. for (var i = 0; i < this._internalTextures.length; i++) {
  48503. var texture = new BABYLON.Texture(null, this.getScene());
  48504. texture._texture = this._internalTextures[i];
  48505. this._textures.push(texture);
  48506. }
  48507. // Keeps references to frame buffer and stencil/depth buffer
  48508. this._texture = this._internalTextures[0];
  48509. };
  48510. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  48511. get: function () {
  48512. return this._samples;
  48513. },
  48514. set: function (value) {
  48515. if (this._samples === value) {
  48516. return;
  48517. }
  48518. for (var i = 0; i < this._internalTextures.length; i++) {
  48519. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  48520. }
  48521. },
  48522. enumerable: true,
  48523. configurable: true
  48524. });
  48525. MultiRenderTarget.prototype.resize = function (size) {
  48526. this.releaseInternalTextures();
  48527. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  48528. this._createInternalTextures();
  48529. };
  48530. MultiRenderTarget.prototype.dispose = function () {
  48531. this.releaseInternalTextures();
  48532. _super.prototype.dispose.call(this);
  48533. };
  48534. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  48535. if (!this._internalTextures) {
  48536. return;
  48537. }
  48538. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  48539. if (this._internalTextures[i] !== undefined) {
  48540. this._internalTextures[i].dispose();
  48541. this._internalTextures.splice(i, 1);
  48542. }
  48543. }
  48544. };
  48545. return MultiRenderTarget;
  48546. }(BABYLON.RenderTargetTexture));
  48547. BABYLON.MultiRenderTarget = MultiRenderTarget;
  48548. })(BABYLON || (BABYLON = {}));
  48549. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  48550. /// <reference path="babylon.renderTargetTexture.ts" />
  48551. var BABYLON;
  48552. (function (BABYLON) {
  48553. var MirrorTexture = (function (_super) {
  48554. __extends(MirrorTexture, _super);
  48555. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  48556. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  48557. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48558. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  48559. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  48560. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  48561. _this._transformMatrix = BABYLON.Matrix.Zero();
  48562. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  48563. _this._blurKernelX = 0;
  48564. _this._blurKernelY = 0;
  48565. _this._blurRatio = 1.0;
  48566. _this.ignoreCameraViewport = true;
  48567. _this.onBeforeRenderObservable.add(function () {
  48568. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  48569. _this._savedViewMatrix = scene.getViewMatrix();
  48570. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  48571. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  48572. scene.clipPlane = _this.mirrorPlane;
  48573. scene.getEngine().cullBackFaces = false;
  48574. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  48575. });
  48576. _this.onAfterRenderObservable.add(function () {
  48577. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  48578. scene.getEngine().cullBackFaces = true;
  48579. scene._mirroredCameraPosition = null;
  48580. delete scene.clipPlane;
  48581. });
  48582. return _this;
  48583. }
  48584. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  48585. get: function () {
  48586. return this._blurRatio;
  48587. },
  48588. set: function (value) {
  48589. if (this._blurRatio === value) {
  48590. return;
  48591. }
  48592. this._blurRatio = value;
  48593. this._preparePostProcesses();
  48594. },
  48595. enumerable: true,
  48596. configurable: true
  48597. });
  48598. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  48599. set: function (value) {
  48600. this.blurKernelX = value;
  48601. this.blurKernelY = value;
  48602. },
  48603. enumerable: true,
  48604. configurable: true
  48605. });
  48606. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  48607. get: function () {
  48608. return this._blurKernelX;
  48609. },
  48610. set: function (value) {
  48611. if (this._blurKernelX === value) {
  48612. return;
  48613. }
  48614. this._blurKernelX = value;
  48615. this._preparePostProcesses();
  48616. },
  48617. enumerable: true,
  48618. configurable: true
  48619. });
  48620. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  48621. get: function () {
  48622. return this._blurKernelY;
  48623. },
  48624. set: function (value) {
  48625. if (this._blurKernelY === value) {
  48626. return;
  48627. }
  48628. this._blurKernelY = value;
  48629. this._preparePostProcesses();
  48630. },
  48631. enumerable: true,
  48632. configurable: true
  48633. });
  48634. MirrorTexture.prototype._preparePostProcesses = function () {
  48635. this.clearPostProcesses(true);
  48636. if (this._blurKernelX && this._blurKernelY) {
  48637. var engine = this.getScene().getEngine();
  48638. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  48639. 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);
  48640. this._blurX.autoClear = false;
  48641. if (this._blurRatio === 1 && this.samples < 2) {
  48642. this._blurX.outputTexture = this._texture;
  48643. }
  48644. else {
  48645. this._blurX.alwaysForcePOT = true;
  48646. }
  48647. 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);
  48648. this._blurY.autoClear = false;
  48649. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  48650. this.addPostProcess(this._blurX);
  48651. this.addPostProcess(this._blurY);
  48652. }
  48653. };
  48654. MirrorTexture.prototype.clone = function () {
  48655. var textureSize = this.getSize();
  48656. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  48657. // Base texture
  48658. newTexture.hasAlpha = this.hasAlpha;
  48659. newTexture.level = this.level;
  48660. // Mirror Texture
  48661. newTexture.mirrorPlane = this.mirrorPlane.clone();
  48662. newTexture.renderList = this.renderList.slice(0);
  48663. return newTexture;
  48664. };
  48665. MirrorTexture.prototype.serialize = function () {
  48666. if (!this.name) {
  48667. return null;
  48668. }
  48669. var serializationObject = _super.prototype.serialize.call(this);
  48670. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  48671. return serializationObject;
  48672. };
  48673. return MirrorTexture;
  48674. }(BABYLON.RenderTargetTexture));
  48675. BABYLON.MirrorTexture = MirrorTexture;
  48676. })(BABYLON || (BABYLON = {}));
  48677. //# sourceMappingURL=babylon.mirrorTexture.js.map
  48678. /// <reference path="babylon.renderTargetTexture.ts" />
  48679. var BABYLON;
  48680. (function (BABYLON) {
  48681. /**
  48682. * Creates a refraction texture used by refraction channel of the standard material.
  48683. * @param name the texture name
  48684. * @param size size of the underlying texture
  48685. * @param scene root scene
  48686. */
  48687. var RefractionTexture = (function (_super) {
  48688. __extends(RefractionTexture, _super);
  48689. function RefractionTexture(name, size, scene, generateMipMaps) {
  48690. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  48691. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  48692. _this.depth = 2.0;
  48693. _this.onBeforeRenderObservable.add(function () {
  48694. scene.clipPlane = _this.refractionPlane;
  48695. });
  48696. _this.onAfterRenderObservable.add(function () {
  48697. delete scene.clipPlane;
  48698. });
  48699. return _this;
  48700. }
  48701. RefractionTexture.prototype.clone = function () {
  48702. var textureSize = this.getSize();
  48703. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  48704. // Base texture
  48705. newTexture.hasAlpha = this.hasAlpha;
  48706. newTexture.level = this.level;
  48707. // Refraction Texture
  48708. newTexture.refractionPlane = this.refractionPlane.clone();
  48709. newTexture.renderList = this.renderList.slice(0);
  48710. newTexture.depth = this.depth;
  48711. return newTexture;
  48712. };
  48713. RefractionTexture.prototype.serialize = function () {
  48714. if (!this.name) {
  48715. return null;
  48716. }
  48717. var serializationObject = _super.prototype.serialize.call(this);
  48718. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  48719. serializationObject.depth = this.depth;
  48720. return serializationObject;
  48721. };
  48722. return RefractionTexture;
  48723. }(BABYLON.RenderTargetTexture));
  48724. BABYLON.RefractionTexture = RefractionTexture;
  48725. })(BABYLON || (BABYLON = {}));
  48726. //# sourceMappingURL=babylon.refractionTexture.js.map
  48727. /// <reference path="babylon.texture.ts" />
  48728. var BABYLON;
  48729. (function (BABYLON) {
  48730. var DynamicTexture = (function (_super) {
  48731. __extends(DynamicTexture, _super);
  48732. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  48733. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48734. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  48735. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  48736. _this.name = name;
  48737. var engine = _this.getScene().getEngine();
  48738. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48739. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48740. _this._generateMipMaps = generateMipMaps;
  48741. if (options.getContext) {
  48742. _this._canvas = options;
  48743. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  48744. }
  48745. else {
  48746. _this._canvas = document.createElement("canvas");
  48747. if (options.width) {
  48748. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  48749. }
  48750. else {
  48751. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  48752. }
  48753. }
  48754. var textureSize = _this.getSize();
  48755. _this._canvas.width = textureSize.width;
  48756. _this._canvas.height = textureSize.height;
  48757. _this._context = _this._canvas.getContext("2d");
  48758. return _this;
  48759. }
  48760. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  48761. get: function () {
  48762. return true;
  48763. },
  48764. enumerable: true,
  48765. configurable: true
  48766. });
  48767. DynamicTexture.prototype._recreate = function (textureSize) {
  48768. this._canvas.width = textureSize.width;
  48769. this._canvas.height = textureSize.height;
  48770. this.releaseInternalTexture();
  48771. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  48772. };
  48773. DynamicTexture.prototype.scale = function (ratio) {
  48774. var textureSize = this.getSize();
  48775. textureSize.width *= ratio;
  48776. textureSize.height *= ratio;
  48777. this._recreate(textureSize);
  48778. };
  48779. DynamicTexture.prototype.scaleTo = function (width, height) {
  48780. var textureSize = this.getSize();
  48781. textureSize.width = width;
  48782. textureSize.height = height;
  48783. this._recreate(textureSize);
  48784. };
  48785. DynamicTexture.prototype.getContext = function () {
  48786. return this._context;
  48787. };
  48788. DynamicTexture.prototype.clear = function () {
  48789. var size = this.getSize();
  48790. this._context.fillRect(0, 0, size.width, size.height);
  48791. };
  48792. DynamicTexture.prototype.update = function (invertY) {
  48793. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  48794. };
  48795. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  48796. if (update === void 0) { update = true; }
  48797. var size = this.getSize();
  48798. if (clearColor) {
  48799. this._context.fillStyle = clearColor;
  48800. this._context.fillRect(0, 0, size.width, size.height);
  48801. }
  48802. this._context.font = font;
  48803. if (x === null || x === undefined) {
  48804. var textSize = this._context.measureText(text);
  48805. x = (size.width - textSize.width) / 2;
  48806. }
  48807. if (y === null || y === undefined) {
  48808. var fontSize = parseInt((font.replace(/\D/g, '')));
  48809. ;
  48810. y = (size.height / 2) + (fontSize / 3.65);
  48811. }
  48812. this._context.fillStyle = color;
  48813. this._context.fillText(text, x, y);
  48814. if (update) {
  48815. this.update(invertY);
  48816. }
  48817. };
  48818. DynamicTexture.prototype.clone = function () {
  48819. var textureSize = this.getSize();
  48820. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  48821. // Base texture
  48822. newTexture.hasAlpha = this.hasAlpha;
  48823. newTexture.level = this.level;
  48824. // Dynamic Texture
  48825. newTexture.wrapU = this.wrapU;
  48826. newTexture.wrapV = this.wrapV;
  48827. return newTexture;
  48828. };
  48829. DynamicTexture.prototype._rebuild = function () {
  48830. this.update();
  48831. };
  48832. return DynamicTexture;
  48833. }(BABYLON.Texture));
  48834. BABYLON.DynamicTexture = DynamicTexture;
  48835. })(BABYLON || (BABYLON = {}));
  48836. //# sourceMappingURL=babylon.dynamicTexture.js.map
  48837. var BABYLON;
  48838. (function (BABYLON) {
  48839. var VideoTexture = (function (_super) {
  48840. __extends(VideoTexture, _super);
  48841. /**
  48842. * Creates a video texture.
  48843. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  48844. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  48845. * @param {BABYLON.Scene} scene is obviously the current scene.
  48846. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  48847. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  48848. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  48849. */
  48850. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  48851. if (generateMipMaps === void 0) { generateMipMaps = false; }
  48852. if (invertY === void 0) { invertY = false; }
  48853. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48854. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  48855. _this._autoLaunch = true;
  48856. var urls;
  48857. _this.name = name;
  48858. if (urlsOrVideo instanceof HTMLVideoElement) {
  48859. _this.video = urlsOrVideo;
  48860. }
  48861. else {
  48862. urls = urlsOrVideo;
  48863. _this.video = document.createElement("video");
  48864. _this.video.autoplay = false;
  48865. _this.video.loop = true;
  48866. }
  48867. _this._generateMipMaps = generateMipMaps;
  48868. _this._samplingMode = samplingMode;
  48869. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  48870. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  48871. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  48872. }
  48873. else {
  48874. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48875. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48876. _this._generateMipMaps = false;
  48877. }
  48878. if (urls) {
  48879. _this.video.addEventListener("canplay", function () {
  48880. _this._createTexture();
  48881. });
  48882. urls.forEach(function (url) {
  48883. var source = document.createElement("source");
  48884. source.src = url;
  48885. _this.video.appendChild(source);
  48886. });
  48887. }
  48888. else {
  48889. _this._createTexture();
  48890. }
  48891. _this._lastUpdate = BABYLON.Tools.Now;
  48892. return _this;
  48893. }
  48894. VideoTexture.prototype.__setTextureReady = function () {
  48895. this._texture.isReady = true;
  48896. };
  48897. VideoTexture.prototype._createTexture = function () {
  48898. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  48899. if (this._autoLaunch) {
  48900. this._autoLaunch = false;
  48901. this.video.play();
  48902. }
  48903. this._setTextureReady = this.__setTextureReady.bind(this);
  48904. this.video.addEventListener("playing", this._setTextureReady);
  48905. };
  48906. VideoTexture.prototype._rebuild = function () {
  48907. this.update();
  48908. };
  48909. VideoTexture.prototype.update = function () {
  48910. var now = BABYLON.Tools.Now;
  48911. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  48912. return false;
  48913. }
  48914. this._lastUpdate = now;
  48915. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  48916. return true;
  48917. };
  48918. VideoTexture.prototype.dispose = function () {
  48919. _super.prototype.dispose.call(this);
  48920. this.video.removeEventListener("playing", this._setTextureReady);
  48921. };
  48922. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  48923. var video = document.createElement("video");
  48924. var constraintsDeviceId;
  48925. if (constraints && constraints.deviceId) {
  48926. constraintsDeviceId = {
  48927. exact: constraints.deviceId
  48928. };
  48929. }
  48930. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  48931. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  48932. if (navigator.getUserMedia) {
  48933. navigator.getUserMedia({
  48934. video: {
  48935. deviceId: constraintsDeviceId,
  48936. width: {
  48937. min: (constraints && constraints.minWidth) || 256,
  48938. max: (constraints && constraints.maxWidth) || 640
  48939. },
  48940. height: {
  48941. min: (constraints && constraints.minHeight) || 256,
  48942. max: (constraints && constraints.maxHeight) || 480
  48943. }
  48944. }
  48945. }, function (stream) {
  48946. if (video.mozSrcObject !== undefined) {
  48947. video.mozSrcObject = stream;
  48948. }
  48949. else {
  48950. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  48951. }
  48952. video.play();
  48953. if (onReady) {
  48954. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  48955. }
  48956. }, function (e) {
  48957. BABYLON.Tools.Error(e.name);
  48958. });
  48959. }
  48960. };
  48961. return VideoTexture;
  48962. }(BABYLON.Texture));
  48963. BABYLON.VideoTexture = VideoTexture;
  48964. })(BABYLON || (BABYLON = {}));
  48965. //# sourceMappingURL=babylon.videoTexture.js.map
  48966. var BABYLON;
  48967. (function (BABYLON) {
  48968. var RawTexture = (function (_super) {
  48969. __extends(RawTexture, _super);
  48970. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  48971. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48972. if (invertY === void 0) { invertY = false; }
  48973. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48974. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  48975. _this.format = format;
  48976. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  48977. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48978. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48979. return _this;
  48980. }
  48981. RawTexture.prototype.update = function (data) {
  48982. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  48983. };
  48984. // Statics
  48985. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48986. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48987. if (invertY === void 0) { invertY = false; }
  48988. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48989. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  48990. };
  48991. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48992. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48993. if (invertY === void 0) { invertY = false; }
  48994. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48995. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  48996. };
  48997. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48998. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48999. if (invertY === void 0) { invertY = false; }
  49000. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49001. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  49002. };
  49003. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49004. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49005. if (invertY === void 0) { invertY = false; }
  49006. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49007. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  49008. };
  49009. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49010. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49011. if (invertY === void 0) { invertY = false; }
  49012. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49013. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  49014. };
  49015. return RawTexture;
  49016. }(BABYLON.Texture));
  49017. BABYLON.RawTexture = RawTexture;
  49018. })(BABYLON || (BABYLON = {}));
  49019. //# sourceMappingURL=babylon.rawTexture.js.map
  49020. var BABYLON;
  49021. (function (BABYLON) {
  49022. var PostProcess = (function () {
  49023. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  49024. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  49025. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49026. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  49027. if (blockCompilation === void 0) { blockCompilation = false; }
  49028. this.name = name;
  49029. this.width = -1;
  49030. this.height = -1;
  49031. this.autoClear = true;
  49032. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  49033. /*
  49034. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  49035. Can only be used on a single postprocess or on the last one of a chain.
  49036. */
  49037. this.enablePixelPerfectMode = false;
  49038. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  49039. this.alwaysForcePOT = false;
  49040. this.samples = 1;
  49041. this.adaptScaleToCurrentViewport = false;
  49042. this._reusable = false;
  49043. this._textures = new BABYLON.SmartArray(2);
  49044. this._currentRenderTextureInd = 0;
  49045. this._scaleRatio = new BABYLON.Vector2(1, 1);
  49046. this._texelSize = BABYLON.Vector2.Zero();
  49047. // Events
  49048. /**
  49049. * An event triggered when the postprocess is activated.
  49050. * @type {BABYLON.Observable}
  49051. */
  49052. this.onActivateObservable = new BABYLON.Observable();
  49053. /**
  49054. * An event triggered when the postprocess changes its size.
  49055. * @type {BABYLON.Observable}
  49056. */
  49057. this.onSizeChangedObservable = new BABYLON.Observable();
  49058. /**
  49059. * An event triggered when the postprocess applies its effect.
  49060. * @type {BABYLON.Observable}
  49061. */
  49062. this.onApplyObservable = new BABYLON.Observable();
  49063. /**
  49064. * An event triggered before rendering the postprocess
  49065. * @type {BABYLON.Observable}
  49066. */
  49067. this.onBeforeRenderObservable = new BABYLON.Observable();
  49068. /**
  49069. * An event triggered after rendering the postprocess
  49070. * @type {BABYLON.Observable}
  49071. */
  49072. this.onAfterRenderObservable = new BABYLON.Observable();
  49073. if (camera != null) {
  49074. this._camera = camera;
  49075. this._scene = camera.getScene();
  49076. camera.attachPostProcess(this);
  49077. this._engine = this._scene.getEngine();
  49078. this._scene.postProcesses.push(this);
  49079. }
  49080. else {
  49081. this._engine = engine;
  49082. this._engine.postProcesses.push(this);
  49083. }
  49084. this._options = options;
  49085. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  49086. this._reusable = reusable || false;
  49087. this._textureType = textureType;
  49088. this._samplers = samplers || [];
  49089. this._samplers.push("textureSampler");
  49090. this._fragmentUrl = fragmentUrl;
  49091. this._vertexUrl = vertexUrl;
  49092. this._parameters = parameters || [];
  49093. this._parameters.push("scale");
  49094. this._indexParameters = indexParameters;
  49095. if (!blockCompilation) {
  49096. this.updateEffect(defines);
  49097. }
  49098. }
  49099. Object.defineProperty(PostProcess.prototype, "onActivate", {
  49100. set: function (callback) {
  49101. if (this._onActivateObserver) {
  49102. this.onActivateObservable.remove(this._onActivateObserver);
  49103. }
  49104. this._onActivateObserver = this.onActivateObservable.add(callback);
  49105. },
  49106. enumerable: true,
  49107. configurable: true
  49108. });
  49109. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  49110. set: function (callback) {
  49111. if (this._onSizeChangedObserver) {
  49112. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  49113. }
  49114. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  49115. },
  49116. enumerable: true,
  49117. configurable: true
  49118. });
  49119. Object.defineProperty(PostProcess.prototype, "onApply", {
  49120. set: function (callback) {
  49121. if (this._onApplyObserver) {
  49122. this.onApplyObservable.remove(this._onApplyObserver);
  49123. }
  49124. this._onApplyObserver = this.onApplyObservable.add(callback);
  49125. },
  49126. enumerable: true,
  49127. configurable: true
  49128. });
  49129. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  49130. set: function (callback) {
  49131. if (this._onBeforeRenderObserver) {
  49132. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  49133. }
  49134. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  49135. },
  49136. enumerable: true,
  49137. configurable: true
  49138. });
  49139. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  49140. set: function (callback) {
  49141. if (this._onAfterRenderObserver) {
  49142. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  49143. }
  49144. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  49145. },
  49146. enumerable: true,
  49147. configurable: true
  49148. });
  49149. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  49150. get: function () {
  49151. return this._textures.data[this._currentRenderTextureInd];
  49152. },
  49153. set: function (value) {
  49154. this._forcedOutputTexture = value;
  49155. },
  49156. enumerable: true,
  49157. configurable: true
  49158. });
  49159. PostProcess.prototype.getCamera = function () {
  49160. return this._camera;
  49161. };
  49162. Object.defineProperty(PostProcess.prototype, "texelSize", {
  49163. get: function () {
  49164. if (this._shareOutputWithPostProcess) {
  49165. return this._shareOutputWithPostProcess.texelSize;
  49166. }
  49167. if (this._forcedOutputTexture) {
  49168. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  49169. }
  49170. return this._texelSize;
  49171. },
  49172. enumerable: true,
  49173. configurable: true
  49174. });
  49175. PostProcess.prototype.getEngine = function () {
  49176. return this._engine;
  49177. };
  49178. PostProcess.prototype.getEffect = function () {
  49179. return this._effect;
  49180. };
  49181. PostProcess.prototype.shareOutputWith = function (postProcess) {
  49182. this._disposeTextures();
  49183. this._shareOutputWithPostProcess = postProcess;
  49184. return this;
  49185. };
  49186. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  49187. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== undefined ? defines : "", null, onCompiled, onError, indexParameters || this._indexParameters);
  49188. };
  49189. PostProcess.prototype.isReusable = function () {
  49190. return this._reusable;
  49191. };
  49192. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  49193. PostProcess.prototype.markTextureDirty = function () {
  49194. this.width = -1;
  49195. };
  49196. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  49197. var _this = this;
  49198. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  49199. camera = camera || this._camera;
  49200. var scene = camera.getScene();
  49201. var engine = scene.getEngine();
  49202. var maxSize = engine.getCaps().maxTextureSize;
  49203. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  49204. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  49205. var desiredWidth = (this._options.width || requiredWidth);
  49206. var desiredHeight = this._options.height || requiredHeight;
  49207. if (this.adaptScaleToCurrentViewport) {
  49208. var currentViewport = engine.currentViewport;
  49209. if (currentViewport) {
  49210. desiredWidth *= currentViewport.width;
  49211. desiredHeight *= currentViewport.height;
  49212. }
  49213. }
  49214. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  49215. if (!this._options.width) {
  49216. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  49217. }
  49218. if (!this._options.height) {
  49219. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  49220. }
  49221. }
  49222. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  49223. if (this._textures.length > 0) {
  49224. for (var i = 0; i < this._textures.length; i++) {
  49225. this._engine._releaseTexture(this._textures.data[i]);
  49226. }
  49227. this._textures.reset();
  49228. }
  49229. this.width = desiredWidth;
  49230. this.height = desiredHeight;
  49231. var textureSize = { width: this.width, height: this.height };
  49232. var textureOptions = {
  49233. generateMipMaps: false,
  49234. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  49235. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  49236. samplingMode: this.renderTargetSamplingMode,
  49237. type: this._textureType
  49238. };
  49239. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  49240. if (this._reusable) {
  49241. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  49242. }
  49243. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  49244. this.onSizeChangedObservable.notifyObservers(this);
  49245. }
  49246. this._textures.forEach(function (texture) {
  49247. if (texture.samples !== _this.samples) {
  49248. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  49249. }
  49250. });
  49251. }
  49252. var target;
  49253. if (this._shareOutputWithPostProcess) {
  49254. target = this._shareOutputWithPostProcess.outputTexture;
  49255. }
  49256. else if (this._forcedOutputTexture) {
  49257. target = this._forcedOutputTexture;
  49258. this.width = this._forcedOutputTexture.width;
  49259. this.height = this._forcedOutputTexture.height;
  49260. }
  49261. else {
  49262. target = this.outputTexture;
  49263. }
  49264. if (this.enablePixelPerfectMode) {
  49265. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  49266. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  49267. }
  49268. else {
  49269. this._scaleRatio.copyFromFloats(1, 1);
  49270. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  49271. }
  49272. this.onActivateObservable.notifyObservers(camera);
  49273. // Clear
  49274. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  49275. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  49276. }
  49277. if (this._reusable) {
  49278. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  49279. }
  49280. };
  49281. Object.defineProperty(PostProcess.prototype, "isSupported", {
  49282. get: function () {
  49283. return this._effect.isSupported;
  49284. },
  49285. enumerable: true,
  49286. configurable: true
  49287. });
  49288. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  49289. get: function () {
  49290. if (this._shareOutputWithPostProcess) {
  49291. return this._shareOutputWithPostProcess.aspectRatio;
  49292. }
  49293. if (this._forcedOutputTexture) {
  49294. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  49295. }
  49296. return this.width / this.height;
  49297. },
  49298. enumerable: true,
  49299. configurable: true
  49300. });
  49301. PostProcess.prototype.apply = function () {
  49302. // Check
  49303. if (!this._effect || !this._effect.isReady())
  49304. return null;
  49305. // States
  49306. this._engine.enableEffect(this._effect);
  49307. this._engine.setState(false);
  49308. this._engine.setDepthBuffer(false);
  49309. this._engine.setDepthWrite(false);
  49310. // Alpha
  49311. this._engine.setAlphaMode(this.alphaMode);
  49312. if (this.alphaConstants) {
  49313. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  49314. }
  49315. // Texture
  49316. var source;
  49317. if (this._shareOutputWithPostProcess) {
  49318. source = this._shareOutputWithPostProcess.outputTexture;
  49319. }
  49320. else if (this._forcedOutputTexture) {
  49321. source = this._forcedOutputTexture;
  49322. }
  49323. else {
  49324. source = this.outputTexture;
  49325. }
  49326. this._effect._bindTexture("textureSampler", source);
  49327. // Parameters
  49328. this._effect.setVector2("scale", this._scaleRatio);
  49329. this.onApplyObservable.notifyObservers(this._effect);
  49330. return this._effect;
  49331. };
  49332. PostProcess.prototype._disposeTextures = function () {
  49333. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  49334. return;
  49335. }
  49336. if (this._textures.length > 0) {
  49337. for (var i = 0; i < this._textures.length; i++) {
  49338. this._engine._releaseTexture(this._textures.data[i]);
  49339. }
  49340. }
  49341. this._textures.dispose();
  49342. };
  49343. PostProcess.prototype.dispose = function (camera) {
  49344. camera = camera || this._camera;
  49345. this._disposeTextures();
  49346. if (this._scene) {
  49347. var index_1 = this._scene.postProcesses.indexOf(this);
  49348. if (index_1 !== -1) {
  49349. this._scene.postProcesses.splice(index_1, 1);
  49350. }
  49351. }
  49352. else {
  49353. var index_2 = this._engine.postProcesses.indexOf(this);
  49354. if (index_2 !== -1) {
  49355. this._engine.postProcesses.splice(index_2, 1);
  49356. }
  49357. }
  49358. if (!camera) {
  49359. return;
  49360. }
  49361. camera.detachPostProcess(this);
  49362. var index = camera._postProcesses.indexOf(this);
  49363. if (index === 0 && camera._postProcesses.length > 0) {
  49364. this._camera._postProcesses[0].markTextureDirty();
  49365. }
  49366. this.onActivateObservable.clear();
  49367. this.onAfterRenderObservable.clear();
  49368. this.onApplyObservable.clear();
  49369. this.onBeforeRenderObservable.clear();
  49370. this.onSizeChangedObservable.clear();
  49371. };
  49372. return PostProcess;
  49373. }());
  49374. BABYLON.PostProcess = PostProcess;
  49375. })(BABYLON || (BABYLON = {}));
  49376. //# sourceMappingURL=babylon.postProcess.js.map
  49377. var BABYLON;
  49378. (function (BABYLON) {
  49379. var PassPostProcess = (function (_super) {
  49380. __extends(PassPostProcess, _super);
  49381. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  49382. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49383. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  49384. }
  49385. return PassPostProcess;
  49386. }(BABYLON.PostProcess));
  49387. BABYLON.PassPostProcess = PassPostProcess;
  49388. })(BABYLON || (BABYLON = {}));
  49389. //# sourceMappingURL=babylon.passPostProcess.js.map
  49390. var BABYLON;
  49391. (function (BABYLON) {
  49392. var ShadowGenerator = (function () {
  49393. /**
  49394. * Creates a ShadowGenerator object.
  49395. * A ShadowGenerator is the required tool to use the shadows.
  49396. * Each light casting shadows needs to use its own ShadowGenerator.
  49397. * Required parameters :
  49398. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  49399. * - `light`: the light object generating the shadows.
  49400. * - `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.
  49401. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  49402. */
  49403. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  49404. // Members
  49405. this._bias = 0.00005;
  49406. this._blurBoxOffset = 1;
  49407. this._blurScale = 2;
  49408. this._blurKernel = 1;
  49409. this._useKernelBlur = false;
  49410. this._filter = ShadowGenerator.FILTER_NONE;
  49411. this._darkness = 0;
  49412. this._transparencyShadow = false;
  49413. /**
  49414. * Controls the extent to which the shadows fade out at the edge of the frustum
  49415. * Used only by directionals and spots
  49416. */
  49417. this.frustumEdgeFalloff = 0;
  49418. this.forceBackFacesOnly = false;
  49419. this._lightDirection = BABYLON.Vector3.Zero();
  49420. this._viewMatrix = BABYLON.Matrix.Zero();
  49421. this._projectionMatrix = BABYLON.Matrix.Zero();
  49422. this._transformMatrix = BABYLON.Matrix.Zero();
  49423. this._currentFaceIndex = 0;
  49424. this._currentFaceIndexCache = 0;
  49425. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  49426. this._mapSize = mapSize;
  49427. this._light = light;
  49428. this._scene = light.getScene();
  49429. light._shadowGenerator = this;
  49430. // Texture type fallback from float to int if not supported.
  49431. var caps = this._scene.getEngine().getCaps();
  49432. if (!useFullFloatFirst) {
  49433. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  49434. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  49435. }
  49436. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  49437. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  49438. }
  49439. else {
  49440. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  49441. }
  49442. }
  49443. else {
  49444. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  49445. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  49446. }
  49447. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  49448. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  49449. }
  49450. else {
  49451. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  49452. }
  49453. }
  49454. this._initializeGenerator();
  49455. }
  49456. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  49457. // Static
  49458. get: function () {
  49459. return ShadowGenerator._FILTER_NONE;
  49460. },
  49461. enumerable: true,
  49462. configurable: true
  49463. });
  49464. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  49465. get: function () {
  49466. return ShadowGenerator._FILTER_POISSONSAMPLING;
  49467. },
  49468. enumerable: true,
  49469. configurable: true
  49470. });
  49471. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  49472. get: function () {
  49473. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  49474. },
  49475. enumerable: true,
  49476. configurable: true
  49477. });
  49478. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  49479. get: function () {
  49480. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  49481. },
  49482. enumerable: true,
  49483. configurable: true
  49484. });
  49485. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  49486. get: function () {
  49487. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  49488. },
  49489. enumerable: true,
  49490. configurable: true
  49491. });
  49492. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  49493. get: function () {
  49494. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  49495. },
  49496. enumerable: true,
  49497. configurable: true
  49498. });
  49499. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  49500. get: function () {
  49501. return this._bias;
  49502. },
  49503. set: function (bias) {
  49504. this._bias = bias;
  49505. },
  49506. enumerable: true,
  49507. configurable: true
  49508. });
  49509. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  49510. get: function () {
  49511. return this._blurBoxOffset;
  49512. },
  49513. set: function (value) {
  49514. if (this._blurBoxOffset === value) {
  49515. return;
  49516. }
  49517. this._blurBoxOffset = value;
  49518. this._disposeBlurPostProcesses();
  49519. },
  49520. enumerable: true,
  49521. configurable: true
  49522. });
  49523. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  49524. get: function () {
  49525. return this._blurScale;
  49526. },
  49527. set: function (value) {
  49528. if (this._blurScale === value) {
  49529. return;
  49530. }
  49531. this._blurScale = value;
  49532. this._disposeBlurPostProcesses();
  49533. },
  49534. enumerable: true,
  49535. configurable: true
  49536. });
  49537. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  49538. get: function () {
  49539. return this._blurKernel;
  49540. },
  49541. set: function (value) {
  49542. if (this._blurKernel === value) {
  49543. return;
  49544. }
  49545. this._blurKernel = value;
  49546. this._disposeBlurPostProcesses();
  49547. },
  49548. enumerable: true,
  49549. configurable: true
  49550. });
  49551. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  49552. get: function () {
  49553. return this._useKernelBlur;
  49554. },
  49555. set: function (value) {
  49556. if (this._useKernelBlur === value) {
  49557. return;
  49558. }
  49559. this._useKernelBlur = value;
  49560. this._disposeBlurPostProcesses();
  49561. },
  49562. enumerable: true,
  49563. configurable: true
  49564. });
  49565. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  49566. get: function () {
  49567. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  49568. },
  49569. set: function (value) {
  49570. this._depthScale = value;
  49571. },
  49572. enumerable: true,
  49573. configurable: true
  49574. });
  49575. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  49576. get: function () {
  49577. return this._filter;
  49578. },
  49579. set: function (value) {
  49580. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  49581. if (this._light.needCube()) {
  49582. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  49583. this.useExponentialShadowMap = true;
  49584. return;
  49585. }
  49586. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  49587. this.useCloseExponentialShadowMap = true;
  49588. return;
  49589. }
  49590. }
  49591. if (this._filter === value) {
  49592. return;
  49593. }
  49594. this._filter = value;
  49595. this._disposeBlurPostProcesses();
  49596. this._applyFilterValues();
  49597. this._light._markMeshesAsLightDirty();
  49598. },
  49599. enumerable: true,
  49600. configurable: true
  49601. });
  49602. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  49603. get: function () {
  49604. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  49605. },
  49606. set: function (value) {
  49607. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  49608. return;
  49609. }
  49610. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  49611. },
  49612. enumerable: true,
  49613. configurable: true
  49614. });
  49615. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  49616. get: function () {
  49617. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  49618. return this.useExponentialShadowMap;
  49619. },
  49620. set: function (value) {
  49621. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  49622. this.useExponentialShadowMap = value;
  49623. },
  49624. enumerable: true,
  49625. configurable: true
  49626. });
  49627. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  49628. get: function () {
  49629. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  49630. return this.useBlurExponentialShadowMap;
  49631. },
  49632. set: function (value) {
  49633. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  49634. this.useBlurExponentialShadowMap = value;
  49635. },
  49636. enumerable: true,
  49637. configurable: true
  49638. });
  49639. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  49640. get: function () {
  49641. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  49642. },
  49643. set: function (value) {
  49644. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  49645. return;
  49646. }
  49647. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  49648. },
  49649. enumerable: true,
  49650. configurable: true
  49651. });
  49652. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  49653. get: function () {
  49654. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  49655. },
  49656. set: function (value) {
  49657. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  49658. return;
  49659. }
  49660. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  49661. },
  49662. enumerable: true,
  49663. configurable: true
  49664. });
  49665. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  49666. get: function () {
  49667. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  49668. },
  49669. set: function (value) {
  49670. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  49671. return;
  49672. }
  49673. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  49674. },
  49675. enumerable: true,
  49676. configurable: true
  49677. });
  49678. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  49679. get: function () {
  49680. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  49681. },
  49682. set: function (value) {
  49683. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  49684. return;
  49685. }
  49686. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  49687. },
  49688. enumerable: true,
  49689. configurable: true
  49690. });
  49691. /**
  49692. * Returns the darkness value (float).
  49693. */
  49694. ShadowGenerator.prototype.getDarkness = function () {
  49695. return this._darkness;
  49696. };
  49697. /**
  49698. * Sets the ShadowGenerator darkness value (float <= 1.0).
  49699. * Returns the ShadowGenerator.
  49700. */
  49701. ShadowGenerator.prototype.setDarkness = function (darkness) {
  49702. if (darkness >= 1.0)
  49703. this._darkness = 1.0;
  49704. else if (darkness <= 0.0)
  49705. this._darkness = 0.0;
  49706. else
  49707. this._darkness = darkness;
  49708. return this;
  49709. };
  49710. /**
  49711. * Sets the ability to have transparent shadow (boolean).
  49712. * Returns the ShadowGenerator.
  49713. */
  49714. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  49715. this._transparencyShadow = hasShadow;
  49716. return this;
  49717. };
  49718. /**
  49719. * Returns a RenderTargetTexture object : the shadow map texture.
  49720. */
  49721. ShadowGenerator.prototype.getShadowMap = function () {
  49722. return this._shadowMap;
  49723. };
  49724. /**
  49725. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  49726. */
  49727. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  49728. if (this._shadowMap2) {
  49729. return this._shadowMap2;
  49730. }
  49731. return this._shadowMap;
  49732. };
  49733. /**
  49734. * Helper function to add a mesh and its descendants to the list of shadow casters
  49735. * @param mesh Mesh to add
  49736. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  49737. */
  49738. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  49739. if (includeDescendants === void 0) { includeDescendants = true; }
  49740. this._shadowMap.renderList.push(mesh);
  49741. if (includeDescendants) {
  49742. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  49743. }
  49744. return this;
  49745. var _a;
  49746. };
  49747. /**
  49748. * Helper function to remove a mesh and its descendants from the list of shadow casters
  49749. * @param mesh Mesh to remove
  49750. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  49751. */
  49752. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  49753. if (includeDescendants === void 0) { includeDescendants = true; }
  49754. var index = this._shadowMap.renderList.indexOf(mesh);
  49755. if (index !== -1) {
  49756. this._shadowMap.renderList.splice(index, 1);
  49757. }
  49758. if (includeDescendants) {
  49759. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  49760. var child = _a[_i];
  49761. this.removeShadowCaster(child);
  49762. }
  49763. }
  49764. return this;
  49765. };
  49766. /**
  49767. * Returns the associated light object.
  49768. */
  49769. ShadowGenerator.prototype.getLight = function () {
  49770. return this._light;
  49771. };
  49772. ShadowGenerator.prototype._initializeGenerator = function () {
  49773. this._light._markMeshesAsLightDirty();
  49774. this._initializeShadowMap();
  49775. };
  49776. ShadowGenerator.prototype._initializeShadowMap = function () {
  49777. var _this = this;
  49778. // Render target
  49779. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  49780. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49781. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49782. this._shadowMap.anisotropicFilteringLevel = 1;
  49783. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49784. this._shadowMap.renderParticles = false;
  49785. this._shadowMap.ignoreCameraViewport = true;
  49786. // Record Face Index before render.
  49787. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  49788. _this._currentFaceIndex = faceIndex;
  49789. });
  49790. // Custom render function.
  49791. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  49792. // Blur if required afer render.
  49793. this._shadowMap.onAfterUnbindObservable.add(function () {
  49794. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  49795. return;
  49796. }
  49797. if (!_this._blurPostProcesses) {
  49798. _this._initializeBlurRTTAndPostProcesses();
  49799. }
  49800. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture(), true);
  49801. });
  49802. // Clear according to the chosen filter.
  49803. this._shadowMap.onClearObservable.add(function (engine) {
  49804. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  49805. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  49806. }
  49807. else {
  49808. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  49809. }
  49810. });
  49811. };
  49812. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  49813. var _this = this;
  49814. var engine = this._scene.getEngine();
  49815. var targetSize = this._mapSize / this.blurScale;
  49816. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  49817. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  49818. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49819. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49820. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49821. }
  49822. if (this.useKernelBlur) {
  49823. 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);
  49824. this._kernelBlurXPostprocess.width = targetSize;
  49825. this._kernelBlurXPostprocess.height = targetSize;
  49826. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  49827. effect.setTexture("textureSampler", _this._shadowMap);
  49828. });
  49829. 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);
  49830. this._kernelBlurXPostprocess.autoClear = false;
  49831. this._kernelBlurYPostprocess.autoClear = false;
  49832. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  49833. this._kernelBlurXPostprocess.packedFloat = true;
  49834. this._kernelBlurYPostprocess.packedFloat = true;
  49835. }
  49836. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  49837. }
  49838. else {
  49839. 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);
  49840. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  49841. effect.setFloat2("screenSize", targetSize, targetSize);
  49842. effect.setTexture("textureSampler", _this._shadowMap);
  49843. });
  49844. this._boxBlurPostprocess.autoClear = false;
  49845. this._blurPostProcesses = [this._boxBlurPostprocess];
  49846. }
  49847. };
  49848. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  49849. var index;
  49850. var engine = this._scene.getEngine();
  49851. if (depthOnlySubMeshes.length) {
  49852. engine.setColorWrite(false);
  49853. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  49854. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  49855. }
  49856. engine.setColorWrite(true);
  49857. }
  49858. for (index = 0; index < opaqueSubMeshes.length; index++) {
  49859. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  49860. }
  49861. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  49862. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  49863. }
  49864. if (this._transparencyShadow) {
  49865. for (index = 0; index < transparentSubMeshes.length; index++) {
  49866. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  49867. }
  49868. }
  49869. };
  49870. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  49871. var _this = this;
  49872. var mesh = subMesh.getRenderingMesh();
  49873. var scene = this._scene;
  49874. var engine = scene.getEngine();
  49875. // Culling
  49876. engine.setState(subMesh.getMaterial().backFaceCulling);
  49877. // Managing instances
  49878. var batch = mesh._getInstancesRenderList(subMesh._id);
  49879. if (batch.mustReturn) {
  49880. return;
  49881. }
  49882. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  49883. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  49884. engine.enableEffect(this._effect);
  49885. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  49886. var material = subMesh.getMaterial();
  49887. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  49888. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  49889. this._effect.setVector3("lightPosition", this.getLight().position);
  49890. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  49891. // Alpha test
  49892. if (material && material.needAlphaTesting()) {
  49893. var alphaTexture = material.getAlphaTestTexture();
  49894. if (alphaTexture) {
  49895. this._effect.setTexture("diffuseSampler", alphaTexture);
  49896. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  49897. }
  49898. }
  49899. // Bones
  49900. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49901. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  49902. }
  49903. if (this.forceBackFacesOnly) {
  49904. engine.setState(true, 0, false, true);
  49905. }
  49906. // Draw
  49907. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  49908. if (this.forceBackFacesOnly) {
  49909. engine.setState(true, 0, false, false);
  49910. }
  49911. }
  49912. else {
  49913. // Need to reset refresh rate of the shadowMap
  49914. this._shadowMap.resetRefreshCounter();
  49915. }
  49916. };
  49917. ShadowGenerator.prototype._applyFilterValues = function () {
  49918. if (this.filter === ShadowGenerator.FILTER_NONE) {
  49919. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  49920. }
  49921. else {
  49922. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49923. }
  49924. };
  49925. /**
  49926. * Force shader compilation including textures ready check
  49927. */
  49928. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  49929. var _this = this;
  49930. var subMeshes = new Array();
  49931. var currentIndex = 0;
  49932. for (var _i = 0, _a = this.getShadowMap().renderList; _i < _a.length; _i++) {
  49933. var mesh = _a[_i];
  49934. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  49935. }
  49936. var checkReady = function () {
  49937. if (!_this._scene || !_this._scene.getEngine()) {
  49938. return;
  49939. }
  49940. var subMesh = subMeshes[currentIndex];
  49941. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  49942. currentIndex++;
  49943. if (currentIndex >= subMeshes.length) {
  49944. if (onCompiled) {
  49945. onCompiled(_this);
  49946. }
  49947. return;
  49948. }
  49949. }
  49950. setTimeout(checkReady, 16);
  49951. };
  49952. if (subMeshes.length > 0) {
  49953. checkReady();
  49954. }
  49955. };
  49956. /**
  49957. * Boolean : true when the ShadowGenerator is finally computed.
  49958. */
  49959. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  49960. var defines = [];
  49961. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  49962. defines.push("#define FLOAT");
  49963. }
  49964. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  49965. defines.push("#define ESM");
  49966. }
  49967. var attribs = [BABYLON.VertexBuffer.PositionKind];
  49968. var mesh = subMesh.getMesh();
  49969. var material = subMesh.getMaterial();
  49970. // Alpha test
  49971. if (material && material.needAlphaTesting()) {
  49972. var alphaTexture = material.getAlphaTestTexture();
  49973. if (alphaTexture) {
  49974. defines.push("#define ALPHATEST");
  49975. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49976. attribs.push(BABYLON.VertexBuffer.UVKind);
  49977. defines.push("#define UV1");
  49978. }
  49979. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  49980. if (alphaTexture.coordinatesIndex === 1) {
  49981. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  49982. defines.push("#define UV2");
  49983. }
  49984. }
  49985. }
  49986. }
  49987. // Bones
  49988. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49989. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  49990. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  49991. if (mesh.numBoneInfluencers > 4) {
  49992. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  49993. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  49994. }
  49995. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  49996. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  49997. }
  49998. else {
  49999. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50000. }
  50001. // Instances
  50002. if (useInstances) {
  50003. defines.push("#define INSTANCES");
  50004. attribs.push("world0");
  50005. attribs.push("world1");
  50006. attribs.push("world2");
  50007. attribs.push("world3");
  50008. }
  50009. // Get correct effect
  50010. var join = defines.join("\n");
  50011. if (this._cachedDefines !== join) {
  50012. this._cachedDefines = join;
  50013. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  50014. }
  50015. return this._effect.isReady();
  50016. };
  50017. /**
  50018. * This creates the defines related to the standard BJS materials.
  50019. */
  50020. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  50021. var scene = this._scene;
  50022. var light = this._light;
  50023. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  50024. return;
  50025. }
  50026. defines["SHADOW" + lightIndex] = true;
  50027. if (this.usePoissonSampling) {
  50028. defines["SHADOWPCF" + lightIndex] = true;
  50029. }
  50030. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  50031. defines["SHADOWESM" + lightIndex] = true;
  50032. }
  50033. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  50034. defines["SHADOWCLOSEESM" + lightIndex] = true;
  50035. }
  50036. if (light.needCube()) {
  50037. defines["SHADOWCUBE" + lightIndex] = true;
  50038. }
  50039. };
  50040. /**
  50041. * This binds shadow lights related to the standard BJS materials.
  50042. * It implies the unifroms available on the materials are the standard BJS ones.
  50043. */
  50044. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  50045. var light = this._light;
  50046. var scene = this._scene;
  50047. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  50048. return;
  50049. }
  50050. if (!light.needCube()) {
  50051. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  50052. }
  50053. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  50054. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  50055. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  50056. };
  50057. // Methods
  50058. /**
  50059. * Returns a Matrix object : the updated transformation matrix.
  50060. */
  50061. ShadowGenerator.prototype.getTransformMatrix = function () {
  50062. var scene = this._scene;
  50063. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  50064. return this._transformMatrix;
  50065. }
  50066. this._currentRenderID = scene.getRenderId();
  50067. this._currentFaceIndexCache = this._currentFaceIndex;
  50068. var lightPosition = this._light.position;
  50069. if (this._light.computeTransformedInformation()) {
  50070. lightPosition = this._light.transformedPosition;
  50071. }
  50072. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  50073. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  50074. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  50075. }
  50076. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  50077. this._cachedPosition = lightPosition.clone();
  50078. this._cachedDirection = this._lightDirection.clone();
  50079. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  50080. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  50081. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  50082. }
  50083. return this._transformMatrix;
  50084. };
  50085. ShadowGenerator.prototype.recreateShadowMap = function () {
  50086. // Track render list.
  50087. var renderList = this._shadowMap.renderList;
  50088. // Clean up existing data.
  50089. this._disposeRTTandPostProcesses();
  50090. // Reinitializes.
  50091. this._initializeGenerator();
  50092. // Reaffect the filter to ensure a correct fallback if necessary.
  50093. this.filter = this.filter;
  50094. // Reaffect the filter.
  50095. this._applyFilterValues();
  50096. // Reaffect Render List.
  50097. this._shadowMap.renderList = renderList;
  50098. };
  50099. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  50100. if (this._shadowMap2) {
  50101. this._shadowMap2.dispose();
  50102. this._shadowMap2 = null;
  50103. }
  50104. if (this._downSamplePostprocess) {
  50105. this._downSamplePostprocess.dispose();
  50106. this._downSamplePostprocess = null;
  50107. }
  50108. if (this._boxBlurPostprocess) {
  50109. this._boxBlurPostprocess.dispose();
  50110. this._boxBlurPostprocess = null;
  50111. }
  50112. if (this._kernelBlurXPostprocess) {
  50113. this._kernelBlurXPostprocess.dispose();
  50114. this._kernelBlurXPostprocess = null;
  50115. }
  50116. if (this._kernelBlurYPostprocess) {
  50117. this._kernelBlurYPostprocess.dispose();
  50118. this._kernelBlurYPostprocess = null;
  50119. }
  50120. this._blurPostProcesses = null;
  50121. };
  50122. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  50123. if (this._shadowMap) {
  50124. this._shadowMap.dispose();
  50125. this._shadowMap = null;
  50126. }
  50127. this._disposeBlurPostProcesses();
  50128. };
  50129. /**
  50130. * Disposes the ShadowGenerator.
  50131. * Returns nothing.
  50132. */
  50133. ShadowGenerator.prototype.dispose = function () {
  50134. this._disposeRTTandPostProcesses();
  50135. this._light._shadowGenerator = null;
  50136. this._light._markMeshesAsLightDirty();
  50137. };
  50138. /**
  50139. * Serializes the ShadowGenerator and returns a serializationObject.
  50140. */
  50141. ShadowGenerator.prototype.serialize = function () {
  50142. var serializationObject = {};
  50143. var shadowMap = this.getShadowMap();
  50144. serializationObject.lightId = this._light.id;
  50145. serializationObject.mapSize = shadowMap.getRenderSize();
  50146. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  50147. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  50148. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  50149. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  50150. serializationObject.usePoissonSampling = this.usePoissonSampling;
  50151. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  50152. serializationObject.depthScale = this.depthScale;
  50153. serializationObject.darkness = this.getDarkness();
  50154. serializationObject.blurBoxOffset = this.blurBoxOffset;
  50155. serializationObject.blurKernel = this.blurKernel;
  50156. serializationObject.blurScale = this.blurScale;
  50157. serializationObject.useKernelBlur = this.useKernelBlur;
  50158. serializationObject.transparencyShadow = this._transparencyShadow;
  50159. serializationObject.renderList = [];
  50160. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  50161. var mesh = shadowMap.renderList[meshIndex];
  50162. serializationObject.renderList.push(mesh.id);
  50163. }
  50164. return serializationObject;
  50165. };
  50166. /**
  50167. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  50168. */
  50169. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  50170. //casting to point light, as light is missing the position attr and typescript complains.
  50171. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  50172. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  50173. var shadowMap = shadowGenerator.getShadowMap();
  50174. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  50175. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  50176. meshes.forEach(function (mesh) {
  50177. shadowMap.renderList.push(mesh);
  50178. });
  50179. }
  50180. if (parsedShadowGenerator.usePoissonSampling) {
  50181. shadowGenerator.usePoissonSampling = true;
  50182. }
  50183. else if (parsedShadowGenerator.useExponentialShadowMap) {
  50184. shadowGenerator.useExponentialShadowMap = true;
  50185. }
  50186. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  50187. shadowGenerator.useBlurExponentialShadowMap = true;
  50188. }
  50189. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  50190. shadowGenerator.useCloseExponentialShadowMap = true;
  50191. }
  50192. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  50193. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  50194. }
  50195. else if (parsedShadowGenerator.useVarianceShadowMap) {
  50196. shadowGenerator.useExponentialShadowMap = true;
  50197. }
  50198. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  50199. shadowGenerator.useBlurExponentialShadowMap = true;
  50200. }
  50201. if (parsedShadowGenerator.depthScale) {
  50202. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  50203. }
  50204. if (parsedShadowGenerator.blurScale) {
  50205. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  50206. }
  50207. if (parsedShadowGenerator.blurBoxOffset) {
  50208. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  50209. }
  50210. if (parsedShadowGenerator.useKernelBlur) {
  50211. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  50212. }
  50213. if (parsedShadowGenerator.blurKernel) {
  50214. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  50215. }
  50216. if (parsedShadowGenerator.bias !== undefined) {
  50217. shadowGenerator.bias = parsedShadowGenerator.bias;
  50218. }
  50219. if (parsedShadowGenerator.darkness) {
  50220. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  50221. }
  50222. if (parsedShadowGenerator.transparencyShadow) {
  50223. shadowGenerator.setTransparencyShadow(true);
  50224. }
  50225. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  50226. return shadowGenerator;
  50227. };
  50228. ShadowGenerator._FILTER_NONE = 0;
  50229. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  50230. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  50231. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  50232. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  50233. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  50234. return ShadowGenerator;
  50235. }());
  50236. BABYLON.ShadowGenerator = ShadowGenerator;
  50237. })(BABYLON || (BABYLON = {}));
  50238. //# sourceMappingURL=babylon.shadowGenerator.js.map
  50239. var BABYLON;
  50240. (function (BABYLON) {
  50241. var DefaultLoadingScreen = (function () {
  50242. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  50243. if (_loadingText === void 0) { _loadingText = ""; }
  50244. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  50245. var _this = this;
  50246. this._renderingCanvas = _renderingCanvas;
  50247. this._loadingText = _loadingText;
  50248. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  50249. // Resize
  50250. this._resizeLoadingUI = function () {
  50251. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  50252. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  50253. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  50254. _this._loadingDiv.style.left = canvasRect.left + "px";
  50255. _this._loadingDiv.style.top = canvasRect.top + "px";
  50256. _this._loadingDiv.style.width = canvasRect.width + "px";
  50257. _this._loadingDiv.style.height = canvasRect.height + "px";
  50258. };
  50259. }
  50260. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  50261. if (this._loadingDiv) {
  50262. // Do not add a loading screen if there is already one
  50263. return;
  50264. }
  50265. this._loadingDiv = document.createElement("div");
  50266. this._loadingDiv.id = "babylonjsLoadingDiv";
  50267. this._loadingDiv.style.opacity = "0";
  50268. this._loadingDiv.style.transition = "opacity 1.5s ease";
  50269. this._loadingDiv.style.pointerEvents = "none";
  50270. // Loading text
  50271. this._loadingTextDiv = document.createElement("div");
  50272. this._loadingTextDiv.style.position = "absolute";
  50273. this._loadingTextDiv.style.left = "0";
  50274. this._loadingTextDiv.style.top = "50%";
  50275. this._loadingTextDiv.style.marginTop = "80px";
  50276. this._loadingTextDiv.style.width = "100%";
  50277. this._loadingTextDiv.style.height = "20px";
  50278. this._loadingTextDiv.style.fontFamily = "Arial";
  50279. this._loadingTextDiv.style.fontSize = "14px";
  50280. this._loadingTextDiv.style.color = "white";
  50281. this._loadingTextDiv.style.textAlign = "center";
  50282. this._loadingTextDiv.innerHTML = "Loading";
  50283. this._loadingDiv.appendChild(this._loadingTextDiv);
  50284. //set the predefined text
  50285. this._loadingTextDiv.innerHTML = this._loadingText;
  50286. // Generating keyframes
  50287. var style = document.createElement('style');
  50288. style.type = 'text/css';
  50289. 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 }";
  50290. style.innerHTML = keyFrames;
  50291. document.getElementsByTagName('head')[0].appendChild(style);
  50292. // Loading img
  50293. var imgBack = new Image();
  50294. 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";
  50295. imgBack.style.position = "absolute";
  50296. imgBack.style.left = "50%";
  50297. imgBack.style.top = "50%";
  50298. imgBack.style.marginLeft = "-60px";
  50299. imgBack.style.marginTop = "-60px";
  50300. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  50301. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  50302. imgBack.style.transformOrigin = "50% 50%";
  50303. imgBack.style.webkitTransformOrigin = "50% 50%";
  50304. this._loadingDiv.appendChild(imgBack);
  50305. this._resizeLoadingUI();
  50306. window.addEventListener("resize", this._resizeLoadingUI);
  50307. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  50308. document.body.appendChild(this._loadingDiv);
  50309. this._loadingDiv.style.opacity = "1";
  50310. };
  50311. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  50312. var _this = this;
  50313. if (!this._loadingDiv) {
  50314. return;
  50315. }
  50316. var onTransitionEnd = function () {
  50317. if (!_this._loadingDiv) {
  50318. return;
  50319. }
  50320. document.body.removeChild(_this._loadingDiv);
  50321. window.removeEventListener("resize", _this._resizeLoadingUI);
  50322. _this._loadingDiv = null;
  50323. };
  50324. this._loadingDiv.style.opacity = "0";
  50325. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  50326. };
  50327. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  50328. set: function (text) {
  50329. this._loadingText = text;
  50330. if (this._loadingTextDiv) {
  50331. this._loadingTextDiv.innerHTML = this._loadingText;
  50332. }
  50333. },
  50334. enumerable: true,
  50335. configurable: true
  50336. });
  50337. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  50338. get: function () {
  50339. return this._loadingDivBackgroundColor;
  50340. },
  50341. set: function (color) {
  50342. this._loadingDivBackgroundColor = color;
  50343. if (!this._loadingDiv) {
  50344. return;
  50345. }
  50346. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  50347. },
  50348. enumerable: true,
  50349. configurable: true
  50350. });
  50351. return DefaultLoadingScreen;
  50352. }());
  50353. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  50354. })(BABYLON || (BABYLON = {}));
  50355. //# sourceMappingURL=babylon.loadingScreen.js.map
  50356. var BABYLON;
  50357. (function (BABYLON) {
  50358. var SceneLoader = (function () {
  50359. function SceneLoader() {
  50360. }
  50361. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  50362. get: function () {
  50363. return 0;
  50364. },
  50365. enumerable: true,
  50366. configurable: true
  50367. });
  50368. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  50369. get: function () {
  50370. return 1;
  50371. },
  50372. enumerable: true,
  50373. configurable: true
  50374. });
  50375. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  50376. get: function () {
  50377. return 2;
  50378. },
  50379. enumerable: true,
  50380. configurable: true
  50381. });
  50382. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  50383. get: function () {
  50384. return 3;
  50385. },
  50386. enumerable: true,
  50387. configurable: true
  50388. });
  50389. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  50390. get: function () {
  50391. return SceneLoader._ForceFullSceneLoadingForIncremental;
  50392. },
  50393. set: function (value) {
  50394. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  50395. },
  50396. enumerable: true,
  50397. configurable: true
  50398. });
  50399. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  50400. get: function () {
  50401. return SceneLoader._ShowLoadingScreen;
  50402. },
  50403. set: function (value) {
  50404. SceneLoader._ShowLoadingScreen = value;
  50405. },
  50406. enumerable: true,
  50407. configurable: true
  50408. });
  50409. Object.defineProperty(SceneLoader, "loggingLevel", {
  50410. get: function () {
  50411. return SceneLoader._loggingLevel;
  50412. },
  50413. set: function (value) {
  50414. SceneLoader._loggingLevel = value;
  50415. },
  50416. enumerable: true,
  50417. configurable: true
  50418. });
  50419. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  50420. get: function () {
  50421. return SceneLoader._CleanBoneMatrixWeights;
  50422. },
  50423. set: function (value) {
  50424. SceneLoader._CleanBoneMatrixWeights = value;
  50425. },
  50426. enumerable: true,
  50427. configurable: true
  50428. });
  50429. SceneLoader._getDefaultPlugin = function () {
  50430. return SceneLoader._registeredPlugins[".babylon"];
  50431. };
  50432. SceneLoader._getPluginForExtension = function (extension) {
  50433. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  50434. if (registeredPlugin) {
  50435. return registeredPlugin;
  50436. }
  50437. return SceneLoader._getDefaultPlugin();
  50438. };
  50439. SceneLoader._getPluginForDirectLoad = function (data) {
  50440. for (var extension in SceneLoader._registeredPlugins) {
  50441. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  50442. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  50443. return SceneLoader._registeredPlugins[extension];
  50444. }
  50445. }
  50446. return SceneLoader._getDefaultPlugin();
  50447. };
  50448. SceneLoader._getPluginForFilename = function (sceneFilename) {
  50449. if (sceneFilename.name) {
  50450. sceneFilename = sceneFilename.name;
  50451. }
  50452. var dotPosition = sceneFilename.lastIndexOf(".");
  50453. var queryStringPosition = sceneFilename.indexOf("?");
  50454. if (queryStringPosition === -1) {
  50455. queryStringPosition = sceneFilename.length;
  50456. }
  50457. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  50458. return SceneLoader._getPluginForExtension(extension);
  50459. };
  50460. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  50461. SceneLoader._getDirectLoad = function (sceneFilename) {
  50462. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  50463. return sceneFilename.substr(5);
  50464. }
  50465. return null;
  50466. };
  50467. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  50468. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  50469. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  50470. var plugin = registeredPlugin.plugin;
  50471. var useArrayBuffer = registeredPlugin.isBinary;
  50472. var database;
  50473. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  50474. var dataCallback = function (data) {
  50475. if (scene.isDisposed) {
  50476. onError("Scene has been disposed");
  50477. return;
  50478. }
  50479. scene.database = database;
  50480. try {
  50481. onSuccess(plugin, data);
  50482. }
  50483. catch (e) {
  50484. onError(null, e);
  50485. }
  50486. };
  50487. var manifestChecked = function (success) {
  50488. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  50489. onError(request.status + " " + request.statusText);
  50490. });
  50491. };
  50492. if (directLoad) {
  50493. dataCallback(directLoad);
  50494. return;
  50495. }
  50496. if (rootUrl.indexOf("file:") === -1) {
  50497. if (scene.getEngine().enableOfflineSupport) {
  50498. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  50499. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  50500. }
  50501. else {
  50502. manifestChecked(true);
  50503. }
  50504. }
  50505. else {
  50506. var fileOrString = sceneFilename;
  50507. if (fileOrString.name) {
  50508. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  50509. }
  50510. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  50511. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  50512. }
  50513. else {
  50514. onError("Unable to find file named " + sceneFilename);
  50515. return;
  50516. }
  50517. }
  50518. };
  50519. // Public functions
  50520. SceneLoader.GetPluginForExtension = function (extension) {
  50521. return SceneLoader._getPluginForExtension(extension).plugin;
  50522. };
  50523. SceneLoader.RegisterPlugin = function (plugin) {
  50524. if (typeof plugin.extensions === "string") {
  50525. var extension = plugin.extensions;
  50526. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  50527. plugin: plugin,
  50528. isBinary: false
  50529. };
  50530. }
  50531. else {
  50532. var extensions = plugin.extensions;
  50533. Object.keys(extensions).forEach(function (extension) {
  50534. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  50535. plugin: plugin,
  50536. isBinary: extensions[extension].isBinary
  50537. };
  50538. });
  50539. }
  50540. };
  50541. /**
  50542. * Import meshes into a scene
  50543. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  50544. * @param rootUrl a string that defines the root url for scene and resources
  50545. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  50546. * @param scene the instance of BABYLON.Scene to append to
  50547. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  50548. * @param onProgress a callback with a progress event for each file being loaded
  50549. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  50550. */
  50551. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  50552. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  50553. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  50554. return;
  50555. }
  50556. var loadingToken = {};
  50557. scene._addPendingData(loadingToken);
  50558. var errorHandler = function (message, exception) {
  50559. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  50560. if (onError) {
  50561. onError(scene, errorMessage, exception);
  50562. }
  50563. else {
  50564. BABYLON.Tools.Error(errorMessage);
  50565. // should the exception be thrown?
  50566. }
  50567. scene._removePendingData(loadingToken);
  50568. };
  50569. var progressHandler = function (event) {
  50570. if (onProgress) {
  50571. onProgress(event);
  50572. }
  50573. };
  50574. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  50575. if (plugin.importMesh) {
  50576. var syncedPlugin = plugin;
  50577. var meshes = new Array();
  50578. var particleSystems = new Array();
  50579. var skeletons = new Array();
  50580. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  50581. return;
  50582. }
  50583. if (onSuccess) {
  50584. // wrap onSuccess with try-catch to know if something went wrong.
  50585. try {
  50586. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  50587. onSuccess(meshes, particleSystems, skeletons);
  50588. scene._removePendingData(loadingToken);
  50589. }
  50590. catch (e) {
  50591. var message = 'Error in onSuccess callback.';
  50592. errorHandler(message, e);
  50593. }
  50594. }
  50595. }
  50596. else {
  50597. var asyncedPlugin = plugin;
  50598. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  50599. if (onSuccess) {
  50600. try {
  50601. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  50602. onSuccess(meshes, particleSystems, skeletons);
  50603. scene._removePendingData(loadingToken);
  50604. }
  50605. catch (e) {
  50606. var message = 'Error in onSuccess callback.';
  50607. errorHandler(message, e);
  50608. }
  50609. }
  50610. }, progressHandler, errorHandler);
  50611. }
  50612. }, progressHandler, errorHandler);
  50613. };
  50614. /**
  50615. * Load a scene
  50616. * @param rootUrl a string that defines the root url for scene and resources
  50617. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  50618. * @param engine is the instance of BABYLON.Engine to use to create the scene
  50619. * @param onSuccess a callback with the scene when import succeeds
  50620. * @param onProgress a callback with a progress event for each file being loaded
  50621. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  50622. */
  50623. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  50624. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  50625. };
  50626. /**
  50627. * Append a scene
  50628. * @param rootUrl a string that defines the root url for scene and resources
  50629. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  50630. * @param scene is the instance of BABYLON.Scene to append to
  50631. * @param onSuccess a callback with the scene when import succeeds
  50632. * @param onProgress a callback with a progress event for each file being loaded
  50633. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  50634. */
  50635. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  50636. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  50637. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  50638. return;
  50639. }
  50640. if (SceneLoader.ShowLoadingScreen) {
  50641. scene.getEngine().displayLoadingUI();
  50642. }
  50643. var loadingToken = {};
  50644. scene._addPendingData(loadingToken);
  50645. var errorHandler = function (message, exception) {
  50646. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  50647. if (onError) {
  50648. onError(scene, errorMessage, exception);
  50649. }
  50650. else {
  50651. BABYLON.Tools.Error(errorMessage);
  50652. // should the exception be thrown?
  50653. }
  50654. scene._removePendingData(loadingToken);
  50655. scene.getEngine().hideLoadingUI();
  50656. };
  50657. var progressHandler = function (event) {
  50658. if (onProgress) {
  50659. onProgress(event);
  50660. }
  50661. };
  50662. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  50663. if (plugin.load) {
  50664. var syncedPlugin = plugin;
  50665. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  50666. return;
  50667. }
  50668. if (onSuccess) {
  50669. try {
  50670. onSuccess(scene);
  50671. }
  50672. catch (e) {
  50673. errorHandler("Error in onSuccess callback", e);
  50674. }
  50675. }
  50676. scene.loadingPluginName = plugin.name;
  50677. scene._removePendingData(loadingToken);
  50678. }
  50679. else {
  50680. var asyncedPlugin = plugin;
  50681. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  50682. if (onSuccess) {
  50683. onSuccess(scene);
  50684. }
  50685. scene.loadingPluginName = plugin.name;
  50686. scene._removePendingData(loadingToken);
  50687. }, progressHandler, errorHandler);
  50688. }
  50689. if (SceneLoader.ShowLoadingScreen) {
  50690. scene.executeWhenReady(function () {
  50691. scene.getEngine().hideLoadingUI();
  50692. });
  50693. }
  50694. }, progressHandler, errorHandler);
  50695. };
  50696. // Flags
  50697. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  50698. SceneLoader._ShowLoadingScreen = true;
  50699. SceneLoader._CleanBoneMatrixWeights = false;
  50700. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  50701. // Members
  50702. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  50703. SceneLoader._registeredPlugins = {};
  50704. return SceneLoader;
  50705. }());
  50706. BABYLON.SceneLoader = SceneLoader;
  50707. ;
  50708. })(BABYLON || (BABYLON = {}));
  50709. //# sourceMappingURL=babylon.sceneLoader.js.map
  50710. var BABYLON;
  50711. (function (BABYLON) {
  50712. var Internals;
  50713. (function (Internals) {
  50714. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  50715. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  50716. var parsedMaterial = parsedData.materials[index];
  50717. if (parsedMaterial.id === id) {
  50718. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  50719. }
  50720. }
  50721. return null;
  50722. };
  50723. var isDescendantOf = function (mesh, names, hierarchyIds) {
  50724. for (var i in names) {
  50725. if (mesh.name === names[i]) {
  50726. hierarchyIds.push(mesh.id);
  50727. return true;
  50728. }
  50729. }
  50730. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  50731. hierarchyIds.push(mesh.id);
  50732. return true;
  50733. }
  50734. return false;
  50735. };
  50736. var logOperation = function (operation, producer) {
  50737. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  50738. };
  50739. BABYLON.SceneLoader.RegisterPlugin({
  50740. name: "babylon.js",
  50741. extensions: ".babylon",
  50742. canDirectLoad: function (data) {
  50743. if (data.indexOf("babylon") !== -1) {
  50744. return true;
  50745. }
  50746. return false;
  50747. },
  50748. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  50749. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  50750. // when SceneLoader.debugLogging = true (default), or exception encountered.
  50751. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  50752. // and avoid problems with multiple concurrent .babylon loads.
  50753. var log = "importMesh has failed JSON parse";
  50754. try {
  50755. var parsedData = JSON.parse(data);
  50756. log = "";
  50757. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  50758. if (!meshesNames) {
  50759. meshesNames = null;
  50760. }
  50761. else if (!Array.isArray(meshesNames)) {
  50762. meshesNames = [meshesNames];
  50763. }
  50764. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  50765. var loadedSkeletonsIds = [];
  50766. var loadedMaterialsIds = [];
  50767. var hierarchyIds = new Array();
  50768. var index;
  50769. var cache;
  50770. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  50771. var parsedMesh = parsedData.meshes[index];
  50772. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  50773. if (meshesNames !== null) {
  50774. // Remove found mesh name from list.
  50775. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  50776. }
  50777. //Geometry?
  50778. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  50779. //does the file contain geometries?
  50780. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  50781. //find the correct geometry and add it to the scene
  50782. var found = false;
  50783. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  50784. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  50785. return;
  50786. }
  50787. else {
  50788. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  50789. if (parsedGeometryData.id === parsedMesh.geometryId) {
  50790. switch (geometryType) {
  50791. case "boxes":
  50792. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  50793. break;
  50794. case "spheres":
  50795. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  50796. break;
  50797. case "cylinders":
  50798. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  50799. break;
  50800. case "toruses":
  50801. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  50802. break;
  50803. case "grounds":
  50804. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  50805. break;
  50806. case "planes":
  50807. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  50808. break;
  50809. case "torusKnots":
  50810. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  50811. break;
  50812. case "vertexData":
  50813. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  50814. break;
  50815. }
  50816. found = true;
  50817. }
  50818. });
  50819. }
  50820. });
  50821. if (found === false) {
  50822. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  50823. }
  50824. }
  50825. }
  50826. // Material ?
  50827. if (parsedMesh.materialId) {
  50828. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  50829. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  50830. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  50831. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  50832. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  50833. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  50834. var subMatId = parsedMultiMaterial.materials[matIndex];
  50835. loadedMaterialsIds.push(subMatId);
  50836. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  50837. log += "\n\tMaterial " + mat.toString(fullDetails);
  50838. }
  50839. loadedMaterialsIds.push(parsedMultiMaterial.id);
  50840. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  50841. materialFound = true;
  50842. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  50843. break;
  50844. }
  50845. }
  50846. }
  50847. if (materialFound === false) {
  50848. loadedMaterialsIds.push(parsedMesh.materialId);
  50849. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  50850. if (!mat) {
  50851. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  50852. }
  50853. else {
  50854. log += "\n\tMaterial " + mat.toString(fullDetails);
  50855. }
  50856. }
  50857. }
  50858. // Skeleton ?
  50859. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  50860. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  50861. if (skeletonAlreadyLoaded === false) {
  50862. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  50863. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  50864. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  50865. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  50866. skeletons.push(skeleton);
  50867. loadedSkeletonsIds.push(parsedSkeleton.id);
  50868. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  50869. }
  50870. }
  50871. }
  50872. }
  50873. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  50874. meshes.push(mesh);
  50875. log += "\n\tMesh " + mesh.toString(fullDetails);
  50876. }
  50877. }
  50878. // Connecting parents
  50879. var currentMesh;
  50880. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  50881. currentMesh = scene.meshes[index];
  50882. if (currentMesh._waitingParentId) {
  50883. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  50884. currentMesh._waitingParentId = undefined;
  50885. }
  50886. }
  50887. // freeze and compute world matrix application
  50888. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  50889. currentMesh = scene.meshes[index];
  50890. if (currentMesh._waitingFreezeWorldMatrix) {
  50891. currentMesh.freezeWorldMatrix();
  50892. currentMesh._waitingFreezeWorldMatrix = undefined;
  50893. }
  50894. else {
  50895. currentMesh.computeWorldMatrix(true);
  50896. }
  50897. }
  50898. }
  50899. // Particles
  50900. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  50901. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  50902. var parsedParticleSystem = parsedData.particleSystems[index];
  50903. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  50904. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  50905. }
  50906. }
  50907. }
  50908. return true;
  50909. }
  50910. catch (err) {
  50911. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  50912. if (onError) {
  50913. onError(msg, err);
  50914. }
  50915. else {
  50916. BABYLON.Tools.Log(msg);
  50917. log = null;
  50918. throw err;
  50919. }
  50920. }
  50921. finally {
  50922. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  50923. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  50924. }
  50925. }
  50926. return false;
  50927. },
  50928. load: function (scene, data, rootUrl, onError) {
  50929. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  50930. // when SceneLoader.debugLogging = true (default), or exception encountered.
  50931. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  50932. // and avoid problems with multiple concurrent .babylon loads.
  50933. var log = "importScene has failed JSON parse";
  50934. try {
  50935. var parsedData = JSON.parse(data);
  50936. log = "";
  50937. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  50938. // Scene
  50939. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  50940. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  50941. }
  50942. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  50943. scene.autoClear = parsedData.autoClear;
  50944. }
  50945. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  50946. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  50947. }
  50948. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  50949. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  50950. }
  50951. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  50952. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  50953. }
  50954. // Fog
  50955. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  50956. scene.fogMode = parsedData.fogMode;
  50957. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  50958. scene.fogStart = parsedData.fogStart;
  50959. scene.fogEnd = parsedData.fogEnd;
  50960. scene.fogDensity = parsedData.fogDensity;
  50961. log += "\tFog mode for scene: ";
  50962. switch (scene.fogMode) {
  50963. // getters not compiling, so using hardcoded
  50964. case 1:
  50965. log += "exp\n";
  50966. break;
  50967. case 2:
  50968. log += "exp2\n";
  50969. break;
  50970. case 3:
  50971. log += "linear\n";
  50972. break;
  50973. }
  50974. }
  50975. //Physics
  50976. if (parsedData.physicsEnabled) {
  50977. var physicsPlugin;
  50978. if (parsedData.physicsEngine === "cannon") {
  50979. physicsPlugin = new BABYLON.CannonJSPlugin();
  50980. }
  50981. else if (parsedData.physicsEngine === "oimo") {
  50982. physicsPlugin = new BABYLON.OimoJSPlugin();
  50983. }
  50984. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  50985. //else - default engine, which is currently oimo
  50986. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  50987. scene.enablePhysics(physicsGravity, physicsPlugin);
  50988. }
  50989. // Metadata
  50990. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  50991. scene.metadata = parsedData.metadata;
  50992. }
  50993. //collisions, if defined. otherwise, default is true
  50994. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  50995. scene.collisionsEnabled = parsedData.collisionsEnabled;
  50996. }
  50997. scene.workerCollisions = !!parsedData.workerCollisions;
  50998. var index;
  50999. var cache;
  51000. // Lights
  51001. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  51002. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  51003. var parsedLight = parsedData.lights[index];
  51004. var light = BABYLON.Light.Parse(parsedLight, scene);
  51005. log += (index === 0 ? "\n\tLights:" : "");
  51006. log += "\n\t\t" + light.toString(fullDetails);
  51007. }
  51008. }
  51009. // Animations
  51010. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  51011. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  51012. var parsedAnimation = parsedData.animations[index];
  51013. var animation = BABYLON.Animation.Parse(parsedAnimation);
  51014. scene.animations.push(animation);
  51015. log += (index === 0 ? "\n\tAnimations:" : "");
  51016. log += "\n\t\t" + animation.toString(fullDetails);
  51017. }
  51018. }
  51019. if (parsedData.autoAnimate) {
  51020. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  51021. }
  51022. // Materials
  51023. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  51024. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  51025. var parsedMaterial = parsedData.materials[index];
  51026. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  51027. log += (index === 0 ? "\n\tMaterials:" : "");
  51028. log += "\n\t\t" + mat.toString(fullDetails);
  51029. }
  51030. }
  51031. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  51032. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  51033. var parsedMultiMaterial = parsedData.multiMaterials[index];
  51034. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  51035. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  51036. log += "\n\t\t" + mmat.toString(fullDetails);
  51037. }
  51038. }
  51039. // Morph targets
  51040. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  51041. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  51042. var managerData = _a[_i];
  51043. BABYLON.MorphTargetManager.Parse(managerData, scene);
  51044. }
  51045. }
  51046. // Skeletons
  51047. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  51048. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  51049. var parsedSkeleton = parsedData.skeletons[index];
  51050. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  51051. log += (index === 0 ? "\n\tSkeletons:" : "");
  51052. log += "\n\t\t" + skeleton.toString(fullDetails);
  51053. }
  51054. }
  51055. // Geometries
  51056. var geometries = parsedData.geometries;
  51057. if (geometries !== undefined && geometries !== null) {
  51058. // Boxes
  51059. var boxes = geometries.boxes;
  51060. if (boxes !== undefined && boxes !== null) {
  51061. for (index = 0, cache = boxes.length; index < cache; index++) {
  51062. var parsedBox = boxes[index];
  51063. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  51064. }
  51065. }
  51066. // Spheres
  51067. var spheres = geometries.spheres;
  51068. if (spheres !== undefined && spheres !== null) {
  51069. for (index = 0, cache = spheres.length; index < cache; index++) {
  51070. var parsedSphere = spheres[index];
  51071. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  51072. }
  51073. }
  51074. // Cylinders
  51075. var cylinders = geometries.cylinders;
  51076. if (cylinders !== undefined && cylinders !== null) {
  51077. for (index = 0, cache = cylinders.length; index < cache; index++) {
  51078. var parsedCylinder = cylinders[index];
  51079. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  51080. }
  51081. }
  51082. // Toruses
  51083. var toruses = geometries.toruses;
  51084. if (toruses !== undefined && toruses !== null) {
  51085. for (index = 0, cache = toruses.length; index < cache; index++) {
  51086. var parsedTorus = toruses[index];
  51087. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  51088. }
  51089. }
  51090. // Grounds
  51091. var grounds = geometries.grounds;
  51092. if (grounds !== undefined && grounds !== null) {
  51093. for (index = 0, cache = grounds.length; index < cache; index++) {
  51094. var parsedGround = grounds[index];
  51095. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  51096. }
  51097. }
  51098. // Planes
  51099. var planes = geometries.planes;
  51100. if (planes !== undefined && planes !== null) {
  51101. for (index = 0, cache = planes.length; index < cache; index++) {
  51102. var parsedPlane = planes[index];
  51103. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  51104. }
  51105. }
  51106. // TorusKnots
  51107. var torusKnots = geometries.torusKnots;
  51108. if (torusKnots !== undefined && torusKnots !== null) {
  51109. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  51110. var parsedTorusKnot = torusKnots[index];
  51111. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  51112. }
  51113. }
  51114. // VertexData
  51115. var vertexData = geometries.vertexData;
  51116. if (vertexData !== undefined && vertexData !== null) {
  51117. for (index = 0, cache = vertexData.length; index < cache; index++) {
  51118. var parsedVertexData = vertexData[index];
  51119. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  51120. }
  51121. }
  51122. }
  51123. // Meshes
  51124. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  51125. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  51126. var parsedMesh = parsedData.meshes[index];
  51127. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  51128. log += (index === 0 ? "\n\tMeshes:" : "");
  51129. log += "\n\t\t" + mesh.toString(fullDetails);
  51130. }
  51131. }
  51132. // Cameras
  51133. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  51134. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  51135. var parsedCamera = parsedData.cameras[index];
  51136. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  51137. log += (index === 0 ? "\n\tCameras:" : "");
  51138. log += "\n\t\t" + camera.toString(fullDetails);
  51139. }
  51140. }
  51141. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  51142. scene.setActiveCameraByID(parsedData.activeCameraID);
  51143. }
  51144. // Browsing all the graph to connect the dots
  51145. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  51146. var camera = scene.cameras[index];
  51147. if (camera._waitingParentId) {
  51148. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  51149. camera._waitingParentId = undefined;
  51150. }
  51151. }
  51152. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  51153. var light = scene.lights[index];
  51154. if (light._waitingParentId) {
  51155. light.parent = scene.getLastEntryByID(light._waitingParentId);
  51156. light._waitingParentId = undefined;
  51157. }
  51158. }
  51159. // Sounds
  51160. var loadedSounds = [];
  51161. var loadedSound;
  51162. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  51163. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  51164. var parsedSound = parsedData.sounds[index];
  51165. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51166. if (!parsedSound.url)
  51167. parsedSound.url = parsedSound.name;
  51168. if (!loadedSounds[parsedSound.url]) {
  51169. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  51170. loadedSounds[parsedSound.url] = loadedSound;
  51171. }
  51172. else {
  51173. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  51174. }
  51175. }
  51176. else {
  51177. new BABYLON.Sound(parsedSound.name, null, scene);
  51178. }
  51179. }
  51180. }
  51181. loadedSounds = [];
  51182. // Connect parents & children and parse actions
  51183. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  51184. var mesh = scene.meshes[index];
  51185. if (mesh._waitingParentId) {
  51186. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  51187. mesh._waitingParentId = undefined;
  51188. }
  51189. if (mesh._waitingActions) {
  51190. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  51191. mesh._waitingActions = undefined;
  51192. }
  51193. }
  51194. // freeze world matrix application
  51195. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  51196. var currentMesh = scene.meshes[index];
  51197. if (currentMesh._waitingFreezeWorldMatrix) {
  51198. currentMesh.freezeWorldMatrix();
  51199. currentMesh._waitingFreezeWorldMatrix = undefined;
  51200. }
  51201. else {
  51202. currentMesh.computeWorldMatrix(true);
  51203. }
  51204. }
  51205. // Particles Systems
  51206. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  51207. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  51208. var parsedParticleSystem = parsedData.particleSystems[index];
  51209. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  51210. }
  51211. }
  51212. // Lens flares
  51213. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  51214. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  51215. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  51216. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  51217. }
  51218. }
  51219. // Shadows
  51220. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  51221. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  51222. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  51223. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  51224. }
  51225. }
  51226. // Lights exclusions / inclusions
  51227. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  51228. var light = scene.lights[index];
  51229. // Excluded check
  51230. if (light._excludedMeshesIds.length > 0) {
  51231. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  51232. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  51233. if (excludedMesh) {
  51234. light.excludedMeshes.push(excludedMesh);
  51235. }
  51236. }
  51237. light._excludedMeshesIds = [];
  51238. }
  51239. // Included check
  51240. if (light._includedOnlyMeshesIds.length > 0) {
  51241. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  51242. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  51243. if (includedOnlyMesh) {
  51244. light.includedOnlyMeshes.push(includedOnlyMesh);
  51245. }
  51246. }
  51247. light._includedOnlyMeshesIds = [];
  51248. }
  51249. }
  51250. // Actions (scene)
  51251. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  51252. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  51253. }
  51254. // Finish
  51255. return true;
  51256. }
  51257. catch (err) {
  51258. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  51259. if (onError) {
  51260. onError(msg, err);
  51261. }
  51262. else {
  51263. BABYLON.Tools.Log(msg);
  51264. log = null;
  51265. throw err;
  51266. }
  51267. }
  51268. finally {
  51269. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  51270. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  51271. }
  51272. }
  51273. return false;
  51274. }
  51275. });
  51276. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51277. })(BABYLON || (BABYLON = {}));
  51278. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  51279. var BABYLON;
  51280. (function (BABYLON) {
  51281. var FilesInput = (function () {
  51282. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  51283. this.onProcessFileCallback = function () { return true; };
  51284. this._engine = engine;
  51285. this._currentScene = scene;
  51286. this._sceneLoadedCallback = sceneLoadedCallback;
  51287. this._progressCallback = progressCallback;
  51288. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  51289. this._textureLoadingCallback = textureLoadingCallback;
  51290. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  51291. this._onReloadCallback = onReloadCallback;
  51292. this._errorCallback = errorCallback;
  51293. }
  51294. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  51295. var _this = this;
  51296. if (elementToMonitor) {
  51297. this._elementToMonitor = elementToMonitor;
  51298. this._dragEnterHandler = function (e) { _this.drag(e); };
  51299. this._dragOverHandler = function (e) { _this.drag(e); };
  51300. this._dropHandler = function (e) { _this.drop(e); };
  51301. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  51302. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  51303. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  51304. }
  51305. };
  51306. FilesInput.prototype.dispose = function () {
  51307. if (!this._elementToMonitor) {
  51308. return;
  51309. }
  51310. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  51311. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  51312. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  51313. };
  51314. FilesInput.prototype.renderFunction = function () {
  51315. if (this._additionalRenderLoopLogicCallback) {
  51316. this._additionalRenderLoopLogicCallback();
  51317. }
  51318. if (this._currentScene) {
  51319. if (this._textureLoadingCallback) {
  51320. var remaining = this._currentScene.getWaitingItemsCount();
  51321. if (remaining > 0) {
  51322. this._textureLoadingCallback(remaining);
  51323. }
  51324. }
  51325. this._currentScene.render();
  51326. }
  51327. };
  51328. FilesInput.prototype.drag = function (e) {
  51329. e.stopPropagation();
  51330. e.preventDefault();
  51331. };
  51332. FilesInput.prototype.drop = function (eventDrop) {
  51333. eventDrop.stopPropagation();
  51334. eventDrop.preventDefault();
  51335. this.loadFiles(eventDrop);
  51336. };
  51337. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  51338. var _this = this;
  51339. var reader = folder.createReader();
  51340. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  51341. reader.readEntries(function (entries) {
  51342. remaining.count += entries.length;
  51343. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  51344. var entry = entries_1[_i];
  51345. if (entry.isFile) {
  51346. entry.file(function (file) {
  51347. file.correctName = relativePath + file.name;
  51348. files.push(file);
  51349. if (--remaining.count === 0) {
  51350. callback();
  51351. }
  51352. });
  51353. }
  51354. else if (entry.isDirectory) {
  51355. _this._traverseFolder(entry, files, remaining, callback);
  51356. }
  51357. }
  51358. if (--remaining.count) {
  51359. callback();
  51360. }
  51361. });
  51362. };
  51363. FilesInput.prototype._processFiles = function (files) {
  51364. var skippedFiles = 0;
  51365. for (var i = 0; i < files.length; i++) {
  51366. var name = files[i].correctName.toLowerCase();
  51367. var extension = name.split('.').pop();
  51368. if (!this.onProcessFileCallback(files[i], name, extension)) {
  51369. skippedFiles++;
  51370. continue;
  51371. }
  51372. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  51373. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  51374. this._sceneFileToLoad = files[i];
  51375. }
  51376. else {
  51377. FilesInput.FilesToLoad[name] = files[i];
  51378. }
  51379. }
  51380. if (this._onReloadCallback) {
  51381. this._onReloadCallback(this._sceneFileToLoad);
  51382. }
  51383. else if (skippedFiles < files.length) {
  51384. this.reload();
  51385. }
  51386. };
  51387. FilesInput.prototype.loadFiles = function (event) {
  51388. var _this = this;
  51389. if (this._startingProcessingFilesCallback)
  51390. this._startingProcessingFilesCallback();
  51391. // Handling data transfer via drag'n'drop
  51392. if (event && event.dataTransfer && event.dataTransfer.files) {
  51393. this._filesToLoad = event.dataTransfer.files;
  51394. }
  51395. // Handling files from input files
  51396. if (event && event.target && event.target.files) {
  51397. this._filesToLoad = event.target.files;
  51398. }
  51399. if (this._filesToLoad && this._filesToLoad.length > 0) {
  51400. var files_1 = new Array();
  51401. var folders = [];
  51402. var items = event.dataTransfer ? event.dataTransfer.items : null;
  51403. for (var i = 0; i < this._filesToLoad.length; i++) {
  51404. var fileToLoad = this._filesToLoad[i];
  51405. var name_1 = fileToLoad.name.toLowerCase();
  51406. var entry = void 0;
  51407. fileToLoad.correctName = name_1;
  51408. if (items) {
  51409. var item = items[i];
  51410. if (item.getAsEntry) {
  51411. entry = item.getAsEntry();
  51412. }
  51413. else if (item.webkitGetAsEntry) {
  51414. entry = item.webkitGetAsEntry();
  51415. }
  51416. }
  51417. if (!entry) {
  51418. files_1.push(fileToLoad);
  51419. }
  51420. else {
  51421. if (entry.isDirectory) {
  51422. folders.push(entry);
  51423. }
  51424. else {
  51425. files_1.push(fileToLoad);
  51426. }
  51427. }
  51428. }
  51429. if (folders.length === 0) {
  51430. this._processFiles(files_1);
  51431. }
  51432. else {
  51433. var remaining = { count: folders.length };
  51434. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  51435. var folder = folders_1[_i];
  51436. this._traverseFolder(folder, files_1, remaining, function () {
  51437. _this._processFiles(files_1);
  51438. });
  51439. }
  51440. }
  51441. }
  51442. };
  51443. FilesInput.prototype.reload = function () {
  51444. var _this = this;
  51445. // If a ".babylon" file has been provided
  51446. if (this._sceneFileToLoad) {
  51447. if (this._currentScene) {
  51448. if (BABYLON.Tools.errorsCount > 0) {
  51449. BABYLON.Tools.ClearLogCache();
  51450. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  51451. }
  51452. this._engine.stopRenderLoop();
  51453. this._currentScene.dispose();
  51454. }
  51455. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  51456. _this._currentScene = newScene;
  51457. if (_this._sceneLoadedCallback) {
  51458. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  51459. }
  51460. // Wait for textures and shaders to be ready
  51461. _this._currentScene.executeWhenReady(function () {
  51462. _this._engine.runRenderLoop(function () {
  51463. _this.renderFunction();
  51464. });
  51465. });
  51466. }, function (progress) {
  51467. if (_this._progressCallback) {
  51468. _this._progressCallback(progress);
  51469. }
  51470. }, function (scene, message) {
  51471. _this._currentScene = scene;
  51472. if (_this._errorCallback) {
  51473. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  51474. }
  51475. });
  51476. }
  51477. else {
  51478. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  51479. }
  51480. };
  51481. FilesInput.FilesToLoad = {};
  51482. return FilesInput;
  51483. }());
  51484. BABYLON.FilesInput = FilesInput;
  51485. })(BABYLON || (BABYLON = {}));
  51486. //# sourceMappingURL=babylon.filesInput.js.map
  51487. var BABYLON;
  51488. (function (BABYLON) {
  51489. /**
  51490. * This class implement a typical dictionary using a string as key and the generic type T as value.
  51491. * The underlying implementation relies on an associative array to ensure the best performances.
  51492. * The value can be anything including 'null' but except 'undefined'
  51493. */
  51494. var StringDictionary = (function () {
  51495. function StringDictionary() {
  51496. this._count = 0;
  51497. this._data = {};
  51498. }
  51499. /**
  51500. * This will clear this dictionary and copy the content from the 'source' one.
  51501. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  51502. * @param source the dictionary to take the content from and copy to this dictionary
  51503. */
  51504. StringDictionary.prototype.copyFrom = function (source) {
  51505. var _this = this;
  51506. this.clear();
  51507. source.forEach(function (t, v) { return _this.add(t, v); });
  51508. };
  51509. /**
  51510. * Get a value based from its key
  51511. * @param key the given key to get the matching value from
  51512. * @return the value if found, otherwise undefined is returned
  51513. */
  51514. StringDictionary.prototype.get = function (key) {
  51515. var val = this._data[key];
  51516. if (val !== undefined) {
  51517. return val;
  51518. }
  51519. return undefined;
  51520. };
  51521. /**
  51522. * Get a value from its key or add it if it doesn't exist.
  51523. * This method will ensure you that a given key/data will be present in the dictionary.
  51524. * @param key the given key to get the matching value from
  51525. * @param factory the factory that will create the value if the key is not present in the dictionary.
  51526. * The factory will only be invoked if there's no data for the given key.
  51527. * @return the value corresponding to the key.
  51528. */
  51529. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  51530. var val = this.get(key);
  51531. if (val !== undefined) {
  51532. return val;
  51533. }
  51534. val = factory(key);
  51535. if (val) {
  51536. this.add(key, val);
  51537. }
  51538. return val;
  51539. };
  51540. /**
  51541. * Get a value from its key if present in the dictionary otherwise add it
  51542. * @param key the key to get the value from
  51543. * @param val if there's no such key/value pair in the dictionary add it with this value
  51544. * @return the value corresponding to the key
  51545. */
  51546. StringDictionary.prototype.getOrAdd = function (key, val) {
  51547. var curVal = this.get(key);
  51548. if (curVal !== undefined) {
  51549. return curVal;
  51550. }
  51551. this.add(key, val);
  51552. return val;
  51553. };
  51554. /**
  51555. * Check if there's a given key in the dictionary
  51556. * @param key the key to check for
  51557. * @return true if the key is present, false otherwise
  51558. */
  51559. StringDictionary.prototype.contains = function (key) {
  51560. return this._data[key] !== undefined;
  51561. };
  51562. /**
  51563. * Add a new key and its corresponding value
  51564. * @param key the key to add
  51565. * @param value the value corresponding to the key
  51566. * @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
  51567. */
  51568. StringDictionary.prototype.add = function (key, value) {
  51569. if (this._data[key] !== undefined) {
  51570. return false;
  51571. }
  51572. this._data[key] = value;
  51573. ++this._count;
  51574. return true;
  51575. };
  51576. StringDictionary.prototype.set = function (key, value) {
  51577. if (this._data[key] === undefined) {
  51578. return false;
  51579. }
  51580. this._data[key] = value;
  51581. return true;
  51582. };
  51583. /**
  51584. * Get the element of the given key and remove it from the dictionary
  51585. * @param key
  51586. */
  51587. StringDictionary.prototype.getAndRemove = function (key) {
  51588. var val = this.get(key);
  51589. if (val !== undefined) {
  51590. delete this._data[key];
  51591. --this._count;
  51592. return val;
  51593. }
  51594. return null;
  51595. };
  51596. /**
  51597. * Remove a key/value from the dictionary.
  51598. * @param key the key to remove
  51599. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  51600. */
  51601. StringDictionary.prototype.remove = function (key) {
  51602. if (this.contains(key)) {
  51603. delete this._data[key];
  51604. --this._count;
  51605. return true;
  51606. }
  51607. return false;
  51608. };
  51609. /**
  51610. * Clear the whole content of the dictionary
  51611. */
  51612. StringDictionary.prototype.clear = function () {
  51613. this._data = {};
  51614. this._count = 0;
  51615. };
  51616. Object.defineProperty(StringDictionary.prototype, "count", {
  51617. get: function () {
  51618. return this._count;
  51619. },
  51620. enumerable: true,
  51621. configurable: true
  51622. });
  51623. /**
  51624. * Execute a callback on each key/val of the dictionary.
  51625. * Note that you can remove any element in this dictionary in the callback implementation
  51626. * @param callback the callback to execute on a given key/value pair
  51627. */
  51628. StringDictionary.prototype.forEach = function (callback) {
  51629. for (var cur in this._data) {
  51630. var val = this._data[cur];
  51631. callback(cur, val);
  51632. }
  51633. };
  51634. /**
  51635. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  51636. * If the callback returns null or undefined the method will iterate to the next key/value pair
  51637. * Note that you can remove any element in this dictionary in the callback implementation
  51638. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  51639. */
  51640. StringDictionary.prototype.first = function (callback) {
  51641. for (var cur in this._data) {
  51642. var val = this._data[cur];
  51643. var res = callback(cur, val);
  51644. if (res) {
  51645. return res;
  51646. }
  51647. }
  51648. return null;
  51649. };
  51650. return StringDictionary;
  51651. }());
  51652. BABYLON.StringDictionary = StringDictionary;
  51653. })(BABYLON || (BABYLON = {}));
  51654. //# sourceMappingURL=babylon.stringDictionary.js.map
  51655. var BABYLON;
  51656. (function (BABYLON) {
  51657. var Tags = (function () {
  51658. function Tags() {
  51659. }
  51660. Tags.EnableFor = function (obj) {
  51661. obj._tags = obj._tags || {};
  51662. obj.hasTags = function () {
  51663. return Tags.HasTags(obj);
  51664. };
  51665. obj.addTags = function (tagsString) {
  51666. return Tags.AddTagsTo(obj, tagsString);
  51667. };
  51668. obj.removeTags = function (tagsString) {
  51669. return Tags.RemoveTagsFrom(obj, tagsString);
  51670. };
  51671. obj.matchesTagsQuery = function (tagsQuery) {
  51672. return Tags.MatchesQuery(obj, tagsQuery);
  51673. };
  51674. };
  51675. Tags.DisableFor = function (obj) {
  51676. delete obj._tags;
  51677. delete obj.hasTags;
  51678. delete obj.addTags;
  51679. delete obj.removeTags;
  51680. delete obj.matchesTagsQuery;
  51681. };
  51682. Tags.HasTags = function (obj) {
  51683. if (!obj._tags) {
  51684. return false;
  51685. }
  51686. return !BABYLON.Tools.IsEmpty(obj._tags);
  51687. };
  51688. Tags.GetTags = function (obj, asString) {
  51689. if (asString === void 0) { asString = true; }
  51690. if (!obj._tags) {
  51691. return null;
  51692. }
  51693. if (asString) {
  51694. var tagsArray = [];
  51695. for (var tag in obj._tags) {
  51696. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  51697. tagsArray.push(tag);
  51698. }
  51699. }
  51700. return tagsArray.join(" ");
  51701. }
  51702. else {
  51703. return obj._tags;
  51704. }
  51705. };
  51706. // the tags 'true' and 'false' are reserved and cannot be used as tags
  51707. // a tag cannot start with '||', '&&', and '!'
  51708. // it cannot contain whitespaces
  51709. Tags.AddTagsTo = function (obj, tagsString) {
  51710. if (!tagsString) {
  51711. return;
  51712. }
  51713. if (typeof tagsString !== "string") {
  51714. return;
  51715. }
  51716. var tags = tagsString.split(" ");
  51717. tags.forEach(function (tag, index, array) {
  51718. Tags._AddTagTo(obj, tag);
  51719. });
  51720. };
  51721. Tags._AddTagTo = function (obj, tag) {
  51722. tag = tag.trim();
  51723. if (tag === "" || tag === "true" || tag === "false") {
  51724. return;
  51725. }
  51726. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  51727. return;
  51728. }
  51729. Tags.EnableFor(obj);
  51730. obj._tags[tag] = true;
  51731. };
  51732. Tags.RemoveTagsFrom = function (obj, tagsString) {
  51733. if (!Tags.HasTags(obj)) {
  51734. return;
  51735. }
  51736. var tags = tagsString.split(" ");
  51737. for (var t in tags) {
  51738. Tags._RemoveTagFrom(obj, tags[t]);
  51739. }
  51740. };
  51741. Tags._RemoveTagFrom = function (obj, tag) {
  51742. delete obj._tags[tag];
  51743. };
  51744. Tags.MatchesQuery = function (obj, tagsQuery) {
  51745. if (tagsQuery === undefined) {
  51746. return true;
  51747. }
  51748. if (tagsQuery === "") {
  51749. return Tags.HasTags(obj);
  51750. }
  51751. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  51752. };
  51753. return Tags;
  51754. }());
  51755. BABYLON.Tags = Tags;
  51756. })(BABYLON || (BABYLON = {}));
  51757. //# sourceMappingURL=babylon.tags.js.map
  51758. var BABYLON;
  51759. (function (BABYLON) {
  51760. var Internals;
  51761. (function (Internals) {
  51762. var AndOrNotEvaluator = (function () {
  51763. function AndOrNotEvaluator() {
  51764. }
  51765. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  51766. if (!query.match(/\([^\(\)]*\)/g)) {
  51767. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  51768. }
  51769. else {
  51770. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  51771. // remove parenthesis
  51772. r = r.slice(1, r.length - 1);
  51773. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  51774. });
  51775. }
  51776. if (query === "true") {
  51777. return true;
  51778. }
  51779. if (query === "false") {
  51780. return false;
  51781. }
  51782. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  51783. };
  51784. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  51785. evaluateCallback = evaluateCallback || (function (r) {
  51786. return r === "true" ? true : false;
  51787. });
  51788. var result;
  51789. var or = parenthesisContent.split("||");
  51790. for (var i in or) {
  51791. if (or.hasOwnProperty(i)) {
  51792. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  51793. var and = ori.split("&&");
  51794. if (and.length > 1) {
  51795. for (var j = 0; j < and.length; ++j) {
  51796. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  51797. if (andj !== "true" && andj !== "false") {
  51798. if (andj[0] === "!") {
  51799. result = !evaluateCallback(andj.substring(1));
  51800. }
  51801. else {
  51802. result = evaluateCallback(andj);
  51803. }
  51804. }
  51805. else {
  51806. result = andj === "true" ? true : false;
  51807. }
  51808. if (!result) {
  51809. ori = "false";
  51810. break;
  51811. }
  51812. }
  51813. }
  51814. if (result || ori === "true") {
  51815. result = true;
  51816. break;
  51817. }
  51818. // result equals false (or undefined)
  51819. if (ori !== "true" && ori !== "false") {
  51820. if (ori[0] === "!") {
  51821. result = !evaluateCallback(ori.substring(1));
  51822. }
  51823. else {
  51824. result = evaluateCallback(ori);
  51825. }
  51826. }
  51827. else {
  51828. result = ori === "true" ? true : false;
  51829. }
  51830. }
  51831. }
  51832. // the whole parenthesis scope is replaced by 'true' or 'false'
  51833. return result ? "true" : "false";
  51834. };
  51835. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  51836. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  51837. // remove whitespaces
  51838. r = r.replace(/[\s]/g, function () { return ""; });
  51839. return r.length % 2 ? "!" : "";
  51840. });
  51841. booleanString = booleanString.trim();
  51842. if (booleanString === "!true") {
  51843. booleanString = "false";
  51844. }
  51845. else if (booleanString === "!false") {
  51846. booleanString = "true";
  51847. }
  51848. return booleanString;
  51849. };
  51850. return AndOrNotEvaluator;
  51851. }());
  51852. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  51853. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51854. })(BABYLON || (BABYLON = {}));
  51855. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  51856. var BABYLON;
  51857. (function (BABYLON) {
  51858. var Database = (function () {
  51859. function Database(urlToScene, callbackManifestChecked) {
  51860. // Handling various flavors of prefixed version of IndexedDB
  51861. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  51862. this.callbackManifestChecked = callbackManifestChecked;
  51863. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  51864. this.db = null;
  51865. this._enableSceneOffline = false;
  51866. this._enableTexturesOffline = false;
  51867. this.manifestVersionFound = 0;
  51868. this.mustUpdateRessources = false;
  51869. this.hasReachedQuota = false;
  51870. if (!Database.IDBStorageEnabled) {
  51871. this.callbackManifestChecked(true);
  51872. }
  51873. else {
  51874. this.checkManifestFile();
  51875. }
  51876. }
  51877. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  51878. get: function () {
  51879. return this._enableSceneOffline;
  51880. },
  51881. enumerable: true,
  51882. configurable: true
  51883. });
  51884. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  51885. get: function () {
  51886. return this._enableTexturesOffline;
  51887. },
  51888. enumerable: true,
  51889. configurable: true
  51890. });
  51891. Database.prototype.checkManifestFile = function () {
  51892. var _this = this;
  51893. var noManifestFile = function () {
  51894. _this._enableSceneOffline = false;
  51895. _this._enableTexturesOffline = false;
  51896. _this.callbackManifestChecked(false);
  51897. };
  51898. var timeStampUsed = false;
  51899. var manifestURL = this.currentSceneUrl + ".manifest";
  51900. var xhr = new XMLHttpRequest();
  51901. if (navigator.onLine) {
  51902. // Adding a timestamp to by-pass browsers' cache
  51903. timeStampUsed = true;
  51904. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  51905. }
  51906. xhr.open("GET", manifestURL, true);
  51907. xhr.addEventListener("load", function () {
  51908. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  51909. try {
  51910. var manifestFile = JSON.parse(xhr.response);
  51911. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  51912. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  51913. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  51914. _this.manifestVersionFound = manifestFile.version;
  51915. }
  51916. if (_this.callbackManifestChecked) {
  51917. _this.callbackManifestChecked(true);
  51918. }
  51919. }
  51920. catch (ex) {
  51921. noManifestFile();
  51922. }
  51923. }
  51924. else {
  51925. noManifestFile();
  51926. }
  51927. }, false);
  51928. xhr.addEventListener("error", function (event) {
  51929. if (timeStampUsed) {
  51930. timeStampUsed = false;
  51931. // Let's retry without the timeStamp
  51932. // It could fail when coupled with HTML5 Offline API
  51933. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  51934. xhr.open("GET", retryManifestURL, true);
  51935. xhr.send();
  51936. }
  51937. else {
  51938. noManifestFile();
  51939. }
  51940. }, false);
  51941. try {
  51942. xhr.send();
  51943. }
  51944. catch (ex) {
  51945. BABYLON.Tools.Error("Error on XHR send request.");
  51946. this.callbackManifestChecked(false);
  51947. }
  51948. };
  51949. Database.prototype.openAsync = function (successCallback, errorCallback) {
  51950. var _this = this;
  51951. function handleError() {
  51952. that.isSupported = false;
  51953. if (errorCallback)
  51954. errorCallback();
  51955. }
  51956. var that = this;
  51957. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  51958. // Your browser doesn't support IndexedDB
  51959. this.isSupported = false;
  51960. if (errorCallback)
  51961. errorCallback();
  51962. }
  51963. else {
  51964. // If the DB hasn't been opened or created yet
  51965. if (!this.db) {
  51966. this.hasReachedQuota = false;
  51967. this.isSupported = true;
  51968. var request = this.idbFactory.open("babylonjs", 1);
  51969. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  51970. request.onerror = function (event) {
  51971. handleError();
  51972. };
  51973. // executes when a version change transaction cannot complete due to other active transactions
  51974. request.onblocked = function (event) {
  51975. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  51976. handleError();
  51977. };
  51978. // DB has been opened successfully
  51979. request.onsuccess = function (event) {
  51980. _this.db = request.result;
  51981. successCallback();
  51982. };
  51983. // Initialization of the DB. Creating Scenes & Textures stores
  51984. request.onupgradeneeded = function (event) {
  51985. _this.db = (event.target).result;
  51986. try {
  51987. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  51988. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  51989. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  51990. }
  51991. catch (ex) {
  51992. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  51993. handleError();
  51994. }
  51995. };
  51996. }
  51997. else {
  51998. if (successCallback)
  51999. successCallback();
  52000. }
  52001. }
  52002. };
  52003. Database.prototype.loadImageFromDB = function (url, image) {
  52004. var _this = this;
  52005. var completeURL = Database.ReturnFullUrlLocation(url);
  52006. var saveAndLoadImage = function () {
  52007. if (!_this.hasReachedQuota && _this.db !== null) {
  52008. // the texture is not yet in the DB, let's try to save it
  52009. _this._saveImageIntoDBAsync(completeURL, image);
  52010. }
  52011. else {
  52012. image.src = url;
  52013. }
  52014. };
  52015. if (!this.mustUpdateRessources) {
  52016. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  52017. }
  52018. else {
  52019. saveAndLoadImage();
  52020. }
  52021. };
  52022. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  52023. if (this.isSupported && this.db !== null) {
  52024. var texture;
  52025. var transaction = this.db.transaction(["textures"]);
  52026. transaction.onabort = function (event) {
  52027. image.src = url;
  52028. };
  52029. transaction.oncomplete = function (event) {
  52030. var blobTextureURL;
  52031. if (texture) {
  52032. var URL = window.URL || window.webkitURL;
  52033. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  52034. image.onerror = function () {
  52035. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  52036. image.src = url;
  52037. };
  52038. image.src = blobTextureURL;
  52039. }
  52040. else {
  52041. notInDBCallback();
  52042. }
  52043. };
  52044. var getRequest = transaction.objectStore("textures").get(url);
  52045. getRequest.onsuccess = function (event) {
  52046. texture = (event.target).result;
  52047. };
  52048. getRequest.onerror = function (event) {
  52049. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  52050. image.src = url;
  52051. };
  52052. }
  52053. else {
  52054. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  52055. image.src = url;
  52056. }
  52057. };
  52058. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  52059. var _this = this;
  52060. if (this.isSupported) {
  52061. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  52062. var generateBlobUrl = function () {
  52063. var blobTextureURL;
  52064. if (blob) {
  52065. var URL = window.URL || window.webkitURL;
  52066. try {
  52067. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  52068. }
  52069. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  52070. catch (ex) {
  52071. blobTextureURL = URL.createObjectURL(blob);
  52072. }
  52073. }
  52074. image.src = blobTextureURL;
  52075. };
  52076. if (Database.IsUASupportingBlobStorage) {
  52077. var xhr = new XMLHttpRequest(), blob;
  52078. xhr.open("GET", url, true);
  52079. xhr.responseType = "blob";
  52080. xhr.addEventListener("load", function () {
  52081. if (xhr.status === 200) {
  52082. // Blob as response (XHR2)
  52083. blob = xhr.response;
  52084. var transaction = _this.db.transaction(["textures"], "readwrite");
  52085. // the transaction could abort because of a QuotaExceededError error
  52086. transaction.onabort = function (event) {
  52087. try {
  52088. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  52089. var error = event.srcElement['error'];
  52090. if (error && error.name === "QuotaExceededError") {
  52091. _this.hasReachedQuota = true;
  52092. }
  52093. }
  52094. catch (ex) { }
  52095. generateBlobUrl();
  52096. };
  52097. transaction.oncomplete = function (event) {
  52098. generateBlobUrl();
  52099. };
  52100. var newTexture = { textureUrl: url, data: blob };
  52101. try {
  52102. // Put the blob into the dabase
  52103. var addRequest = transaction.objectStore("textures").put(newTexture);
  52104. addRequest.onsuccess = function (event) {
  52105. };
  52106. addRequest.onerror = function (event) {
  52107. generateBlobUrl();
  52108. };
  52109. }
  52110. catch (ex) {
  52111. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  52112. if (ex.code === 25) {
  52113. Database.IsUASupportingBlobStorage = false;
  52114. }
  52115. image.src = url;
  52116. }
  52117. }
  52118. else {
  52119. image.src = url;
  52120. }
  52121. }, false);
  52122. xhr.addEventListener("error", function (event) {
  52123. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  52124. image.src = url;
  52125. }, false);
  52126. xhr.send();
  52127. }
  52128. else {
  52129. image.src = url;
  52130. }
  52131. }
  52132. else {
  52133. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  52134. image.src = url;
  52135. }
  52136. };
  52137. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  52138. var _this = this;
  52139. var updateVersion = function () {
  52140. // the version is not yet in the DB or we need to update it
  52141. _this._saveVersionIntoDBAsync(url, versionLoaded);
  52142. };
  52143. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  52144. };
  52145. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  52146. var _this = this;
  52147. if (this.isSupported) {
  52148. var version;
  52149. try {
  52150. var transaction = this.db.transaction(["versions"]);
  52151. transaction.oncomplete = function (event) {
  52152. if (version) {
  52153. // If the version in the JSON file is > than the version in DB
  52154. if (_this.manifestVersionFound > version.data) {
  52155. _this.mustUpdateRessources = true;
  52156. updateInDBCallback();
  52157. }
  52158. else {
  52159. callback(version.data);
  52160. }
  52161. }
  52162. else {
  52163. _this.mustUpdateRessources = true;
  52164. updateInDBCallback();
  52165. }
  52166. };
  52167. transaction.onabort = function (event) {
  52168. callback(-1);
  52169. };
  52170. var getRequest = transaction.objectStore("versions").get(url);
  52171. getRequest.onsuccess = function (event) {
  52172. version = (event.target).result;
  52173. };
  52174. getRequest.onerror = function (event) {
  52175. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  52176. callback(-1);
  52177. };
  52178. }
  52179. catch (ex) {
  52180. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  52181. callback(-1);
  52182. }
  52183. }
  52184. else {
  52185. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  52186. callback(-1);
  52187. }
  52188. };
  52189. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  52190. var _this = this;
  52191. if (this.isSupported && !this.hasReachedQuota) {
  52192. try {
  52193. // Open a transaction to the database
  52194. var transaction = this.db.transaction(["versions"], "readwrite");
  52195. // the transaction could abort because of a QuotaExceededError error
  52196. transaction.onabort = function (event) {
  52197. try {
  52198. var error = event.srcElement['error'];
  52199. if (error && error.name === "QuotaExceededError") {
  52200. _this.hasReachedQuota = true;
  52201. }
  52202. }
  52203. catch (ex) { }
  52204. callback(-1);
  52205. };
  52206. transaction.oncomplete = function (event) {
  52207. callback(_this.manifestVersionFound);
  52208. };
  52209. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  52210. // Put the scene into the database
  52211. var addRequest = transaction.objectStore("versions").put(newVersion);
  52212. addRequest.onsuccess = function (event) {
  52213. };
  52214. addRequest.onerror = function (event) {
  52215. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  52216. };
  52217. }
  52218. catch (ex) {
  52219. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  52220. callback(-1);
  52221. }
  52222. }
  52223. else {
  52224. callback(-1);
  52225. }
  52226. };
  52227. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  52228. var _this = this;
  52229. var completeUrl = Database.ReturnFullUrlLocation(url);
  52230. var saveAndLoadFile = function () {
  52231. // the scene is not yet in the DB, let's try to save it
  52232. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  52233. };
  52234. this._checkVersionFromDB(completeUrl, function (version) {
  52235. if (version !== -1) {
  52236. if (!_this.mustUpdateRessources) {
  52237. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  52238. }
  52239. else {
  52240. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  52241. }
  52242. }
  52243. else {
  52244. errorCallback();
  52245. }
  52246. });
  52247. };
  52248. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  52249. if (this.isSupported) {
  52250. var targetStore;
  52251. if (url.indexOf(".babylon") !== -1) {
  52252. targetStore = "scenes";
  52253. }
  52254. else {
  52255. targetStore = "textures";
  52256. }
  52257. var file;
  52258. var transaction = this.db.transaction([targetStore]);
  52259. transaction.oncomplete = function (event) {
  52260. if (file) {
  52261. callback(file.data);
  52262. }
  52263. else {
  52264. notInDBCallback();
  52265. }
  52266. };
  52267. transaction.onabort = function (event) {
  52268. notInDBCallback();
  52269. };
  52270. var getRequest = transaction.objectStore(targetStore).get(url);
  52271. getRequest.onsuccess = function (event) {
  52272. file = (event.target).result;
  52273. };
  52274. getRequest.onerror = function (event) {
  52275. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  52276. notInDBCallback();
  52277. };
  52278. }
  52279. else {
  52280. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  52281. callback();
  52282. }
  52283. };
  52284. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  52285. var _this = this;
  52286. if (this.isSupported) {
  52287. var targetStore;
  52288. if (url.indexOf(".babylon") !== -1) {
  52289. targetStore = "scenes";
  52290. }
  52291. else {
  52292. targetStore = "textures";
  52293. }
  52294. // Create XHR
  52295. var xhr = new XMLHttpRequest();
  52296. var fileData;
  52297. xhr.open("GET", url, true);
  52298. if (useArrayBuffer) {
  52299. xhr.responseType = "arraybuffer";
  52300. }
  52301. xhr.onprogress = progressCallback;
  52302. xhr.addEventListener("load", function () {
  52303. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  52304. // Blob as response (XHR2)
  52305. //fileData = xhr.responseText;
  52306. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  52307. if (!_this.hasReachedQuota) {
  52308. // Open a transaction to the database
  52309. var transaction = _this.db.transaction([targetStore], "readwrite");
  52310. // the transaction could abort because of a QuotaExceededError error
  52311. transaction.onabort = function (event) {
  52312. try {
  52313. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  52314. var error = event.srcElement['error'];
  52315. if (error && error.name === "QuotaExceededError") {
  52316. _this.hasReachedQuota = true;
  52317. }
  52318. }
  52319. catch (ex) { }
  52320. callback(fileData);
  52321. };
  52322. transaction.oncomplete = function (event) {
  52323. callback(fileData);
  52324. };
  52325. var newFile;
  52326. if (targetStore === "scenes") {
  52327. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  52328. }
  52329. else {
  52330. newFile = { textureUrl: url, data: fileData };
  52331. }
  52332. try {
  52333. // Put the scene into the database
  52334. var addRequest = transaction.objectStore(targetStore).put(newFile);
  52335. addRequest.onsuccess = function (event) {
  52336. };
  52337. addRequest.onerror = function (event) {
  52338. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  52339. };
  52340. }
  52341. catch (ex) {
  52342. callback(fileData);
  52343. }
  52344. }
  52345. else {
  52346. callback(fileData);
  52347. }
  52348. }
  52349. else {
  52350. callback();
  52351. }
  52352. }, false);
  52353. xhr.addEventListener("error", function (event) {
  52354. BABYLON.Tools.Error("error on XHR request.");
  52355. callback();
  52356. }, false);
  52357. xhr.send();
  52358. }
  52359. else {
  52360. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  52361. callback();
  52362. }
  52363. };
  52364. Database.IsUASupportingBlobStorage = true;
  52365. Database.IDBStorageEnabled = true;
  52366. Database.parseURL = function (url) {
  52367. var a = document.createElement('a');
  52368. a.href = url;
  52369. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  52370. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  52371. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  52372. return absLocation;
  52373. };
  52374. Database.ReturnFullUrlLocation = function (url) {
  52375. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  52376. return (Database.parseURL(window.location.href) + url);
  52377. }
  52378. else {
  52379. return url;
  52380. }
  52381. };
  52382. return Database;
  52383. }());
  52384. BABYLON.Database = Database;
  52385. })(BABYLON || (BABYLON = {}));
  52386. //# sourceMappingURL=babylon.database.js.map
  52387. var BABYLON;
  52388. (function (BABYLON) {
  52389. var FresnelParameters = (function () {
  52390. function FresnelParameters() {
  52391. this._isEnabled = true;
  52392. this.leftColor = BABYLON.Color3.White();
  52393. this.rightColor = BABYLON.Color3.Black();
  52394. this.bias = 0;
  52395. this.power = 1;
  52396. }
  52397. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  52398. get: function () {
  52399. return this._isEnabled;
  52400. },
  52401. set: function (value) {
  52402. if (this._isEnabled === value) {
  52403. return;
  52404. }
  52405. this._isEnabled = value;
  52406. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  52407. },
  52408. enumerable: true,
  52409. configurable: true
  52410. });
  52411. FresnelParameters.prototype.clone = function () {
  52412. var newFresnelParameters = new FresnelParameters();
  52413. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  52414. return newFresnelParameters;
  52415. };
  52416. FresnelParameters.prototype.serialize = function () {
  52417. var serializationObject = {};
  52418. serializationObject.isEnabled = this.isEnabled;
  52419. serializationObject.leftColor = this.leftColor;
  52420. serializationObject.rightColor = this.rightColor;
  52421. serializationObject.bias = this.bias;
  52422. serializationObject.power = this.power;
  52423. return serializationObject;
  52424. };
  52425. FresnelParameters.Parse = function (parsedFresnelParameters) {
  52426. var fresnelParameters = new FresnelParameters();
  52427. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  52428. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  52429. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  52430. fresnelParameters.bias = parsedFresnelParameters.bias;
  52431. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  52432. return fresnelParameters;
  52433. };
  52434. return FresnelParameters;
  52435. }());
  52436. BABYLON.FresnelParameters = FresnelParameters;
  52437. })(BABYLON || (BABYLON = {}));
  52438. //# sourceMappingURL=babylon.fresnelParameters.js.map
  52439. var BABYLON;
  52440. (function (BABYLON) {
  52441. var MultiMaterial = (function (_super) {
  52442. __extends(MultiMaterial, _super);
  52443. function MultiMaterial(name, scene) {
  52444. var _this = _super.call(this, name, scene, true) || this;
  52445. scene.multiMaterials.push(_this);
  52446. _this.subMaterials = new Array();
  52447. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  52448. return _this;
  52449. }
  52450. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  52451. get: function () {
  52452. return this._subMaterials;
  52453. },
  52454. set: function (value) {
  52455. this._subMaterials = value;
  52456. this._hookArray(value);
  52457. },
  52458. enumerable: true,
  52459. configurable: true
  52460. });
  52461. MultiMaterial.prototype._hookArray = function (array) {
  52462. var _this = this;
  52463. var oldPush = array.push;
  52464. array.push = function () {
  52465. var items = [];
  52466. for (var _i = 0; _i < arguments.length; _i++) {
  52467. items[_i] = arguments[_i];
  52468. }
  52469. var result = oldPush.apply(array, items);
  52470. _this._markAllSubMeshesAsTexturesDirty();
  52471. return result;
  52472. };
  52473. var oldSplice = array.splice;
  52474. array.splice = function (index, deleteCount) {
  52475. var deleted = oldSplice.apply(array, [index, deleteCount]);
  52476. _this._markAllSubMeshesAsTexturesDirty();
  52477. return deleted;
  52478. };
  52479. };
  52480. // Properties
  52481. MultiMaterial.prototype.getSubMaterial = function (index) {
  52482. if (index < 0 || index >= this.subMaterials.length) {
  52483. return this.getScene().defaultMaterial;
  52484. }
  52485. return this.subMaterials[index];
  52486. };
  52487. MultiMaterial.prototype.getActiveTextures = function () {
  52488. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  52489. var _a;
  52490. };
  52491. // Methods
  52492. MultiMaterial.prototype.getClassName = function () {
  52493. return "MultiMaterial";
  52494. };
  52495. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  52496. for (var index = 0; index < this.subMaterials.length; index++) {
  52497. var subMaterial = this.subMaterials[index];
  52498. if (subMaterial) {
  52499. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  52500. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  52501. return false;
  52502. }
  52503. continue;
  52504. }
  52505. if (!this.subMaterials[index].isReady(mesh)) {
  52506. return false;
  52507. }
  52508. }
  52509. }
  52510. return true;
  52511. };
  52512. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  52513. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  52514. for (var index = 0; index < this.subMaterials.length; index++) {
  52515. var subMaterial = null;
  52516. if (cloneChildren) {
  52517. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  52518. }
  52519. else {
  52520. subMaterial = this.subMaterials[index];
  52521. }
  52522. newMultiMaterial.subMaterials.push(subMaterial);
  52523. }
  52524. return newMultiMaterial;
  52525. };
  52526. MultiMaterial.prototype.serialize = function () {
  52527. var serializationObject = {};
  52528. serializationObject.name = this.name;
  52529. serializationObject.id = this.id;
  52530. serializationObject.tags = BABYLON.Tags.GetTags(this);
  52531. serializationObject.materials = [];
  52532. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  52533. var subMat = this.subMaterials[matIndex];
  52534. if (subMat) {
  52535. serializationObject.materials.push(subMat.id);
  52536. }
  52537. else {
  52538. serializationObject.materials.push(null);
  52539. }
  52540. }
  52541. return serializationObject;
  52542. };
  52543. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  52544. var scene = this.getScene();
  52545. if (!scene) {
  52546. return;
  52547. }
  52548. var index = scene.multiMaterials.indexOf(this);
  52549. if (index >= 0) {
  52550. scene.multiMaterials.splice(index, 1);
  52551. }
  52552. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  52553. };
  52554. return MultiMaterial;
  52555. }(BABYLON.Material));
  52556. BABYLON.MultiMaterial = MultiMaterial;
  52557. })(BABYLON || (BABYLON = {}));
  52558. //# sourceMappingURL=babylon.multiMaterial.js.map
  52559. var BABYLON;
  52560. (function (BABYLON) {
  52561. var FreeCameraTouchInput = (function () {
  52562. function FreeCameraTouchInput() {
  52563. this._offsetX = null;
  52564. this._offsetY = null;
  52565. this._pointerCount = 0;
  52566. this._pointerPressed = new Array();
  52567. this.touchAngularSensibility = 200000.0;
  52568. this.touchMoveSensibility = 250.0;
  52569. }
  52570. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  52571. var _this = this;
  52572. var previousPosition;
  52573. if (this._pointerInput === undefined) {
  52574. this._onLostFocus = function (evt) {
  52575. _this._offsetX = null;
  52576. _this._offsetY = null;
  52577. };
  52578. this._pointerInput = function (p, s) {
  52579. var evt = p.event;
  52580. if (evt.pointerType === "mouse") {
  52581. return;
  52582. }
  52583. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  52584. if (!noPreventDefault) {
  52585. evt.preventDefault();
  52586. }
  52587. _this._pointerPressed.push(evt.pointerId);
  52588. if (_this._pointerPressed.length !== 1) {
  52589. return;
  52590. }
  52591. previousPosition = {
  52592. x: evt.clientX,
  52593. y: evt.clientY
  52594. };
  52595. }
  52596. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  52597. if (!noPreventDefault) {
  52598. evt.preventDefault();
  52599. }
  52600. var index = _this._pointerPressed.indexOf(evt.pointerId);
  52601. if (index === -1) {
  52602. return;
  52603. }
  52604. _this._pointerPressed.splice(index, 1);
  52605. if (index != 0) {
  52606. return;
  52607. }
  52608. previousPosition = null;
  52609. _this._offsetX = null;
  52610. _this._offsetY = null;
  52611. }
  52612. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  52613. if (!noPreventDefault) {
  52614. evt.preventDefault();
  52615. }
  52616. if (!previousPosition) {
  52617. return;
  52618. }
  52619. var index = _this._pointerPressed.indexOf(evt.pointerId);
  52620. if (index != 0) {
  52621. return;
  52622. }
  52623. _this._offsetX = evt.clientX - previousPosition.x;
  52624. _this._offsetY = -(evt.clientY - previousPosition.y);
  52625. }
  52626. };
  52627. }
  52628. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  52629. element.addEventListener("blur", this._onLostFocus);
  52630. };
  52631. FreeCameraTouchInput.prototype.detachControl = function (element) {
  52632. if (this._pointerInput && element) {
  52633. this.camera.getScene().onPointerObservable.remove(this._observer);
  52634. this._observer = null;
  52635. element.removeEventListener("blur", this._onLostFocus);
  52636. this._onLostFocus = null;
  52637. this._pointerPressed = [];
  52638. this._offsetX = null;
  52639. this._offsetY = null;
  52640. this._pointerCount = 0;
  52641. }
  52642. };
  52643. FreeCameraTouchInput.prototype.checkInputs = function () {
  52644. if (this._offsetX) {
  52645. var camera = this.camera;
  52646. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  52647. if (this._pointerPressed.length > 1) {
  52648. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  52649. }
  52650. else {
  52651. var speed = camera._computeLocalCameraSpeed();
  52652. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  52653. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  52654. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  52655. }
  52656. }
  52657. };
  52658. FreeCameraTouchInput.prototype.getClassName = function () {
  52659. return "FreeCameraTouchInput";
  52660. };
  52661. FreeCameraTouchInput.prototype.getSimpleName = function () {
  52662. return "touch";
  52663. };
  52664. __decorate([
  52665. BABYLON.serialize()
  52666. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  52667. __decorate([
  52668. BABYLON.serialize()
  52669. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  52670. return FreeCameraTouchInput;
  52671. }());
  52672. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  52673. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  52674. })(BABYLON || (BABYLON = {}));
  52675. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  52676. /// <reference path="babylon.freeCamera.ts" />
  52677. var BABYLON;
  52678. (function (BABYLON) {
  52679. // We're mainly based on the logic defined into the FreeCamera code
  52680. var TouchCamera = (function (_super) {
  52681. __extends(TouchCamera, _super);
  52682. //-- end properties for backward compatibility for inputs
  52683. function TouchCamera(name, position, scene) {
  52684. var _this = _super.call(this, name, position, scene) || this;
  52685. _this.inputs.addTouch();
  52686. _this._setupInputs();
  52687. return _this;
  52688. }
  52689. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  52690. //-- Begin properties for backward compatibility for inputs
  52691. get: function () {
  52692. var touch = this.inputs.attached["touch"];
  52693. if (touch)
  52694. return touch.touchAngularSensibility;
  52695. return null;
  52696. },
  52697. set: function (value) {
  52698. var touch = this.inputs.attached["touch"];
  52699. if (touch)
  52700. touch.touchAngularSensibility = value;
  52701. },
  52702. enumerable: true,
  52703. configurable: true
  52704. });
  52705. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  52706. get: function () {
  52707. var touch = this.inputs.attached["touch"];
  52708. if (touch)
  52709. return touch.touchMoveSensibility;
  52710. return null;
  52711. },
  52712. set: function (value) {
  52713. var touch = this.inputs.attached["touch"];
  52714. if (touch)
  52715. touch.touchMoveSensibility = value;
  52716. },
  52717. enumerable: true,
  52718. configurable: true
  52719. });
  52720. TouchCamera.prototype.getClassName = function () {
  52721. return "TouchCamera";
  52722. };
  52723. TouchCamera.prototype._setupInputs = function () {
  52724. var mouse = this.inputs.attached["mouse"];
  52725. if (mouse) {
  52726. mouse.touchEnabled = false;
  52727. }
  52728. };
  52729. return TouchCamera;
  52730. }(BABYLON.FreeCamera));
  52731. BABYLON.TouchCamera = TouchCamera;
  52732. })(BABYLON || (BABYLON = {}));
  52733. //# sourceMappingURL=babylon.touchCamera.js.map
  52734. var BABYLON;
  52735. (function (BABYLON) {
  52736. var ProceduralTexture = (function (_super) {
  52737. __extends(ProceduralTexture, _super);
  52738. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  52739. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52740. if (isCube === void 0) { isCube = false; }
  52741. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  52742. _this.isCube = isCube;
  52743. _this.isEnabled = true;
  52744. _this._currentRefreshId = -1;
  52745. _this._refreshRate = 1;
  52746. _this._vertexBuffers = {};
  52747. _this._uniforms = new Array();
  52748. _this._samplers = new Array();
  52749. _this._textures = {};
  52750. _this._floats = {};
  52751. _this._floatsArrays = {};
  52752. _this._colors3 = {};
  52753. _this._colors4 = {};
  52754. _this._vectors2 = {};
  52755. _this._vectors3 = {};
  52756. _this._matrices = {};
  52757. _this._fallbackTextureUsed = false;
  52758. scene._proceduralTextures.push(_this);
  52759. _this.name = name;
  52760. _this.isRenderTarget = true;
  52761. _this._size = size;
  52762. _this._generateMipMaps = generateMipMaps;
  52763. _this.setFragment(fragment);
  52764. _this._fallbackTexture = fallbackTexture;
  52765. var engine = scene.getEngine();
  52766. if (isCube) {
  52767. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  52768. _this.setFloat("face", 0);
  52769. }
  52770. else {
  52771. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  52772. }
  52773. // VBO
  52774. var vertices = [];
  52775. vertices.push(1, 1);
  52776. vertices.push(-1, 1);
  52777. vertices.push(-1, -1);
  52778. vertices.push(1, -1);
  52779. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  52780. _this._createIndexBuffer();
  52781. return _this;
  52782. }
  52783. ProceduralTexture.prototype._createIndexBuffer = function () {
  52784. var engine = this.getScene().getEngine();
  52785. // Indices
  52786. var indices = [];
  52787. indices.push(0);
  52788. indices.push(1);
  52789. indices.push(2);
  52790. indices.push(0);
  52791. indices.push(2);
  52792. indices.push(3);
  52793. this._indexBuffer = engine.createIndexBuffer(indices);
  52794. };
  52795. ProceduralTexture.prototype._rebuild = function () {
  52796. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  52797. this._createIndexBuffer();
  52798. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  52799. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  52800. }
  52801. };
  52802. ProceduralTexture.prototype.reset = function () {
  52803. if (this._effect === undefined) {
  52804. return;
  52805. }
  52806. var engine = this.getScene().getEngine();
  52807. engine._releaseEffect(this._effect);
  52808. };
  52809. ProceduralTexture.prototype.isReady = function () {
  52810. var _this = this;
  52811. var engine = this.getScene().getEngine();
  52812. var shaders;
  52813. if (!this._fragment) {
  52814. return false;
  52815. }
  52816. if (this._fallbackTextureUsed) {
  52817. return true;
  52818. }
  52819. if (this._fragment.fragmentElement !== undefined) {
  52820. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  52821. }
  52822. else {
  52823. shaders = { vertex: "procedural", fragment: this._fragment };
  52824. }
  52825. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  52826. _this.releaseInternalTexture();
  52827. if (_this._fallbackTexture) {
  52828. _this._texture = _this._fallbackTexture._texture;
  52829. _this._texture.incrementReferences();
  52830. }
  52831. _this._fallbackTextureUsed = true;
  52832. });
  52833. return this._effect.isReady();
  52834. };
  52835. ProceduralTexture.prototype.resetRefreshCounter = function () {
  52836. this._currentRefreshId = -1;
  52837. };
  52838. ProceduralTexture.prototype.setFragment = function (fragment) {
  52839. this._fragment = fragment;
  52840. };
  52841. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  52842. get: function () {
  52843. return this._refreshRate;
  52844. },
  52845. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  52846. set: function (value) {
  52847. this._refreshRate = value;
  52848. this.resetRefreshCounter();
  52849. },
  52850. enumerable: true,
  52851. configurable: true
  52852. });
  52853. ProceduralTexture.prototype._shouldRender = function () {
  52854. if (!this.isEnabled || !this.isReady() || !this._texture) {
  52855. return false;
  52856. }
  52857. if (this._fallbackTextureUsed) {
  52858. return false;
  52859. }
  52860. if (this._currentRefreshId === -1) {
  52861. this._currentRefreshId = 1;
  52862. return true;
  52863. }
  52864. if (this.refreshRate === this._currentRefreshId) {
  52865. this._currentRefreshId = 1;
  52866. return true;
  52867. }
  52868. this._currentRefreshId++;
  52869. return false;
  52870. };
  52871. ProceduralTexture.prototype.getRenderSize = function () {
  52872. return this._size;
  52873. };
  52874. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  52875. if (this._fallbackTextureUsed) {
  52876. return;
  52877. }
  52878. this.releaseInternalTexture();
  52879. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  52880. };
  52881. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  52882. if (this._uniforms.indexOf(uniformName) === -1) {
  52883. this._uniforms.push(uniformName);
  52884. }
  52885. };
  52886. ProceduralTexture.prototype.setTexture = function (name, texture) {
  52887. if (this._samplers.indexOf(name) === -1) {
  52888. this._samplers.push(name);
  52889. }
  52890. this._textures[name] = texture;
  52891. return this;
  52892. };
  52893. ProceduralTexture.prototype.setFloat = function (name, value) {
  52894. this._checkUniform(name);
  52895. this._floats[name] = value;
  52896. return this;
  52897. };
  52898. ProceduralTexture.prototype.setFloats = function (name, value) {
  52899. this._checkUniform(name);
  52900. this._floatsArrays[name] = value;
  52901. return this;
  52902. };
  52903. ProceduralTexture.prototype.setColor3 = function (name, value) {
  52904. this._checkUniform(name);
  52905. this._colors3[name] = value;
  52906. return this;
  52907. };
  52908. ProceduralTexture.prototype.setColor4 = function (name, value) {
  52909. this._checkUniform(name);
  52910. this._colors4[name] = value;
  52911. return this;
  52912. };
  52913. ProceduralTexture.prototype.setVector2 = function (name, value) {
  52914. this._checkUniform(name);
  52915. this._vectors2[name] = value;
  52916. return this;
  52917. };
  52918. ProceduralTexture.prototype.setVector3 = function (name, value) {
  52919. this._checkUniform(name);
  52920. this._vectors3[name] = value;
  52921. return this;
  52922. };
  52923. ProceduralTexture.prototype.setMatrix = function (name, value) {
  52924. this._checkUniform(name);
  52925. this._matrices[name] = value;
  52926. return this;
  52927. };
  52928. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  52929. var scene = this.getScene();
  52930. var engine = scene.getEngine();
  52931. // Render
  52932. engine.enableEffect(this._effect);
  52933. engine.setState(false);
  52934. // Texture
  52935. for (var name in this._textures) {
  52936. this._effect.setTexture(name, this._textures[name]);
  52937. }
  52938. // Float
  52939. for (name in this._floats) {
  52940. this._effect.setFloat(name, this._floats[name]);
  52941. }
  52942. // Floats
  52943. for (name in this._floatsArrays) {
  52944. this._effect.setArray(name, this._floatsArrays[name]);
  52945. }
  52946. // Color3
  52947. for (name in this._colors3) {
  52948. this._effect.setColor3(name, this._colors3[name]);
  52949. }
  52950. // Color4
  52951. for (name in this._colors4) {
  52952. var color = this._colors4[name];
  52953. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  52954. }
  52955. // Vector2
  52956. for (name in this._vectors2) {
  52957. this._effect.setVector2(name, this._vectors2[name]);
  52958. }
  52959. // Vector3
  52960. for (name in this._vectors3) {
  52961. this._effect.setVector3(name, this._vectors3[name]);
  52962. }
  52963. // Matrix
  52964. for (name in this._matrices) {
  52965. this._effect.setMatrix(name, this._matrices[name]);
  52966. }
  52967. if (this.isCube) {
  52968. for (var face = 0; face < 6; face++) {
  52969. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  52970. // VBOs
  52971. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  52972. this._effect.setFloat("face", face);
  52973. // Clear
  52974. engine.clear(scene.clearColor, true, true, true);
  52975. // Draw order
  52976. engine.draw(true, 0, 6);
  52977. // Mipmaps
  52978. if (face === 5) {
  52979. engine.generateMipMapsForCubemap(this._texture);
  52980. }
  52981. }
  52982. }
  52983. else {
  52984. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  52985. // VBOs
  52986. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  52987. // Clear
  52988. engine.clear(scene.clearColor, true, true, true);
  52989. // Draw order
  52990. engine.draw(true, 0, 6);
  52991. }
  52992. // Unbind
  52993. engine.unBindFramebuffer(this._texture, this.isCube);
  52994. if (this.onGenerated) {
  52995. this.onGenerated();
  52996. }
  52997. };
  52998. ProceduralTexture.prototype.clone = function () {
  52999. var textureSize = this.getSize();
  53000. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  53001. // Base texture
  53002. newTexture.hasAlpha = this.hasAlpha;
  53003. newTexture.level = this.level;
  53004. // RenderTarget Texture
  53005. newTexture.coordinatesMode = this.coordinatesMode;
  53006. return newTexture;
  53007. };
  53008. ProceduralTexture.prototype.dispose = function () {
  53009. var index = this.getScene()._proceduralTextures.indexOf(this);
  53010. if (index >= 0) {
  53011. this.getScene()._proceduralTextures.splice(index, 1);
  53012. }
  53013. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  53014. if (vertexBuffer) {
  53015. vertexBuffer.dispose();
  53016. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  53017. }
  53018. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  53019. this._indexBuffer = null;
  53020. }
  53021. _super.prototype.dispose.call(this);
  53022. };
  53023. return ProceduralTexture;
  53024. }(BABYLON.Texture));
  53025. BABYLON.ProceduralTexture = ProceduralTexture;
  53026. })(BABYLON || (BABYLON = {}));
  53027. //# sourceMappingURL=babylon.proceduralTexture.js.map
  53028. /// <reference path="babylon.proceduralTexture.ts" />
  53029. var BABYLON;
  53030. (function (BABYLON) {
  53031. var CustomProceduralTexture = (function (_super) {
  53032. __extends(CustomProceduralTexture, _super);
  53033. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  53034. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  53035. _this._animate = true;
  53036. _this._time = 0;
  53037. _this._texturePath = texturePath;
  53038. //Try to load json
  53039. _this.loadJson(texturePath);
  53040. _this.refreshRate = 1;
  53041. return _this;
  53042. }
  53043. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  53044. var _this = this;
  53045. var that = this;
  53046. function noConfigFile() {
  53047. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  53048. try {
  53049. that.setFragment(that._texturePath);
  53050. }
  53051. catch (ex) {
  53052. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  53053. }
  53054. }
  53055. var configFileUrl = jsonUrl + "/config.json";
  53056. var xhr = new XMLHttpRequest();
  53057. xhr.open("GET", configFileUrl, true);
  53058. xhr.addEventListener("load", function () {
  53059. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  53060. try {
  53061. _this._config = JSON.parse(xhr.response);
  53062. _this.updateShaderUniforms();
  53063. _this.updateTextures();
  53064. _this.setFragment(_this._texturePath + "/custom");
  53065. _this._animate = _this._config.animate;
  53066. _this.refreshRate = _this._config.refreshrate;
  53067. }
  53068. catch (ex) {
  53069. noConfigFile();
  53070. }
  53071. }
  53072. else {
  53073. noConfigFile();
  53074. }
  53075. }, false);
  53076. xhr.addEventListener("error", function () {
  53077. noConfigFile();
  53078. }, false);
  53079. try {
  53080. xhr.send();
  53081. }
  53082. catch (ex) {
  53083. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  53084. }
  53085. };
  53086. CustomProceduralTexture.prototype.isReady = function () {
  53087. if (!_super.prototype.isReady.call(this)) {
  53088. return false;
  53089. }
  53090. for (var name in this._textures) {
  53091. var texture = this._textures[name];
  53092. if (!texture.isReady()) {
  53093. return false;
  53094. }
  53095. }
  53096. return true;
  53097. };
  53098. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  53099. if (this._animate) {
  53100. this._time += this.getScene().getAnimationRatio() * 0.03;
  53101. this.updateShaderUniforms();
  53102. }
  53103. _super.prototype.render.call(this, useCameraPostProcess);
  53104. };
  53105. CustomProceduralTexture.prototype.updateTextures = function () {
  53106. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  53107. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  53108. }
  53109. };
  53110. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  53111. if (this._config) {
  53112. for (var j = 0; j < this._config.uniforms.length; j++) {
  53113. var uniform = this._config.uniforms[j];
  53114. switch (uniform.type) {
  53115. case "float":
  53116. this.setFloat(uniform.name, uniform.value);
  53117. break;
  53118. case "color3":
  53119. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  53120. break;
  53121. case "color4":
  53122. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  53123. break;
  53124. case "vector2":
  53125. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  53126. break;
  53127. case "vector3":
  53128. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  53129. break;
  53130. }
  53131. }
  53132. }
  53133. this.setFloat("time", this._time);
  53134. };
  53135. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  53136. get: function () {
  53137. return this._animate;
  53138. },
  53139. set: function (value) {
  53140. this._animate = value;
  53141. },
  53142. enumerable: true,
  53143. configurable: true
  53144. });
  53145. return CustomProceduralTexture;
  53146. }(BABYLON.ProceduralTexture));
  53147. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  53148. })(BABYLON || (BABYLON = {}));
  53149. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  53150. var BABYLON;
  53151. (function (BABYLON) {
  53152. var FreeCameraGamepadInput = (function () {
  53153. function FreeCameraGamepadInput() {
  53154. this.gamepadAngularSensibility = 200;
  53155. this.gamepadMoveSensibility = 40;
  53156. // private members
  53157. this._cameraTransform = BABYLON.Matrix.Identity();
  53158. this._deltaTransform = BABYLON.Vector3.Zero();
  53159. this._vector3 = BABYLON.Vector3.Zero();
  53160. this._vector2 = BABYLON.Vector2.Zero();
  53161. }
  53162. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  53163. var _this = this;
  53164. var manager = this.camera.getScene().gamepadManager;
  53165. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  53166. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  53167. // prioritize XBOX gamepads.
  53168. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  53169. _this.gamepad = gamepad;
  53170. }
  53171. }
  53172. });
  53173. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  53174. if (_this.gamepad === gamepad) {
  53175. _this.gamepad = null;
  53176. }
  53177. });
  53178. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  53179. };
  53180. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  53181. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  53182. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  53183. this.gamepad = null;
  53184. };
  53185. FreeCameraGamepadInput.prototype.checkInputs = function () {
  53186. if (this.gamepad && this.gamepad.leftStick) {
  53187. var camera = this.camera;
  53188. var LSValues = this.gamepad.leftStick;
  53189. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  53190. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  53191. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  53192. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  53193. var RSValues = this.gamepad.rightStick;
  53194. if (RSValues) {
  53195. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  53196. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  53197. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  53198. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  53199. }
  53200. else {
  53201. RSValues = { x: 0, y: 0 };
  53202. }
  53203. if (!camera.rotationQuaternion) {
  53204. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  53205. }
  53206. else {
  53207. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  53208. }
  53209. var speed = camera._computeLocalCameraSpeed() * 50.0;
  53210. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  53211. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  53212. camera.cameraDirection.addInPlace(this._deltaTransform);
  53213. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  53214. camera.cameraRotation.addInPlace(this._vector2);
  53215. }
  53216. };
  53217. FreeCameraGamepadInput.prototype.getClassName = function () {
  53218. return "FreeCameraGamepadInput";
  53219. };
  53220. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  53221. return "gamepad";
  53222. };
  53223. __decorate([
  53224. BABYLON.serialize()
  53225. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  53226. __decorate([
  53227. BABYLON.serialize()
  53228. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  53229. return FreeCameraGamepadInput;
  53230. }());
  53231. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  53232. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  53233. })(BABYLON || (BABYLON = {}));
  53234. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  53235. var BABYLON;
  53236. (function (BABYLON) {
  53237. var ArcRotateCameraGamepadInput = (function () {
  53238. function ArcRotateCameraGamepadInput() {
  53239. this.gamepadRotationSensibility = 80;
  53240. this.gamepadMoveSensibility = 40;
  53241. }
  53242. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  53243. var _this = this;
  53244. var manager = this.camera.getScene().gamepadManager;
  53245. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  53246. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  53247. // prioritize XBOX gamepads.
  53248. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  53249. _this.gamepad = gamepad;
  53250. }
  53251. }
  53252. });
  53253. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  53254. if (_this.gamepad === gamepad) {
  53255. _this.gamepad = null;
  53256. }
  53257. });
  53258. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  53259. };
  53260. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  53261. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  53262. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  53263. this.gamepad = null;
  53264. };
  53265. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  53266. if (this.gamepad) {
  53267. var camera = this.camera;
  53268. var RSValues = this.gamepad.rightStick;
  53269. if (RSValues) {
  53270. if (RSValues.x != 0) {
  53271. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  53272. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  53273. camera.inertialAlphaOffset += normalizedRX;
  53274. }
  53275. }
  53276. if (RSValues.y != 0) {
  53277. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  53278. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  53279. camera.inertialBetaOffset += normalizedRY;
  53280. }
  53281. }
  53282. }
  53283. var LSValues = this.gamepad.leftStick;
  53284. if (LSValues && LSValues.y != 0) {
  53285. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  53286. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  53287. this.camera.inertialRadiusOffset -= normalizedLY;
  53288. }
  53289. }
  53290. }
  53291. };
  53292. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  53293. return "ArcRotateCameraGamepadInput";
  53294. };
  53295. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  53296. return "gamepad";
  53297. };
  53298. __decorate([
  53299. BABYLON.serialize()
  53300. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  53301. __decorate([
  53302. BABYLON.serialize()
  53303. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  53304. return ArcRotateCameraGamepadInput;
  53305. }());
  53306. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  53307. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  53308. })(BABYLON || (BABYLON = {}));
  53309. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  53310. var BABYLON;
  53311. (function (BABYLON) {
  53312. var GamepadManager = (function () {
  53313. function GamepadManager() {
  53314. var _this = this;
  53315. this._babylonGamepads = [];
  53316. this._oneGamepadConnected = false;
  53317. this._isMonitoring = false;
  53318. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  53319. if (!BABYLON.Tools.IsWindowObjectExist()) {
  53320. this._gamepadEventSupported = false;
  53321. }
  53322. else {
  53323. this._gamepadEventSupported = 'GamepadEvent' in window;
  53324. this._gamepadSupport = (navigator.getGamepads ||
  53325. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  53326. }
  53327. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  53328. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  53329. for (var i in _this._babylonGamepads) {
  53330. var gamepad = _this._babylonGamepads[i];
  53331. if (gamepad && gamepad._isConnected) {
  53332. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  53333. }
  53334. }
  53335. });
  53336. this._onGamepadConnectedEvent = function (evt) {
  53337. var gamepad = evt.gamepad;
  53338. if (gamepad.index in _this._babylonGamepads) {
  53339. if (_this._babylonGamepads[gamepad.index].isConnected) {
  53340. return;
  53341. }
  53342. }
  53343. var newGamepad;
  53344. if (_this._babylonGamepads[gamepad.index]) {
  53345. newGamepad = _this._babylonGamepads[gamepad.index];
  53346. newGamepad.browserGamepad = gamepad;
  53347. newGamepad._isConnected = true;
  53348. }
  53349. else {
  53350. newGamepad = _this._addNewGamepad(gamepad);
  53351. }
  53352. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  53353. _this._startMonitoringGamepads();
  53354. };
  53355. this._onGamepadDisconnectedEvent = function (evt) {
  53356. var gamepad = evt.gamepad;
  53357. // Remove the gamepad from the list of gamepads to monitor.
  53358. for (var i in _this._babylonGamepads) {
  53359. if (_this._babylonGamepads[i].index === gamepad.index) {
  53360. var disconnectedGamepad = _this._babylonGamepads[i];
  53361. disconnectedGamepad._isConnected = false;
  53362. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  53363. break;
  53364. }
  53365. }
  53366. };
  53367. if (this._gamepadSupport) {
  53368. //first add already-connected gamepads
  53369. this._updateGamepadObjects();
  53370. if (this._babylonGamepads.length) {
  53371. this._startMonitoringGamepads();
  53372. }
  53373. // Checking if the gamepad connected event is supported (like in Firefox)
  53374. if (this._gamepadEventSupported) {
  53375. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  53376. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  53377. }
  53378. else {
  53379. this._startMonitoringGamepads();
  53380. }
  53381. }
  53382. }
  53383. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  53384. get: function () {
  53385. return this._babylonGamepads;
  53386. },
  53387. enumerable: true,
  53388. configurable: true
  53389. });
  53390. GamepadManager.prototype.getGamepadByType = function (type) {
  53391. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  53392. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  53393. var gamepad = _a[_i];
  53394. if (gamepad && gamepad.type === type) {
  53395. return gamepad;
  53396. }
  53397. }
  53398. return null;
  53399. };
  53400. GamepadManager.prototype.dispose = function () {
  53401. if (this._gamepadEventSupported) {
  53402. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  53403. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  53404. this._onGamepadConnectedEvent = null;
  53405. this._onGamepadDisconnectedEvent = null;
  53406. }
  53407. this._babylonGamepads.forEach(function (gamepad) {
  53408. gamepad.dispose();
  53409. });
  53410. this.onGamepadConnectedObservable.clear();
  53411. this.onGamepadDisconnectedObservable.clear();
  53412. this._oneGamepadConnected = false;
  53413. this._stopMonitoringGamepads();
  53414. this._babylonGamepads = [];
  53415. };
  53416. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  53417. if (!this._oneGamepadConnected) {
  53418. this._oneGamepadConnected = true;
  53419. }
  53420. var newGamepad;
  53421. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  53422. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  53423. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  53424. }
  53425. else if (gamepad.pose) {
  53426. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  53427. }
  53428. else {
  53429. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  53430. }
  53431. this._babylonGamepads[newGamepad.index] = newGamepad;
  53432. return newGamepad;
  53433. };
  53434. GamepadManager.prototype._startMonitoringGamepads = function () {
  53435. if (!this._isMonitoring) {
  53436. this._isMonitoring = true;
  53437. this._checkGamepadsStatus();
  53438. }
  53439. };
  53440. GamepadManager.prototype._stopMonitoringGamepads = function () {
  53441. this._isMonitoring = false;
  53442. };
  53443. GamepadManager.prototype._checkGamepadsStatus = function () {
  53444. var _this = this;
  53445. // Hack to be compatible Chrome
  53446. this._updateGamepadObjects();
  53447. for (var i in this._babylonGamepads) {
  53448. var gamepad = this._babylonGamepads[i];
  53449. if (!gamepad || !gamepad.isConnected) {
  53450. continue;
  53451. }
  53452. gamepad.update();
  53453. }
  53454. if (this._isMonitoring) {
  53455. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  53456. }
  53457. };
  53458. // This function is called only on Chrome, which does not properly support
  53459. // connection/disconnection events and forces you to recopy again the gamepad object
  53460. GamepadManager.prototype._updateGamepadObjects = function () {
  53461. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  53462. for (var i = 0; i < gamepads.length; i++) {
  53463. if (gamepads[i]) {
  53464. if (!this._babylonGamepads[gamepads[i].index]) {
  53465. var newGamepad = this._addNewGamepad(gamepads[i]);
  53466. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  53467. }
  53468. else {
  53469. // Forced to copy again this object for Chrome for unknown reason
  53470. this._babylonGamepads[i].browserGamepad = gamepads[i];
  53471. if (!this._babylonGamepads[i].isConnected) {
  53472. this._babylonGamepads[i]._isConnected = true;
  53473. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  53474. }
  53475. }
  53476. }
  53477. }
  53478. };
  53479. return GamepadManager;
  53480. }());
  53481. BABYLON.GamepadManager = GamepadManager;
  53482. })(BABYLON || (BABYLON = {}));
  53483. //# sourceMappingURL=babylon.gamepadManager.js.map
  53484. var BABYLON;
  53485. (function (BABYLON) {
  53486. var StickValues = (function () {
  53487. function StickValues(x, y) {
  53488. this.x = x;
  53489. this.y = y;
  53490. }
  53491. return StickValues;
  53492. }());
  53493. BABYLON.StickValues = StickValues;
  53494. var Gamepad = (function () {
  53495. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  53496. if (leftStickX === void 0) { leftStickX = 0; }
  53497. if (leftStickY === void 0) { leftStickY = 1; }
  53498. if (rightStickX === void 0) { rightStickX = 2; }
  53499. if (rightStickY === void 0) { rightStickY = 3; }
  53500. this.id = id;
  53501. this.index = index;
  53502. this.browserGamepad = browserGamepad;
  53503. this._isConnected = true;
  53504. this.type = Gamepad.GAMEPAD;
  53505. this._leftStickAxisX = leftStickX;
  53506. this._leftStickAxisY = leftStickY;
  53507. this._rightStickAxisX = rightStickX;
  53508. this._rightStickAxisY = rightStickY;
  53509. if (this.browserGamepad.axes.length >= 2) {
  53510. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  53511. }
  53512. if (this.browserGamepad.axes.length >= 4) {
  53513. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  53514. }
  53515. }
  53516. Object.defineProperty(Gamepad.prototype, "isConnected", {
  53517. get: function () {
  53518. return this._isConnected;
  53519. },
  53520. enumerable: true,
  53521. configurable: true
  53522. });
  53523. Gamepad.prototype.onleftstickchanged = function (callback) {
  53524. this._onleftstickchanged = callback;
  53525. };
  53526. Gamepad.prototype.onrightstickchanged = function (callback) {
  53527. this._onrightstickchanged = callback;
  53528. };
  53529. Object.defineProperty(Gamepad.prototype, "leftStick", {
  53530. get: function () {
  53531. return this._leftStick;
  53532. },
  53533. set: function (newValues) {
  53534. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  53535. this._onleftstickchanged(newValues);
  53536. }
  53537. this._leftStick = newValues;
  53538. },
  53539. enumerable: true,
  53540. configurable: true
  53541. });
  53542. Object.defineProperty(Gamepad.prototype, "rightStick", {
  53543. get: function () {
  53544. return this._rightStick;
  53545. },
  53546. set: function (newValues) {
  53547. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  53548. this._onrightstickchanged(newValues);
  53549. }
  53550. this._rightStick = newValues;
  53551. },
  53552. enumerable: true,
  53553. configurable: true
  53554. });
  53555. Gamepad.prototype.update = function () {
  53556. if (this._leftStick) {
  53557. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  53558. }
  53559. if (this._rightStick) {
  53560. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  53561. }
  53562. };
  53563. Gamepad.prototype.dispose = function () {
  53564. };
  53565. Gamepad.GAMEPAD = 0;
  53566. Gamepad.GENERIC = 1;
  53567. Gamepad.XBOX = 2;
  53568. Gamepad.POSE_ENABLED = 3;
  53569. return Gamepad;
  53570. }());
  53571. BABYLON.Gamepad = Gamepad;
  53572. var GenericPad = (function (_super) {
  53573. __extends(GenericPad, _super);
  53574. function GenericPad(id, index, browserGamepad) {
  53575. var _this = _super.call(this, id, index, browserGamepad) || this;
  53576. _this.onButtonDownObservable = new BABYLON.Observable();
  53577. _this.onButtonUpObservable = new BABYLON.Observable();
  53578. _this.type = Gamepad.GENERIC;
  53579. _this._buttons = new Array(browserGamepad.buttons.length);
  53580. return _this;
  53581. }
  53582. GenericPad.prototype.onbuttondown = function (callback) {
  53583. this._onbuttondown = callback;
  53584. };
  53585. GenericPad.prototype.onbuttonup = function (callback) {
  53586. this._onbuttonup = callback;
  53587. };
  53588. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  53589. if (newValue !== currentValue) {
  53590. if (newValue === 1) {
  53591. if (this._onbuttondown) {
  53592. this._onbuttondown(buttonIndex);
  53593. }
  53594. this.onButtonDownObservable.notifyObservers(buttonIndex);
  53595. }
  53596. if (newValue === 0) {
  53597. if (this._onbuttonup) {
  53598. this._onbuttonup(buttonIndex);
  53599. }
  53600. this.onButtonUpObservable.notifyObservers(buttonIndex);
  53601. }
  53602. }
  53603. return newValue;
  53604. };
  53605. GenericPad.prototype.update = function () {
  53606. _super.prototype.update.call(this);
  53607. for (var index = 0; index < this._buttons.length; index++) {
  53608. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  53609. }
  53610. };
  53611. return GenericPad;
  53612. }(Gamepad));
  53613. BABYLON.GenericPad = GenericPad;
  53614. })(BABYLON || (BABYLON = {}));
  53615. //# sourceMappingURL=babylon.gamepad.js.map
  53616. var BABYLON;
  53617. (function (BABYLON) {
  53618. var Xbox360Button;
  53619. (function (Xbox360Button) {
  53620. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  53621. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  53622. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  53623. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  53624. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  53625. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  53626. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  53627. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  53628. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  53629. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  53630. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  53631. var Xbox360Dpad;
  53632. (function (Xbox360Dpad) {
  53633. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  53634. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  53635. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  53636. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  53637. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  53638. var Xbox360Pad = (function (_super) {
  53639. __extends(Xbox360Pad, _super);
  53640. function Xbox360Pad(id, index, gamepad, xboxOne) {
  53641. if (xboxOne === void 0) { xboxOne = false; }
  53642. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  53643. _this._leftTrigger = 0;
  53644. _this._rightTrigger = 0;
  53645. _this.onButtonDownObservable = new BABYLON.Observable();
  53646. _this.onButtonUpObservable = new BABYLON.Observable();
  53647. _this.onPadDownObservable = new BABYLON.Observable();
  53648. _this.onPadUpObservable = new BABYLON.Observable();
  53649. _this._buttonA = 0;
  53650. _this._buttonB = 0;
  53651. _this._buttonX = 0;
  53652. _this._buttonY = 0;
  53653. _this._buttonBack = 0;
  53654. _this._buttonStart = 0;
  53655. _this._buttonLB = 0;
  53656. _this._buttonRB = 0;
  53657. _this._buttonLeftStick = 0;
  53658. _this._buttonRightStick = 0;
  53659. _this._dPadUp = 0;
  53660. _this._dPadDown = 0;
  53661. _this._dPadLeft = 0;
  53662. _this._dPadRight = 0;
  53663. _this._isXboxOnePad = false;
  53664. _this.type = BABYLON.Gamepad.XBOX;
  53665. _this._isXboxOnePad = xboxOne;
  53666. return _this;
  53667. }
  53668. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  53669. this._onlefttriggerchanged = callback;
  53670. };
  53671. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  53672. this._onrighttriggerchanged = callback;
  53673. };
  53674. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  53675. get: function () {
  53676. return this._leftTrigger;
  53677. },
  53678. set: function (newValue) {
  53679. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  53680. this._onlefttriggerchanged(newValue);
  53681. }
  53682. this._leftTrigger = newValue;
  53683. },
  53684. enumerable: true,
  53685. configurable: true
  53686. });
  53687. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  53688. get: function () {
  53689. return this._rightTrigger;
  53690. },
  53691. set: function (newValue) {
  53692. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  53693. this._onrighttriggerchanged(newValue);
  53694. }
  53695. this._rightTrigger = newValue;
  53696. },
  53697. enumerable: true,
  53698. configurable: true
  53699. });
  53700. Xbox360Pad.prototype.onbuttondown = function (callback) {
  53701. this._onbuttondown = callback;
  53702. };
  53703. Xbox360Pad.prototype.onbuttonup = function (callback) {
  53704. this._onbuttonup = callback;
  53705. };
  53706. Xbox360Pad.prototype.ondpaddown = function (callback) {
  53707. this._ondpaddown = callback;
  53708. };
  53709. Xbox360Pad.prototype.ondpadup = function (callback) {
  53710. this._ondpadup = callback;
  53711. };
  53712. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  53713. if (newValue !== currentValue) {
  53714. if (newValue === 1) {
  53715. if (this._onbuttondown) {
  53716. this._onbuttondown(buttonType);
  53717. }
  53718. this.onButtonDownObservable.notifyObservers(buttonType);
  53719. }
  53720. if (newValue === 0) {
  53721. if (this._onbuttonup) {
  53722. this._onbuttonup(buttonType);
  53723. }
  53724. this.onButtonUpObservable.notifyObservers(buttonType);
  53725. }
  53726. }
  53727. return newValue;
  53728. };
  53729. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  53730. if (newValue !== currentValue) {
  53731. if (newValue === 1) {
  53732. if (this._ondpaddown) {
  53733. this._ondpaddown(buttonType);
  53734. }
  53735. this.onPadDownObservable.notifyObservers(buttonType);
  53736. }
  53737. if (newValue === 0) {
  53738. if (this._ondpadup) {
  53739. this._ondpadup(buttonType);
  53740. }
  53741. this.onPadUpObservable.notifyObservers(buttonType);
  53742. }
  53743. }
  53744. return newValue;
  53745. };
  53746. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  53747. get: function () {
  53748. return this._buttonA;
  53749. },
  53750. set: function (value) {
  53751. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  53752. },
  53753. enumerable: true,
  53754. configurable: true
  53755. });
  53756. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  53757. get: function () {
  53758. return this._buttonB;
  53759. },
  53760. set: function (value) {
  53761. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  53762. },
  53763. enumerable: true,
  53764. configurable: true
  53765. });
  53766. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  53767. get: function () {
  53768. return this._buttonX;
  53769. },
  53770. set: function (value) {
  53771. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  53772. },
  53773. enumerable: true,
  53774. configurable: true
  53775. });
  53776. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  53777. get: function () {
  53778. return this._buttonY;
  53779. },
  53780. set: function (value) {
  53781. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  53782. },
  53783. enumerable: true,
  53784. configurable: true
  53785. });
  53786. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  53787. get: function () {
  53788. return this._buttonStart;
  53789. },
  53790. set: function (value) {
  53791. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  53792. },
  53793. enumerable: true,
  53794. configurable: true
  53795. });
  53796. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  53797. get: function () {
  53798. return this._buttonBack;
  53799. },
  53800. set: function (value) {
  53801. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  53802. },
  53803. enumerable: true,
  53804. configurable: true
  53805. });
  53806. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  53807. get: function () {
  53808. return this._buttonLB;
  53809. },
  53810. set: function (value) {
  53811. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  53812. },
  53813. enumerable: true,
  53814. configurable: true
  53815. });
  53816. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  53817. get: function () {
  53818. return this._buttonRB;
  53819. },
  53820. set: function (value) {
  53821. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  53822. },
  53823. enumerable: true,
  53824. configurable: true
  53825. });
  53826. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  53827. get: function () {
  53828. return this._buttonLeftStick;
  53829. },
  53830. set: function (value) {
  53831. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  53832. },
  53833. enumerable: true,
  53834. configurable: true
  53835. });
  53836. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  53837. get: function () {
  53838. return this._buttonRightStick;
  53839. },
  53840. set: function (value) {
  53841. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  53842. },
  53843. enumerable: true,
  53844. configurable: true
  53845. });
  53846. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  53847. get: function () {
  53848. return this._dPadUp;
  53849. },
  53850. set: function (value) {
  53851. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  53852. },
  53853. enumerable: true,
  53854. configurable: true
  53855. });
  53856. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  53857. get: function () {
  53858. return this._dPadDown;
  53859. },
  53860. set: function (value) {
  53861. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  53862. },
  53863. enumerable: true,
  53864. configurable: true
  53865. });
  53866. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  53867. get: function () {
  53868. return this._dPadLeft;
  53869. },
  53870. set: function (value) {
  53871. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  53872. },
  53873. enumerable: true,
  53874. configurable: true
  53875. });
  53876. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  53877. get: function () {
  53878. return this._dPadRight;
  53879. },
  53880. set: function (value) {
  53881. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  53882. },
  53883. enumerable: true,
  53884. configurable: true
  53885. });
  53886. Xbox360Pad.prototype.update = function () {
  53887. _super.prototype.update.call(this);
  53888. if (this._isXboxOnePad) {
  53889. this.buttonA = this.browserGamepad.buttons[0].value;
  53890. this.buttonB = this.browserGamepad.buttons[1].value;
  53891. this.buttonX = this.browserGamepad.buttons[2].value;
  53892. this.buttonY = this.browserGamepad.buttons[3].value;
  53893. this.buttonLB = this.browserGamepad.buttons[4].value;
  53894. this.buttonRB = this.browserGamepad.buttons[5].value;
  53895. this.leftTrigger = this.browserGamepad.axes[2];
  53896. this.rightTrigger = this.browserGamepad.axes[5];
  53897. this.buttonBack = this.browserGamepad.buttons[9].value;
  53898. this.buttonStart = this.browserGamepad.buttons[8].value;
  53899. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  53900. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  53901. this.dPadUp = this.browserGamepad.buttons[11].value;
  53902. this.dPadDown = this.browserGamepad.buttons[12].value;
  53903. this.dPadLeft = this.browserGamepad.buttons[13].value;
  53904. this.dPadRight = this.browserGamepad.buttons[14].value;
  53905. }
  53906. else {
  53907. this.buttonA = this.browserGamepad.buttons[0].value;
  53908. this.buttonB = this.browserGamepad.buttons[1].value;
  53909. this.buttonX = this.browserGamepad.buttons[2].value;
  53910. this.buttonY = this.browserGamepad.buttons[3].value;
  53911. this.buttonLB = this.browserGamepad.buttons[4].value;
  53912. this.buttonRB = this.browserGamepad.buttons[5].value;
  53913. this.leftTrigger = this.browserGamepad.buttons[6].value;
  53914. this.rightTrigger = this.browserGamepad.buttons[7].value;
  53915. this.buttonBack = this.browserGamepad.buttons[8].value;
  53916. this.buttonStart = this.browserGamepad.buttons[9].value;
  53917. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  53918. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  53919. this.dPadUp = this.browserGamepad.buttons[12].value;
  53920. this.dPadDown = this.browserGamepad.buttons[13].value;
  53921. this.dPadLeft = this.browserGamepad.buttons[14].value;
  53922. this.dPadRight = this.browserGamepad.buttons[15].value;
  53923. }
  53924. };
  53925. return Xbox360Pad;
  53926. }(BABYLON.Gamepad));
  53927. BABYLON.Xbox360Pad = Xbox360Pad;
  53928. })(BABYLON || (BABYLON = {}));
  53929. //# sourceMappingURL=babylon.xboxGamepad.js.map
  53930. var BABYLON;
  53931. (function (BABYLON) {
  53932. var PoseEnabledControllerType;
  53933. (function (PoseEnabledControllerType) {
  53934. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  53935. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  53936. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  53937. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  53938. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  53939. var PoseEnabledControllerHelper = (function () {
  53940. function PoseEnabledControllerHelper() {
  53941. }
  53942. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  53943. // Oculus Touch
  53944. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  53945. return new BABYLON.OculusTouchController(vrGamepad);
  53946. }
  53947. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  53948. return new BABYLON.WindowsMotionController(vrGamepad);
  53949. }
  53950. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  53951. return new BABYLON.ViveController(vrGamepad);
  53952. }
  53953. else {
  53954. return new BABYLON.GenericController(vrGamepad);
  53955. }
  53956. };
  53957. return PoseEnabledControllerHelper;
  53958. }());
  53959. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  53960. var PoseEnabledController = (function (_super) {
  53961. __extends(PoseEnabledController, _super);
  53962. function PoseEnabledController(browserGamepad) {
  53963. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  53964. _this.deviceScaleFactor = 1;
  53965. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  53966. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  53967. _this.controllerType = PoseEnabledControllerType.GENERIC;
  53968. _this.position = BABYLON.Vector3.Zero();
  53969. _this.rotationQuaternion = new BABYLON.Quaternion();
  53970. _this.devicePosition = BABYLON.Vector3.Zero();
  53971. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  53972. _this._calculatedPosition = BABYLON.Vector3.Zero();
  53973. _this._calculatedRotation = new BABYLON.Quaternion();
  53974. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  53975. return _this;
  53976. }
  53977. PoseEnabledController.prototype.update = function () {
  53978. _super.prototype.update.call(this);
  53979. var pose = this.browserGamepad.pose;
  53980. this.updateFromDevice(pose);
  53981. if (this._mesh) {
  53982. this._mesh.position.copyFrom(this._calculatedPosition);
  53983. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  53984. }
  53985. };
  53986. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  53987. if (poseData) {
  53988. this.rawPose = poseData;
  53989. if (poseData.position) {
  53990. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  53991. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  53992. this.devicePosition.z *= -1;
  53993. }
  53994. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  53995. this._calculatedPosition.addInPlace(this.position);
  53996. }
  53997. if (poseData.orientation) {
  53998. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  53999. if (this._mesh) {
  54000. if (this._mesh.getScene().useRightHandedSystem) {
  54001. this.deviceRotationQuaternion.z *= -1;
  54002. this.deviceRotationQuaternion.w *= -1;
  54003. }
  54004. else {
  54005. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  54006. }
  54007. }
  54008. // if the camera is set, rotate to the camera's rotation
  54009. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  54010. }
  54011. }
  54012. };
  54013. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  54014. if (this._mesh) {
  54015. this._mesh.parent = undefined;
  54016. }
  54017. this._mesh = mesh;
  54018. if (this._poseControlledCamera) {
  54019. this._mesh.parent = this._poseControlledCamera;
  54020. }
  54021. if (!this._mesh.rotationQuaternion) {
  54022. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  54023. }
  54024. };
  54025. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  54026. this._poseControlledCamera = camera;
  54027. if (this._mesh) {
  54028. this._mesh.parent = this._poseControlledCamera;
  54029. }
  54030. };
  54031. PoseEnabledController.prototype.dispose = function () {
  54032. if (this._mesh) {
  54033. this._mesh.dispose();
  54034. }
  54035. this._mesh = undefined;
  54036. _super.prototype.dispose.call(this);
  54037. };
  54038. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  54039. get: function () {
  54040. return this._mesh;
  54041. },
  54042. enumerable: true,
  54043. configurable: true
  54044. });
  54045. PoseEnabledController.prototype.getForwardRay = function (length) {
  54046. if (length === void 0) { length = 100; }
  54047. if (!this.mesh) {
  54048. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  54049. }
  54050. var m = this.mesh.getWorldMatrix();
  54051. var origin = m.getTranslation();
  54052. var forward = new BABYLON.Vector3(0, 0, -1);
  54053. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  54054. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  54055. return new BABYLON.Ray(origin, direction, length);
  54056. };
  54057. return PoseEnabledController;
  54058. }(BABYLON.Gamepad));
  54059. BABYLON.PoseEnabledController = PoseEnabledController;
  54060. })(BABYLON || (BABYLON = {}));
  54061. //# sourceMappingURL=babylon.poseEnabledController.js.map
  54062. var BABYLON;
  54063. (function (BABYLON) {
  54064. var WebVRController = (function (_super) {
  54065. __extends(WebVRController, _super);
  54066. function WebVRController(vrGamepad) {
  54067. var _this = _super.call(this, vrGamepad) || this;
  54068. // Observables
  54069. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  54070. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  54071. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  54072. _this.onPadStateChangedObservable = new BABYLON.Observable();
  54073. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  54074. _this.pad = { x: 0, y: 0 };
  54075. // avoid GC, store state in a tmp object
  54076. _this._changes = {
  54077. pressChanged: false,
  54078. touchChanged: false,
  54079. valueChanged: false,
  54080. changed: false
  54081. };
  54082. _this._buttons = new Array(vrGamepad.buttons.length);
  54083. _this.hand = vrGamepad.hand;
  54084. return _this;
  54085. }
  54086. WebVRController.prototype.onButtonStateChange = function (callback) {
  54087. this._onButtonStateChange = callback;
  54088. };
  54089. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  54090. get: function () {
  54091. return this._defaultModel;
  54092. },
  54093. enumerable: true,
  54094. configurable: true
  54095. });
  54096. WebVRController.prototype.update = function () {
  54097. _super.prototype.update.call(this);
  54098. for (var index = 0; index < this._buttons.length; index++) {
  54099. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  54100. }
  54101. ;
  54102. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  54103. this.pad.x = this.leftStick.x;
  54104. this.pad.y = this.leftStick.y;
  54105. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  54106. }
  54107. };
  54108. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  54109. if (!newState) {
  54110. newState = {
  54111. pressed: false,
  54112. touched: false,
  54113. value: 0
  54114. };
  54115. }
  54116. if (!currentState) {
  54117. this._buttons[buttonIndex] = {
  54118. pressed: newState.pressed,
  54119. touched: newState.touched,
  54120. value: newState.value
  54121. };
  54122. return;
  54123. }
  54124. this._checkChanges(newState, currentState);
  54125. if (this._changes.changed) {
  54126. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  54127. this.handleButtonChange(buttonIndex, newState, this._changes);
  54128. }
  54129. this._buttons[buttonIndex].pressed = newState.pressed;
  54130. this._buttons[buttonIndex].touched = newState.touched;
  54131. // oculus triggers are never 0, thou not touched.
  54132. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  54133. };
  54134. WebVRController.prototype._checkChanges = function (newState, currentState) {
  54135. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  54136. this._changes.touchChanged = newState.touched !== currentState.touched;
  54137. this._changes.valueChanged = newState.value !== currentState.value;
  54138. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  54139. return this._changes;
  54140. };
  54141. WebVRController.prototype.dispose = function () {
  54142. _super.prototype.dispose.call(this);
  54143. this.onTriggerStateChangedObservable.clear();
  54144. this.onMainButtonStateChangedObservable.clear();
  54145. this.onSecondaryButtonStateChangedObservable.clear();
  54146. this.onPadStateChangedObservable.clear();
  54147. this.onPadValuesChangedObservable.clear();
  54148. };
  54149. return WebVRController;
  54150. }(BABYLON.PoseEnabledController));
  54151. BABYLON.WebVRController = WebVRController;
  54152. })(BABYLON || (BABYLON = {}));
  54153. //# sourceMappingURL=babylon.webVRController.js.map
  54154. var BABYLON;
  54155. (function (BABYLON) {
  54156. var OculusTouchController = (function (_super) {
  54157. __extends(OculusTouchController, _super);
  54158. function OculusTouchController(vrGamepad) {
  54159. var _this = _super.call(this, vrGamepad) || this;
  54160. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  54161. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  54162. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  54163. return _this;
  54164. }
  54165. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  54166. var _this = this;
  54167. var meshName;
  54168. // Hand
  54169. if (this.hand === 'left') {
  54170. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  54171. }
  54172. else {
  54173. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  54174. }
  54175. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  54176. /*
  54177. Parent Mesh name: oculus_touch_left
  54178. - body
  54179. - trigger
  54180. - thumbstick
  54181. - grip
  54182. - button_y
  54183. - button_x
  54184. - button_enter
  54185. */
  54186. _this._defaultModel = newMeshes[1];
  54187. if (meshLoaded) {
  54188. meshLoaded(_this._defaultModel);
  54189. }
  54190. _this.attachToMesh(_this._defaultModel);
  54191. });
  54192. };
  54193. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  54194. // helper getters for left and right hand.
  54195. get: function () {
  54196. if (this.hand === 'right') {
  54197. return this.onMainButtonStateChangedObservable;
  54198. }
  54199. else {
  54200. throw new Error('No A button on left hand');
  54201. }
  54202. },
  54203. enumerable: true,
  54204. configurable: true
  54205. });
  54206. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  54207. get: function () {
  54208. if (this.hand === 'right') {
  54209. return this.onSecondaryButtonStateChangedObservable;
  54210. }
  54211. else {
  54212. throw new Error('No B button on left hand');
  54213. }
  54214. },
  54215. enumerable: true,
  54216. configurable: true
  54217. });
  54218. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  54219. get: function () {
  54220. if (this.hand === 'left') {
  54221. return this.onMainButtonStateChangedObservable;
  54222. }
  54223. else {
  54224. throw new Error('No X button on right hand');
  54225. }
  54226. },
  54227. enumerable: true,
  54228. configurable: true
  54229. });
  54230. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  54231. get: function () {
  54232. if (this.hand === 'left') {
  54233. return this.onSecondaryButtonStateChangedObservable;
  54234. }
  54235. else {
  54236. throw new Error('No Y button on right hand');
  54237. }
  54238. },
  54239. enumerable: true,
  54240. configurable: true
  54241. });
  54242. /*
  54243. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  54244. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  54245. 2) secondary trigger (same)
  54246. 3) A (right) X (left), touch, pressed = value
  54247. 4) B / Y
  54248. 5) thumb rest
  54249. */
  54250. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  54251. var notifyObject = state; //{ state: state, changes: changes };
  54252. var triggerDirection = this.hand === 'right' ? -1 : 1;
  54253. switch (buttonIdx) {
  54254. case 0:
  54255. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  54256. return;
  54257. case 1:// index trigger
  54258. if (this._defaultModel) {
  54259. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  54260. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  54261. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  54262. }
  54263. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  54264. return;
  54265. case 2:// secondary trigger
  54266. if (this._defaultModel) {
  54267. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  54268. }
  54269. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  54270. return;
  54271. case 3:
  54272. if (this._defaultModel) {
  54273. if (notifyObject.pressed) {
  54274. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  54275. }
  54276. else {
  54277. (this._defaultModel.getChildren()[1]).position.y = 0;
  54278. }
  54279. }
  54280. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  54281. return;
  54282. case 4:
  54283. if (this._defaultModel) {
  54284. if (notifyObject.pressed) {
  54285. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  54286. }
  54287. else {
  54288. (this._defaultModel.getChildren()[2]).position.y = 0;
  54289. }
  54290. }
  54291. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  54292. return;
  54293. case 5:
  54294. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  54295. return;
  54296. }
  54297. };
  54298. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  54299. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  54300. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  54301. return OculusTouchController;
  54302. }(BABYLON.WebVRController));
  54303. BABYLON.OculusTouchController = OculusTouchController;
  54304. })(BABYLON || (BABYLON = {}));
  54305. //# sourceMappingURL=babylon.oculusTouchController.js.map
  54306. var BABYLON;
  54307. (function (BABYLON) {
  54308. var ViveController = (function (_super) {
  54309. __extends(ViveController, _super);
  54310. function ViveController(vrGamepad) {
  54311. var _this = _super.call(this, vrGamepad) || this;
  54312. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  54313. return _this;
  54314. }
  54315. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  54316. var _this = this;
  54317. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  54318. /*
  54319. Parent Mesh name: ViveWand
  54320. - body
  54321. - r_gripper
  54322. - l_gripper
  54323. - menu_button
  54324. - system_button
  54325. - trackpad
  54326. - trigger
  54327. - LED
  54328. */
  54329. _this._defaultModel = newMeshes[1];
  54330. if (meshLoaded) {
  54331. meshLoaded(_this._defaultModel);
  54332. }
  54333. _this.attachToMesh(_this._defaultModel);
  54334. });
  54335. };
  54336. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  54337. get: function () {
  54338. return this.onMainButtonStateChangedObservable;
  54339. },
  54340. enumerable: true,
  54341. configurable: true
  54342. });
  54343. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  54344. get: function () {
  54345. return this.onMainButtonStateChangedObservable;
  54346. },
  54347. enumerable: true,
  54348. configurable: true
  54349. });
  54350. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  54351. get: function () {
  54352. return this.onSecondaryButtonStateChangedObservable;
  54353. },
  54354. enumerable: true,
  54355. configurable: true
  54356. });
  54357. /**
  54358. * Vive mapping:
  54359. * 0: touchpad
  54360. * 1: trigger
  54361. * 2: left AND right buttons
  54362. * 3: menu button
  54363. */
  54364. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  54365. var notifyObject = state; //{ state: state, changes: changes };
  54366. switch (buttonIdx) {
  54367. case 0:
  54368. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  54369. return;
  54370. case 1:// index trigger
  54371. if (this._defaultModel) {
  54372. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  54373. }
  54374. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  54375. return;
  54376. case 2:// left AND right button
  54377. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  54378. return;
  54379. case 3:
  54380. if (this._defaultModel) {
  54381. if (notifyObject.pressed) {
  54382. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  54383. }
  54384. else {
  54385. (this._defaultModel.getChildren()[2]).position.y = 0;
  54386. }
  54387. }
  54388. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  54389. return;
  54390. }
  54391. };
  54392. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  54393. ViveController.MODEL_FILENAME = 'wand.babylon';
  54394. return ViveController;
  54395. }(BABYLON.WebVRController));
  54396. BABYLON.ViveController = ViveController;
  54397. })(BABYLON || (BABYLON = {}));
  54398. //# sourceMappingURL=babylon.viveController.js.map
  54399. var BABYLON;
  54400. (function (BABYLON) {
  54401. var GenericController = (function (_super) {
  54402. __extends(GenericController, _super);
  54403. function GenericController(vrGamepad) {
  54404. return _super.call(this, vrGamepad) || this;
  54405. }
  54406. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  54407. var _this = this;
  54408. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  54409. _this._defaultModel = newMeshes[1];
  54410. if (meshLoaded) {
  54411. meshLoaded(_this._defaultModel);
  54412. }
  54413. _this.attachToMesh(_this._defaultModel);
  54414. });
  54415. };
  54416. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  54417. console.log("Button id: " + buttonIdx + "state: ");
  54418. console.dir(state);
  54419. };
  54420. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  54421. GenericController.MODEL_FILENAME = 'generic.babylon';
  54422. return GenericController;
  54423. }(BABYLON.WebVRController));
  54424. BABYLON.GenericController = GenericController;
  54425. })(BABYLON || (BABYLON = {}));
  54426. //# sourceMappingURL=babylon.genericController.js.map
  54427. var BABYLON;
  54428. (function (BABYLON) {
  54429. var LoadedMeshInfo = (function () {
  54430. function LoadedMeshInfo() {
  54431. this.buttonMeshes = {};
  54432. this.axisMeshes = {};
  54433. }
  54434. return LoadedMeshInfo;
  54435. }());
  54436. var WindowsMotionController = (function (_super) {
  54437. __extends(WindowsMotionController, _super);
  54438. function WindowsMotionController(vrGamepad) {
  54439. var _this = _super.call(this, vrGamepad) || this;
  54440. _this._mapping = {
  54441. // Semantic button names
  54442. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  54443. // A mapping of the button name to glTF model node name
  54444. // that should be transformed by button value.
  54445. buttonMeshNames: {
  54446. 'trigger': 'SELECT',
  54447. 'menu': 'MENU',
  54448. 'grip': 'GRASP',
  54449. 'thumbstick': 'THUMBSTICK_PRESS',
  54450. 'trackpad': 'TOUCHPAD_PRESS'
  54451. },
  54452. // This mapping is used to translate from the Motion Controller to Babylon semantics
  54453. buttonObservableNames: {
  54454. 'trigger': 'onTriggerStateChangedObservable',
  54455. 'menu': 'onSecondaryButtonStateChangedObservable',
  54456. 'grip': 'onMainButtonStateChangedObservable',
  54457. 'thumbstick': 'onPadStateChangedObservable',
  54458. 'trackpad': 'onTrackpadChangedObservable'
  54459. },
  54460. // A mapping of the axis name to glTF model node name
  54461. // that should be transformed by axis value.
  54462. // This array mirrors the browserGamepad.axes array, such that
  54463. // the mesh corresponding to axis 0 is in this array index 0.
  54464. axisMeshNames: [
  54465. 'THUMBSTICK_X',
  54466. 'THUMBSTICK_Y',
  54467. 'TOUCHPAD_TOUCH_X',
  54468. 'TOUCHPAD_TOUCH_Y'
  54469. ],
  54470. pointingPoseMeshName: 'POINTING_POSE'
  54471. };
  54472. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  54473. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  54474. _this._loadedMeshInfo = null;
  54475. return _this;
  54476. }
  54477. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  54478. get: function () {
  54479. return this.onTriggerStateChangedObservable;
  54480. },
  54481. enumerable: true,
  54482. configurable: true
  54483. });
  54484. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  54485. get: function () {
  54486. return this.onSecondaryButtonStateChangedObservable;
  54487. },
  54488. enumerable: true,
  54489. configurable: true
  54490. });
  54491. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  54492. get: function () {
  54493. return this.onMainButtonStateChangedObservable;
  54494. },
  54495. enumerable: true,
  54496. configurable: true
  54497. });
  54498. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  54499. get: function () {
  54500. return this.onPadStateChangedObservable;
  54501. },
  54502. enumerable: true,
  54503. configurable: true
  54504. });
  54505. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  54506. get: function () {
  54507. return this.onTrackpadChangedObservable;
  54508. },
  54509. enumerable: true,
  54510. configurable: true
  54511. });
  54512. /**
  54513. * Called once per frame by the engine.
  54514. */
  54515. WindowsMotionController.prototype.update = function () {
  54516. _super.prototype.update.call(this);
  54517. // Only need to animate axes if there is a loaded mesh
  54518. if (this._loadedMeshInfo) {
  54519. if (this.browserGamepad.axes) {
  54520. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  54521. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  54522. }
  54523. }
  54524. }
  54525. };
  54526. /**
  54527. * Called once for each button that changed state since the last frame
  54528. * @param buttonIdx Which button index changed
  54529. * @param state New state of the button
  54530. * @param changes Which properties on the state changed since last frame
  54531. */
  54532. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  54533. var buttonName = this._mapping.buttons[buttonIdx];
  54534. if (!buttonName) {
  54535. return;
  54536. }
  54537. // Only emit events for buttons that we know how to map from index to name
  54538. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  54539. if (observable) {
  54540. observable.notifyObservers(state);
  54541. }
  54542. this.lerpButtonTransform(buttonName, state.value);
  54543. };
  54544. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  54545. // If there is no loaded mesh, there is nothing to transform.
  54546. if (!this._loadedMeshInfo) {
  54547. return;
  54548. }
  54549. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  54550. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  54551. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  54552. };
  54553. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  54554. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  54555. if (!meshInfo) {
  54556. return;
  54557. }
  54558. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  54559. var lerpValue = axisValue * 0.5 + 0.5;
  54560. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  54561. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  54562. };
  54563. /**
  54564. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  54565. * @param scene scene in which to add meshes
  54566. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  54567. */
  54568. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  54569. var _this = this;
  54570. if (forceDefault === void 0) { forceDefault = false; }
  54571. var path;
  54572. var filename;
  54573. // Checking if GLB loader is present
  54574. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  54575. // Determine the device specific folder based on the ID suffix
  54576. var device = 'default';
  54577. if (this.id && !forceDefault) {
  54578. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  54579. device = ((match && match[0]) || device);
  54580. }
  54581. // Hand
  54582. if (this.hand === 'left') {
  54583. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  54584. }
  54585. else {
  54586. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  54587. }
  54588. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  54589. }
  54590. else {
  54591. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  54592. path = BABYLON.GenericController.MODEL_BASE_URL;
  54593. filename = BABYLON.GenericController.MODEL_FILENAME;
  54594. }
  54595. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  54596. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  54597. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  54598. if (!_this._loadedMeshInfo) {
  54599. return;
  54600. }
  54601. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  54602. _this.attachToMesh(_this._defaultModel);
  54603. if (meshLoaded) {
  54604. meshLoaded(_this._defaultModel);
  54605. }
  54606. }, null, function (scene, message) {
  54607. BABYLON.Tools.Log(message);
  54608. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  54609. if (!forceDefault) {
  54610. _this.initControllerMesh(scene, meshLoaded, true);
  54611. }
  54612. });
  54613. };
  54614. /**
  54615. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  54616. * can be transformed by button presses and axes values, based on this._mapping.
  54617. *
  54618. * @param scene scene in which the meshes exist
  54619. * @param meshes list of meshes that make up the controller model to process
  54620. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  54621. */
  54622. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  54623. var loadedMeshInfo = null;
  54624. // Create a new mesh to contain the glTF hierarchy
  54625. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  54626. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  54627. var childMesh = null;
  54628. for (var i = 0; i < meshes.length; i++) {
  54629. var mesh = meshes[i];
  54630. if (!mesh.parent) {
  54631. // Exclude controller meshes from picking results
  54632. mesh.isPickable = false;
  54633. // Handle root node, attach to the new parentMesh
  54634. childMesh = mesh;
  54635. break;
  54636. }
  54637. }
  54638. if (childMesh) {
  54639. childMesh.setParent(parentMesh);
  54640. // Create our mesh info. Note that this method will always return non-null.
  54641. loadedMeshInfo = this.createMeshInfo(parentMesh);
  54642. }
  54643. else {
  54644. BABYLON.Tools.Warn('Could not find root node in model file.');
  54645. }
  54646. return loadedMeshInfo;
  54647. };
  54648. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  54649. var loadedMeshInfo = new LoadedMeshInfo();
  54650. var i;
  54651. loadedMeshInfo.rootNode = rootNode;
  54652. // Reset the caches
  54653. loadedMeshInfo.buttonMeshes = {};
  54654. loadedMeshInfo.axisMeshes = {};
  54655. // Button Meshes
  54656. for (i = 0; i < this._mapping.buttons.length; i++) {
  54657. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  54658. if (!buttonMeshName) {
  54659. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  54660. continue;
  54661. }
  54662. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  54663. if (!buttonMesh) {
  54664. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  54665. continue;
  54666. }
  54667. var buttonMeshInfo = {
  54668. index: i,
  54669. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  54670. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  54671. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  54672. };
  54673. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  54674. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  54675. }
  54676. else {
  54677. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  54678. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  54679. '(VALUE: ' + !!buttonMeshInfo.value +
  54680. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  54681. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  54682. ')');
  54683. }
  54684. }
  54685. // Axis Meshes
  54686. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  54687. var axisMeshName = this._mapping.axisMeshNames[i];
  54688. if (!axisMeshName) {
  54689. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  54690. continue;
  54691. }
  54692. var axisMesh = getChildByName(rootNode, axisMeshName);
  54693. if (!axisMesh) {
  54694. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  54695. continue;
  54696. }
  54697. var axisMeshInfo = {
  54698. index: i,
  54699. value: getImmediateChildByName(axisMesh, 'VALUE'),
  54700. min: getImmediateChildByName(axisMesh, 'MIN'),
  54701. max: getImmediateChildByName(axisMesh, 'MAX')
  54702. };
  54703. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  54704. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  54705. }
  54706. else {
  54707. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  54708. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  54709. '(VALUE: ' + !!axisMeshInfo.value +
  54710. ', MIN: ' + !!axisMeshInfo.min +
  54711. ', MAX:' + !!axisMeshInfo.max +
  54712. ')');
  54713. }
  54714. }
  54715. // Pointing Ray
  54716. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  54717. if (!loadedMeshInfo.pointingPoseNode) {
  54718. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  54719. }
  54720. return loadedMeshInfo;
  54721. // Look through all children recursively. This will return null if no mesh exists with the given name.
  54722. function getChildByName(node, name) {
  54723. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  54724. }
  54725. // Look through only immediate children. This will return null if no mesh exists with the given name.
  54726. function getImmediateChildByName(node, name) {
  54727. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  54728. }
  54729. };
  54730. WindowsMotionController.prototype.getForwardRay = function (length) {
  54731. if (length === void 0) { length = 100; }
  54732. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  54733. return _super.prototype.getForwardRay.call(this, length);
  54734. }
  54735. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  54736. var origin = m.getTranslation();
  54737. var forward = new BABYLON.Vector3(0, 0, -1);
  54738. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  54739. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  54740. return new BABYLON.Ray(origin, direction, length);
  54741. };
  54742. WindowsMotionController.prototype.dispose = function () {
  54743. _super.prototype.dispose.call(this);
  54744. this.onTrackpadChangedObservable.clear();
  54745. };
  54746. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  54747. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  54748. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  54749. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  54750. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  54751. return WindowsMotionController;
  54752. }(BABYLON.WebVRController));
  54753. BABYLON.WindowsMotionController = WindowsMotionController;
  54754. })(BABYLON || (BABYLON = {}));
  54755. //# sourceMappingURL=babylon.windowsMotionController.js.map
  54756. /// <reference path="babylon.targetCamera.ts" />
  54757. var BABYLON;
  54758. (function (BABYLON) {
  54759. var FollowCamera = (function (_super) {
  54760. __extends(FollowCamera, _super);
  54761. function FollowCamera(name, position, scene, lockedTarget) {
  54762. var _this = _super.call(this, name, position, scene) || this;
  54763. _this.radius = 12;
  54764. _this.rotationOffset = 0;
  54765. _this.heightOffset = 4;
  54766. _this.cameraAcceleration = 0.05;
  54767. _this.maxCameraSpeed = 20;
  54768. _this.lockedTarget = lockedTarget;
  54769. return _this;
  54770. }
  54771. FollowCamera.prototype.getRadians = function (degrees) {
  54772. return degrees * Math.PI / 180;
  54773. };
  54774. FollowCamera.prototype.follow = function (cameraTarget) {
  54775. if (!cameraTarget)
  54776. return;
  54777. var yRotation;
  54778. if (cameraTarget.rotationQuaternion) {
  54779. var rotMatrix = new BABYLON.Matrix();
  54780. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  54781. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  54782. }
  54783. else {
  54784. yRotation = cameraTarget.rotation.y;
  54785. }
  54786. var radians = this.getRadians(this.rotationOffset) + yRotation;
  54787. var targetPosition = cameraTarget.getAbsolutePosition();
  54788. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  54789. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  54790. var dx = targetX - this.position.x;
  54791. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  54792. var dz = (targetZ) - this.position.z;
  54793. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  54794. var vy = dy * this.cameraAcceleration;
  54795. var vz = dz * this.cameraAcceleration * 2;
  54796. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  54797. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  54798. }
  54799. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  54800. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  54801. }
  54802. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  54803. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  54804. }
  54805. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  54806. this.setTarget(targetPosition);
  54807. };
  54808. FollowCamera.prototype._checkInputs = function () {
  54809. _super.prototype._checkInputs.call(this);
  54810. this.follow(this.lockedTarget);
  54811. };
  54812. FollowCamera.prototype.getClassName = function () {
  54813. return "FollowCamera";
  54814. };
  54815. __decorate([
  54816. BABYLON.serialize()
  54817. ], FollowCamera.prototype, "radius", void 0);
  54818. __decorate([
  54819. BABYLON.serialize()
  54820. ], FollowCamera.prototype, "rotationOffset", void 0);
  54821. __decorate([
  54822. BABYLON.serialize()
  54823. ], FollowCamera.prototype, "heightOffset", void 0);
  54824. __decorate([
  54825. BABYLON.serialize()
  54826. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  54827. __decorate([
  54828. BABYLON.serialize()
  54829. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  54830. __decorate([
  54831. BABYLON.serializeAsMeshReference("lockedTargetId")
  54832. ], FollowCamera.prototype, "lockedTarget", void 0);
  54833. return FollowCamera;
  54834. }(BABYLON.TargetCamera));
  54835. BABYLON.FollowCamera = FollowCamera;
  54836. var ArcFollowCamera = (function (_super) {
  54837. __extends(ArcFollowCamera, _super);
  54838. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  54839. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  54840. _this.alpha = alpha;
  54841. _this.beta = beta;
  54842. _this.radius = radius;
  54843. _this.target = target;
  54844. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  54845. _this.follow();
  54846. return _this;
  54847. }
  54848. ArcFollowCamera.prototype.follow = function () {
  54849. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  54850. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  54851. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  54852. var targetPosition = this.target.getAbsolutePosition();
  54853. this.position = targetPosition.add(this._cartesianCoordinates);
  54854. this.setTarget(targetPosition);
  54855. };
  54856. ArcFollowCamera.prototype._checkInputs = function () {
  54857. _super.prototype._checkInputs.call(this);
  54858. this.follow();
  54859. };
  54860. ArcFollowCamera.prototype.getClassName = function () {
  54861. return "ArcFollowCamera";
  54862. };
  54863. return ArcFollowCamera;
  54864. }(BABYLON.TargetCamera));
  54865. BABYLON.ArcFollowCamera = ArcFollowCamera;
  54866. })(BABYLON || (BABYLON = {}));
  54867. //# sourceMappingURL=babylon.followCamera.js.map
  54868. /// <reference path="babylon.touchCamera.ts" />
  54869. var BABYLON;
  54870. (function (BABYLON) {
  54871. // We're mainly based on the logic defined into the FreeCamera code
  54872. var UniversalCamera = (function (_super) {
  54873. __extends(UniversalCamera, _super);
  54874. //-- end properties for backward compatibility for inputs
  54875. function UniversalCamera(name, position, scene) {
  54876. var _this = _super.call(this, name, position, scene) || this;
  54877. _this.inputs.addGamepad();
  54878. return _this;
  54879. }
  54880. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  54881. //-- Begin properties for backward compatibility for inputs
  54882. get: function () {
  54883. var gamepad = this.inputs.attached["gamepad"];
  54884. if (gamepad)
  54885. return gamepad.gamepadAngularSensibility;
  54886. return null;
  54887. },
  54888. set: function (value) {
  54889. var gamepad = this.inputs.attached["gamepad"];
  54890. if (gamepad)
  54891. gamepad.gamepadAngularSensibility = value;
  54892. },
  54893. enumerable: true,
  54894. configurable: true
  54895. });
  54896. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  54897. get: function () {
  54898. var gamepad = this.inputs.attached["gamepad"];
  54899. if (gamepad)
  54900. return gamepad.gamepadMoveSensibility;
  54901. return null;
  54902. },
  54903. set: function (value) {
  54904. var gamepad = this.inputs.attached["gamepad"];
  54905. if (gamepad)
  54906. gamepad.gamepadMoveSensibility = value;
  54907. },
  54908. enumerable: true,
  54909. configurable: true
  54910. });
  54911. UniversalCamera.prototype.getClassName = function () {
  54912. return "UniversalCamera";
  54913. };
  54914. return UniversalCamera;
  54915. }(BABYLON.TouchCamera));
  54916. BABYLON.UniversalCamera = UniversalCamera;
  54917. })(BABYLON || (BABYLON = {}));
  54918. //# sourceMappingURL=babylon.universalCamera.js.map
  54919. /// <reference path="babylon.universalCamera.ts" />
  54920. var BABYLON;
  54921. (function (BABYLON) {
  54922. // We're mainly based on the logic defined into the FreeCamera code
  54923. var GamepadCamera = (function (_super) {
  54924. __extends(GamepadCamera, _super);
  54925. //-- end properties for backward compatibility for inputs
  54926. function GamepadCamera(name, position, scene) {
  54927. return _super.call(this, name, position, scene) || this;
  54928. }
  54929. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  54930. //-- Begin properties for backward compatibility for inputs
  54931. get: function () {
  54932. var gamepad = this.inputs.attached["gamepad"];
  54933. if (gamepad)
  54934. return gamepad.gamepadAngularSensibility;
  54935. return null;
  54936. },
  54937. set: function (value) {
  54938. var gamepad = this.inputs.attached["gamepad"];
  54939. if (gamepad)
  54940. gamepad.gamepadAngularSensibility = value;
  54941. },
  54942. enumerable: true,
  54943. configurable: true
  54944. });
  54945. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  54946. get: function () {
  54947. var gamepad = this.inputs.attached["gamepad"];
  54948. if (gamepad)
  54949. return gamepad.gamepadMoveSensibility;
  54950. return null;
  54951. },
  54952. set: function (value) {
  54953. var gamepad = this.inputs.attached["gamepad"];
  54954. if (gamepad)
  54955. gamepad.gamepadMoveSensibility = value;
  54956. },
  54957. enumerable: true,
  54958. configurable: true
  54959. });
  54960. GamepadCamera.prototype.getClassName = function () {
  54961. return "GamepadCamera";
  54962. };
  54963. return GamepadCamera;
  54964. }(BABYLON.UniversalCamera));
  54965. BABYLON.GamepadCamera = GamepadCamera;
  54966. })(BABYLON || (BABYLON = {}));
  54967. //# sourceMappingURL=babylon.gamepadCamera.js.map
  54968. var BABYLON;
  54969. (function (BABYLON) {
  54970. var PostProcessRenderPipelineManager = (function () {
  54971. function PostProcessRenderPipelineManager() {
  54972. this._renderPipelines = {};
  54973. }
  54974. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  54975. this._renderPipelines[renderPipeline._name] = renderPipeline;
  54976. };
  54977. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  54978. var renderPipeline = this._renderPipelines[renderPipelineName];
  54979. if (!renderPipeline) {
  54980. return;
  54981. }
  54982. renderPipeline._attachCameras(cameras, unique);
  54983. };
  54984. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  54985. var renderPipeline = this._renderPipelines[renderPipelineName];
  54986. if (!renderPipeline) {
  54987. return;
  54988. }
  54989. renderPipeline._detachCameras(cameras);
  54990. };
  54991. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  54992. var renderPipeline = this._renderPipelines[renderPipelineName];
  54993. if (!renderPipeline) {
  54994. return;
  54995. }
  54996. renderPipeline._enableEffect(renderEffectName, cameras);
  54997. };
  54998. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  54999. var renderPipeline = this._renderPipelines[renderPipelineName];
  55000. if (!renderPipeline) {
  55001. return;
  55002. }
  55003. renderPipeline._disableEffect(renderEffectName, cameras);
  55004. };
  55005. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  55006. var renderPipeline = this._renderPipelines[renderPipelineName];
  55007. if (!renderPipeline) {
  55008. return;
  55009. }
  55010. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  55011. };
  55012. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  55013. var renderPipeline = this._renderPipelines[renderPipelineName];
  55014. if (!renderPipeline) {
  55015. return;
  55016. }
  55017. renderPipeline._disableDisplayOnlyPass(cameras);
  55018. };
  55019. PostProcessRenderPipelineManager.prototype.update = function () {
  55020. for (var renderPipelineName in this._renderPipelines) {
  55021. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  55022. var pipeline = this._renderPipelines[renderPipelineName];
  55023. if (!pipeline.isSupported) {
  55024. pipeline.dispose();
  55025. delete this._renderPipelines[renderPipelineName];
  55026. }
  55027. else {
  55028. pipeline._update();
  55029. }
  55030. }
  55031. }
  55032. };
  55033. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  55034. for (var renderPipelineName in this._renderPipelines) {
  55035. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  55036. var pipeline = this._renderPipelines[renderPipelineName];
  55037. pipeline._rebuild();
  55038. }
  55039. }
  55040. };
  55041. PostProcessRenderPipelineManager.prototype.dispose = function () {
  55042. for (var renderPipelineName in this._renderPipelines) {
  55043. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  55044. var pipeline = this._renderPipelines[renderPipelineName];
  55045. pipeline.dispose();
  55046. }
  55047. }
  55048. };
  55049. return PostProcessRenderPipelineManager;
  55050. }());
  55051. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  55052. })(BABYLON || (BABYLON = {}));
  55053. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  55054. var BABYLON;
  55055. (function (BABYLON) {
  55056. var PostProcessRenderPass = (function () {
  55057. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  55058. this._refCount = 0;
  55059. this._name = name;
  55060. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  55061. this.setRenderList(renderList);
  55062. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  55063. this._renderTexture.onAfterRenderObservable.add(afterRender);
  55064. this._scene = scene;
  55065. this._renderList = renderList;
  55066. }
  55067. // private
  55068. PostProcessRenderPass.prototype._incRefCount = function () {
  55069. if (this._refCount === 0) {
  55070. this._scene.customRenderTargets.push(this._renderTexture);
  55071. }
  55072. return ++this._refCount;
  55073. };
  55074. PostProcessRenderPass.prototype._decRefCount = function () {
  55075. this._refCount--;
  55076. if (this._refCount <= 0) {
  55077. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  55078. }
  55079. return this._refCount;
  55080. };
  55081. PostProcessRenderPass.prototype._update = function () {
  55082. this.setRenderList(this._renderList);
  55083. };
  55084. // public
  55085. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  55086. this._renderTexture.renderList = renderList;
  55087. };
  55088. PostProcessRenderPass.prototype.getRenderTexture = function () {
  55089. return this._renderTexture;
  55090. };
  55091. return PostProcessRenderPass;
  55092. }());
  55093. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  55094. })(BABYLON || (BABYLON = {}));
  55095. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  55096. var BABYLON;
  55097. (function (BABYLON) {
  55098. var PostProcessRenderEffect = (function () {
  55099. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  55100. this._engine = engine;
  55101. this._name = name;
  55102. this._singleInstance = singleInstance || true;
  55103. this._getPostProcess = getPostProcess;
  55104. this._cameras = [];
  55105. this._indicesForCamera = [];
  55106. this._postProcesses = {};
  55107. this._renderPasses = {};
  55108. this._renderEffectAsPasses = {};
  55109. }
  55110. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  55111. get: function () {
  55112. for (var index in this._postProcesses) {
  55113. if (!this._postProcesses[index].isSupported) {
  55114. return false;
  55115. }
  55116. }
  55117. return true;
  55118. },
  55119. enumerable: true,
  55120. configurable: true
  55121. });
  55122. PostProcessRenderEffect.prototype._update = function () {
  55123. for (var renderPassName in this._renderPasses) {
  55124. this._renderPasses[renderPassName]._update();
  55125. }
  55126. };
  55127. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  55128. this._renderPasses[renderPass._name] = renderPass;
  55129. this._linkParameters();
  55130. };
  55131. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  55132. delete this._renderPasses[renderPass._name];
  55133. this._linkParameters();
  55134. };
  55135. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  55136. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  55137. this._linkParameters();
  55138. };
  55139. PostProcessRenderEffect.prototype.getPass = function (passName) {
  55140. for (var renderPassName in this._renderPasses) {
  55141. if (renderPassName === passName) {
  55142. return this._renderPasses[passName];
  55143. }
  55144. }
  55145. return null;
  55146. };
  55147. PostProcessRenderEffect.prototype.emptyPasses = function () {
  55148. this._renderPasses = {};
  55149. this._linkParameters();
  55150. };
  55151. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  55152. var cameraKey;
  55153. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  55154. for (var i = 0; i < _cam.length; i++) {
  55155. var camera = _cam[i];
  55156. var cameraName = camera.name;
  55157. if (this._singleInstance) {
  55158. cameraKey = 0;
  55159. }
  55160. else {
  55161. cameraKey = cameraName;
  55162. }
  55163. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  55164. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  55165. if (!this._indicesForCamera[cameraName]) {
  55166. this._indicesForCamera[cameraName] = [];
  55167. }
  55168. this._indicesForCamera[cameraName].push(index);
  55169. if (this._cameras.indexOf(camera) === -1) {
  55170. this._cameras[cameraName] = camera;
  55171. }
  55172. for (var passName in this._renderPasses) {
  55173. this._renderPasses[passName]._incRefCount();
  55174. }
  55175. }
  55176. this._linkParameters();
  55177. };
  55178. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  55179. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  55180. for (var i = 0; i < _cam.length; i++) {
  55181. var camera = _cam[i];
  55182. var cameraName = camera.name;
  55183. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  55184. var index = this._cameras.indexOf(cameraName);
  55185. this._indicesForCamera.splice(index, 1);
  55186. this._cameras.splice(index, 1);
  55187. for (var passName in this._renderPasses) {
  55188. this._renderPasses[passName]._decRefCount();
  55189. }
  55190. }
  55191. };
  55192. PostProcessRenderEffect.prototype._enable = function (cameras) {
  55193. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  55194. for (var i = 0; i < _cam.length; i++) {
  55195. var camera = _cam[i];
  55196. var cameraName = camera.name;
  55197. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  55198. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  55199. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  55200. }
  55201. }
  55202. for (var passName in this._renderPasses) {
  55203. this._renderPasses[passName]._incRefCount();
  55204. }
  55205. }
  55206. };
  55207. PostProcessRenderEffect.prototype._disable = function (cameras) {
  55208. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  55209. for (var i = 0; i < _cam.length; i++) {
  55210. var camera = _cam[i];
  55211. var cameraName = camera.Name;
  55212. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  55213. for (var passName in this._renderPasses) {
  55214. this._renderPasses[passName]._decRefCount();
  55215. }
  55216. }
  55217. };
  55218. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  55219. if (this._singleInstance) {
  55220. return this._postProcesses[0];
  55221. }
  55222. else {
  55223. return this._postProcesses[camera.name];
  55224. }
  55225. };
  55226. PostProcessRenderEffect.prototype._linkParameters = function () {
  55227. var _this = this;
  55228. for (var index in this._postProcesses) {
  55229. if (this.applyParameters) {
  55230. this.applyParameters(this._postProcesses[index]);
  55231. }
  55232. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  55233. _this._linkTextures(effect);
  55234. });
  55235. }
  55236. };
  55237. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  55238. for (var renderPassName in this._renderPasses) {
  55239. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  55240. }
  55241. for (var renderEffectName in this._renderEffectAsPasses) {
  55242. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  55243. }
  55244. };
  55245. return PostProcessRenderEffect;
  55246. }());
  55247. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  55248. })(BABYLON || (BABYLON = {}));
  55249. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  55250. var BABYLON;
  55251. (function (BABYLON) {
  55252. var PostProcessRenderPipeline = (function () {
  55253. function PostProcessRenderPipeline(engine, name) {
  55254. this._engine = engine;
  55255. this._name = name;
  55256. this._renderEffects = new Array();
  55257. this._renderEffectsForIsolatedPass = new Array();
  55258. this._cameras = [];
  55259. }
  55260. PostProcessRenderPipeline.prototype.getClassName = function () {
  55261. return "PostProcessRenderPipeline";
  55262. };
  55263. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  55264. get: function () {
  55265. for (var renderEffectName in this._renderEffects) {
  55266. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  55267. if (!this._renderEffects[renderEffectName].isSupported) {
  55268. return false;
  55269. }
  55270. }
  55271. }
  55272. return true;
  55273. },
  55274. enumerable: true,
  55275. configurable: true
  55276. });
  55277. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  55278. this._renderEffects[renderEffect._name] = renderEffect;
  55279. };
  55280. // private
  55281. PostProcessRenderPipeline.prototype._rebuild = function () {
  55282. };
  55283. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  55284. var renderEffects = this._renderEffects[renderEffectName];
  55285. if (!renderEffects) {
  55286. return;
  55287. }
  55288. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  55289. };
  55290. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  55291. var renderEffects = this._renderEffects[renderEffectName];
  55292. if (!renderEffects) {
  55293. return;
  55294. }
  55295. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  55296. };
  55297. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  55298. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  55299. var indicesToDelete = [];
  55300. var i;
  55301. for (i = 0; i < _cam.length; i++) {
  55302. var camera = _cam[i];
  55303. var cameraName = camera.name;
  55304. if (this._cameras.indexOf(camera) === -1) {
  55305. this._cameras[cameraName] = camera;
  55306. }
  55307. else if (unique) {
  55308. indicesToDelete.push(i);
  55309. }
  55310. }
  55311. for (i = 0; i < indicesToDelete.length; i++) {
  55312. cameras.splice(indicesToDelete[i], 1);
  55313. }
  55314. for (var renderEffectName in this._renderEffects) {
  55315. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  55316. this._renderEffects[renderEffectName]._attachCameras(_cam);
  55317. }
  55318. }
  55319. };
  55320. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  55321. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  55322. for (var renderEffectName in this._renderEffects) {
  55323. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  55324. this._renderEffects[renderEffectName]._detachCameras(_cam);
  55325. }
  55326. }
  55327. for (var i = 0; i < _cam.length; i++) {
  55328. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  55329. }
  55330. };
  55331. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  55332. var _this = this;
  55333. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  55334. var pass = null;
  55335. var renderEffectName;
  55336. for (renderEffectName in this._renderEffects) {
  55337. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  55338. pass = this._renderEffects[renderEffectName].getPass(passName);
  55339. if (pass != null) {
  55340. break;
  55341. }
  55342. }
  55343. }
  55344. if (pass === null) {
  55345. return;
  55346. }
  55347. for (renderEffectName in this._renderEffects) {
  55348. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  55349. this._renderEffects[renderEffectName]._disable(_cam);
  55350. }
  55351. }
  55352. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  55353. for (var i = 0; i < _cam.length; i++) {
  55354. var camera = _cam[i];
  55355. var cameraName = camera.name;
  55356. 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, null, _this._engine, true); });
  55357. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  55358. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  55359. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  55360. }
  55361. };
  55362. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  55363. var _this = this;
  55364. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  55365. for (var i = 0; i < _cam.length; i++) {
  55366. var camera = _cam[i];
  55367. var cameraName = camera.name;
  55368. 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, null, _this._engine, true); });
  55369. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  55370. }
  55371. for (var renderEffectName in this._renderEffects) {
  55372. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  55373. this._renderEffects[renderEffectName]._enable(_cam);
  55374. }
  55375. }
  55376. };
  55377. PostProcessRenderPipeline.prototype._update = function () {
  55378. for (var renderEffectName in this._renderEffects) {
  55379. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  55380. this._renderEffects[renderEffectName]._update();
  55381. }
  55382. }
  55383. for (var i = 0; i < this._cameras.length; i++) {
  55384. var cameraName = this._cameras[i].name;
  55385. if (this._renderEffectsForIsolatedPass[cameraName]) {
  55386. this._renderEffectsForIsolatedPass[cameraName]._update();
  55387. }
  55388. }
  55389. };
  55390. PostProcessRenderPipeline.prototype._reset = function () {
  55391. this._renderEffects = new Array();
  55392. this._renderEffectsForIsolatedPass = new Array();
  55393. };
  55394. PostProcessRenderPipeline.prototype.dispose = function () {
  55395. // Must be implemented by children
  55396. };
  55397. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  55398. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  55399. __decorate([
  55400. BABYLON.serialize()
  55401. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  55402. return PostProcessRenderPipeline;
  55403. }());
  55404. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  55405. })(BABYLON || (BABYLON = {}));
  55406. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  55407. var BABYLON;
  55408. (function (BABYLON) {
  55409. var DepthRenderer = (function () {
  55410. function DepthRenderer(scene, type) {
  55411. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  55412. var _this = this;
  55413. this._scene = scene;
  55414. var engine = scene.getEngine();
  55415. // Render target
  55416. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  55417. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55418. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55419. this._depthMap.refreshRate = 1;
  55420. this._depthMap.renderParticles = false;
  55421. this._depthMap.renderList = null;
  55422. // set default depth value to 1.0 (far away)
  55423. this._depthMap.onClearObservable.add(function (engine) {
  55424. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  55425. });
  55426. // Custom render function
  55427. var renderSubMesh = function (subMesh) {
  55428. var mesh = subMesh.getRenderingMesh();
  55429. var scene = _this._scene;
  55430. var engine = scene.getEngine();
  55431. // Culling
  55432. engine.setState(subMesh.getMaterial().backFaceCulling);
  55433. // Managing instances
  55434. var batch = mesh._getInstancesRenderList(subMesh._id);
  55435. if (batch.mustReturn) {
  55436. return;
  55437. }
  55438. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  55439. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  55440. engine.enableEffect(_this._effect);
  55441. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  55442. var material = subMesh.getMaterial();
  55443. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  55444. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  55445. // Alpha test
  55446. if (material && material.needAlphaTesting()) {
  55447. var alphaTexture = material.getAlphaTestTexture();
  55448. _this._effect.setTexture("diffuseSampler", alphaTexture);
  55449. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  55450. }
  55451. // Bones
  55452. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55453. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  55454. }
  55455. // Draw
  55456. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  55457. }
  55458. };
  55459. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  55460. var index;
  55461. if (depthOnlySubMeshes.length) {
  55462. engine.setColorWrite(false);
  55463. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  55464. renderSubMesh(depthOnlySubMeshes.data[index]);
  55465. }
  55466. engine.setColorWrite(true);
  55467. }
  55468. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55469. renderSubMesh(opaqueSubMeshes.data[index]);
  55470. }
  55471. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55472. renderSubMesh(alphaTestSubMeshes.data[index]);
  55473. }
  55474. };
  55475. }
  55476. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  55477. var material = subMesh.getMaterial();
  55478. if (material.disableDepthWrite) {
  55479. return false;
  55480. }
  55481. var defines = [];
  55482. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55483. var mesh = subMesh.getMesh();
  55484. // Alpha test
  55485. if (material && material.needAlphaTesting()) {
  55486. defines.push("#define ALPHATEST");
  55487. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55488. attribs.push(BABYLON.VertexBuffer.UVKind);
  55489. defines.push("#define UV1");
  55490. }
  55491. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55492. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55493. defines.push("#define UV2");
  55494. }
  55495. }
  55496. // Bones
  55497. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55498. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55499. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55500. if (mesh.numBoneInfluencers > 4) {
  55501. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55502. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55503. }
  55504. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55505. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55506. }
  55507. else {
  55508. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55509. }
  55510. // Instances
  55511. if (useInstances) {
  55512. defines.push("#define INSTANCES");
  55513. attribs.push("world0");
  55514. attribs.push("world1");
  55515. attribs.push("world2");
  55516. attribs.push("world3");
  55517. }
  55518. // Get correct effect
  55519. var join = defines.join("\n");
  55520. if (this._cachedDefines !== join) {
  55521. this._cachedDefines = join;
  55522. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  55523. }
  55524. return this._effect.isReady();
  55525. };
  55526. DepthRenderer.prototype.getDepthMap = function () {
  55527. return this._depthMap;
  55528. };
  55529. // Methods
  55530. DepthRenderer.prototype.dispose = function () {
  55531. this._depthMap.dispose();
  55532. };
  55533. return DepthRenderer;
  55534. }());
  55535. BABYLON.DepthRenderer = DepthRenderer;
  55536. })(BABYLON || (BABYLON = {}));
  55537. //# sourceMappingURL=babylon.depthRenderer.js.map
  55538. var BABYLON;
  55539. (function (BABYLON) {
  55540. var SSAORenderingPipeline = (function (_super) {
  55541. __extends(SSAORenderingPipeline, _super);
  55542. /**
  55543. * @constructor
  55544. * @param {string} name - The rendering pipeline name
  55545. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55546. * @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 }
  55547. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55548. */
  55549. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  55550. var _this = _super.call(this, scene.getEngine(), name) || this;
  55551. // Members
  55552. /**
  55553. * The PassPostProcess id in the pipeline that contains the original scene color
  55554. * @type {string}
  55555. */
  55556. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  55557. /**
  55558. * The SSAO PostProcess id in the pipeline
  55559. * @type {string}
  55560. */
  55561. _this.SSAORenderEffect = "SSAORenderEffect";
  55562. /**
  55563. * The horizontal blur PostProcess id in the pipeline
  55564. * @type {string}
  55565. */
  55566. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  55567. /**
  55568. * The vertical blur PostProcess id in the pipeline
  55569. * @type {string}
  55570. */
  55571. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  55572. /**
  55573. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  55574. * @type {string}
  55575. */
  55576. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  55577. /**
  55578. * The output strength of the SSAO post-process. Default value is 1.0.
  55579. * @type {number}
  55580. */
  55581. _this.totalStrength = 1.0;
  55582. /**
  55583. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  55584. * @type {number}
  55585. */
  55586. _this.radius = 0.0001;
  55587. /**
  55588. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  55589. * Must not be equal to fallOff and superior to fallOff.
  55590. * Default value is 0.975
  55591. * @type {number}
  55592. */
  55593. _this.area = 0.0075;
  55594. /**
  55595. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  55596. * Must not be equal to area and inferior to area.
  55597. * Default value is 0.0
  55598. * @type {number}
  55599. */
  55600. _this.fallOff = 0.000001;
  55601. /**
  55602. * The base color of the SSAO post-process
  55603. * The final result is "base + ssao" between [0, 1]
  55604. * @type {number}
  55605. */
  55606. _this.base = 0.5;
  55607. _this._firstUpdate = true;
  55608. _this._scene = scene;
  55609. // Set up assets
  55610. _this._createRandomTexture();
  55611. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  55612. var ssaoRatio = ratio.ssaoRatio || ratio;
  55613. var combineRatio = ratio.combineRatio || ratio;
  55614. _this._ratio = {
  55615. ssaoRatio: ssaoRatio,
  55616. combineRatio: combineRatio
  55617. };
  55618. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  55619. _this._createSSAOPostProcess(ssaoRatio);
  55620. _this._createBlurPostProcess(ssaoRatio);
  55621. _this._createSSAOCombinePostProcess(combineRatio);
  55622. // Set up pipeline
  55623. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  55624. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  55625. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  55626. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  55627. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  55628. // Finish
  55629. scene.postProcessRenderPipelineManager.addPipeline(_this);
  55630. if (cameras)
  55631. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55632. return _this;
  55633. }
  55634. // Public Methods
  55635. /**
  55636. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  55637. */
  55638. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  55639. if (disableDepthRender === void 0) { disableDepthRender = false; }
  55640. for (var i = 0; i < this._scene.cameras.length; i++) {
  55641. var camera = this._scene.cameras[i];
  55642. this._originalColorPostProcess.dispose(camera);
  55643. this._ssaoPostProcess.dispose(camera);
  55644. this._blurHPostProcess.dispose(camera);
  55645. this._blurVPostProcess.dispose(camera);
  55646. this._ssaoCombinePostProcess.dispose(camera);
  55647. }
  55648. this._randomTexture.dispose();
  55649. if (disableDepthRender)
  55650. this._scene.disableDepthRenderer();
  55651. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55652. _super.prototype.dispose.call(this);
  55653. };
  55654. // Private Methods
  55655. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  55656. var _this = this;
  55657. /*
  55658. var samplerOffsets = [
  55659. -8.0, -6.0, -4.0, -2.0,
  55660. 0.0,
  55661. 2.0, 4.0, 6.0, 8.0
  55662. ];
  55663. */
  55664. var samplerOffsets = new Array();
  55665. for (var i = -8; i < 8; i++) {
  55666. samplerOffsets.push(i * 2);
  55667. }
  55668. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16");
  55669. this._blurHPostProcess.onApply = function (effect) {
  55670. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  55671. effect.setTexture("depthSampler", _this._depthTexture);
  55672. if (_this._firstUpdate) {
  55673. effect.setArray("samplerOffsets", samplerOffsets);
  55674. }
  55675. };
  55676. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define SAMPLES 16");
  55677. this._blurVPostProcess.onApply = function (effect) {
  55678. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  55679. effect.setTexture("depthSampler", _this._depthTexture);
  55680. if (_this._firstUpdate) {
  55681. effect.setArray("samplerOffsets", samplerOffsets);
  55682. _this._firstUpdate = false;
  55683. }
  55684. };
  55685. };
  55686. SSAORenderingPipeline.prototype._rebuild = function () {
  55687. this._firstUpdate = true;
  55688. _super.prototype._rebuild.call(this);
  55689. };
  55690. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  55691. var _this = this;
  55692. var numSamples = 16;
  55693. var sampleSphere = [
  55694. 0.5381, 0.1856, -0.4319,
  55695. 0.1379, 0.2486, 0.4430,
  55696. 0.3371, 0.5679, -0.0057,
  55697. -0.6999, -0.0451, -0.0019,
  55698. 0.0689, -0.1598, -0.8547,
  55699. 0.0560, 0.0069, -0.1843,
  55700. -0.0146, 0.1402, 0.0762,
  55701. 0.0100, -0.1924, -0.0344,
  55702. -0.3577, -0.5301, -0.4358,
  55703. -0.3169, 0.1063, 0.0158,
  55704. 0.0103, -0.5869, 0.0046,
  55705. -0.0897, -0.4940, 0.3287,
  55706. 0.7119, -0.0154, -0.0918,
  55707. -0.0533, 0.0596, -0.5411,
  55708. 0.0352, -0.0631, 0.5460,
  55709. -0.4776, 0.2847, -0.0271
  55710. ];
  55711. var samplesFactor = 1.0 / numSamples;
  55712. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  55713. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  55714. "area", "fallOff", "base", "range", "viewport"
  55715. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  55716. this._ssaoPostProcess.onApply = function (effect) {
  55717. if (_this._firstUpdate) {
  55718. effect.setArray3("sampleSphere", sampleSphere);
  55719. effect.setFloat("samplesFactor", samplesFactor);
  55720. effect.setFloat("randTextureTiles", 4.0);
  55721. }
  55722. effect.setFloat("totalStrength", _this.totalStrength);
  55723. effect.setFloat("radius", _this.radius);
  55724. effect.setFloat("area", _this.area);
  55725. effect.setFloat("fallOff", _this.fallOff);
  55726. effect.setFloat("base", _this.base);
  55727. effect.setTexture("textureSampler", _this._depthTexture);
  55728. effect.setTexture("randomSampler", _this._randomTexture);
  55729. };
  55730. };
  55731. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  55732. var _this = this;
  55733. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  55734. this._ssaoCombinePostProcess.onApply = function (effect) {
  55735. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  55736. };
  55737. };
  55738. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  55739. var size = 512;
  55740. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  55741. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55742. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55743. var context = this._randomTexture.getContext();
  55744. var rand = function (min, max) {
  55745. return Math.random() * (max - min) + min;
  55746. };
  55747. var randVector = BABYLON.Vector3.Zero();
  55748. for (var x = 0; x < size; x++) {
  55749. for (var y = 0; y < size; y++) {
  55750. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  55751. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  55752. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  55753. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  55754. context.fillRect(x, y, 1, 1);
  55755. }
  55756. }
  55757. this._randomTexture.update(false);
  55758. };
  55759. __decorate([
  55760. BABYLON.serialize()
  55761. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  55762. __decorate([
  55763. BABYLON.serialize()
  55764. ], SSAORenderingPipeline.prototype, "radius", void 0);
  55765. __decorate([
  55766. BABYLON.serialize()
  55767. ], SSAORenderingPipeline.prototype, "area", void 0);
  55768. __decorate([
  55769. BABYLON.serialize()
  55770. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  55771. __decorate([
  55772. BABYLON.serialize()
  55773. ], SSAORenderingPipeline.prototype, "base", void 0);
  55774. __decorate([
  55775. BABYLON.serialize()
  55776. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  55777. return SSAORenderingPipeline;
  55778. }(BABYLON.PostProcessRenderPipeline));
  55779. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  55780. })(BABYLON || (BABYLON = {}));
  55781. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  55782. var BABYLON;
  55783. (function (BABYLON) {
  55784. var SSAO2RenderingPipeline = (function (_super) {
  55785. __extends(SSAO2RenderingPipeline, _super);
  55786. /**
  55787. * @constructor
  55788. * @param {string} name - The rendering pipeline name
  55789. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55790. * @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 }
  55791. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55792. */
  55793. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  55794. var _this = _super.call(this, scene.getEngine(), name) || this;
  55795. // Members
  55796. /**
  55797. * The PassPostProcess id in the pipeline that contains the original scene color
  55798. * @type {string}
  55799. */
  55800. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  55801. /**
  55802. * The SSAO PostProcess id in the pipeline
  55803. * @type {string}
  55804. */
  55805. _this.SSAORenderEffect = "SSAORenderEffect";
  55806. /**
  55807. * The horizontal blur PostProcess id in the pipeline
  55808. * @type {string}
  55809. */
  55810. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  55811. /**
  55812. * The vertical blur PostProcess id in the pipeline
  55813. * @type {string}
  55814. */
  55815. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  55816. /**
  55817. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  55818. * @type {string}
  55819. */
  55820. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  55821. /**
  55822. * The output strength of the SSAO post-process. Default value is 1.0.
  55823. * @type {number}
  55824. */
  55825. _this.totalStrength = 1.0;
  55826. /**
  55827. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  55828. * @type {number}
  55829. */
  55830. _this.maxZ = 100.0;
  55831. /**
  55832. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  55833. * @type {number}
  55834. */
  55835. _this.minZAspect = 0.2;
  55836. /**
  55837. * Number of samples used for the SSAO calculations. Default value is 8
  55838. * @type {number}
  55839. */
  55840. _this._samples = 8;
  55841. /**
  55842. * Are we using bilateral blur ?
  55843. * @type {boolean}
  55844. */
  55845. _this._expensiveBlur = true;
  55846. /**
  55847. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  55848. * @type {number}
  55849. */
  55850. _this.radius = 2.0;
  55851. /**
  55852. * The base color of the SSAO post-process
  55853. * The final result is "base + ssao" between [0, 1]
  55854. * @type {number}
  55855. */
  55856. _this.base = 0.1;
  55857. _this._firstUpdate = true;
  55858. _this._scene = scene;
  55859. if (!_this.isSupported) {
  55860. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  55861. return _this;
  55862. }
  55863. var ssaoRatio = ratio.ssaoRatio || ratio;
  55864. var blurRatio = ratio.blurRatio || ratio;
  55865. _this._ratio = {
  55866. ssaoRatio: ssaoRatio,
  55867. blurRatio: blurRatio
  55868. };
  55869. // Set up assets
  55870. _this._createRandomTexture();
  55871. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  55872. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  55873. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  55874. _this._createSSAOPostProcess(1.0);
  55875. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  55876. _this._createSSAOCombinePostProcess(blurRatio);
  55877. // Set up pipeline
  55878. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  55879. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  55880. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  55881. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  55882. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  55883. // Finish
  55884. scene.postProcessRenderPipelineManager.addPipeline(_this);
  55885. if (cameras)
  55886. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55887. return _this;
  55888. }
  55889. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  55890. get: function () {
  55891. return this._samples;
  55892. },
  55893. set: function (n) {
  55894. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  55895. this._samples = n;
  55896. this._sampleSphere = this._generateHemisphere();
  55897. this._firstUpdate = true;
  55898. },
  55899. enumerable: true,
  55900. configurable: true
  55901. });
  55902. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  55903. get: function () {
  55904. return this._expensiveBlur;
  55905. },
  55906. set: function (b) {
  55907. 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"]);
  55908. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  55909. this._expensiveBlur = b;
  55910. this._firstUpdate = true;
  55911. },
  55912. enumerable: true,
  55913. configurable: true
  55914. });
  55915. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  55916. /**
  55917. * Support test.
  55918. * @type {boolean}
  55919. */
  55920. get: function () {
  55921. var engine = BABYLON.Engine.LastCreatedEngine;
  55922. return engine.getCaps().drawBuffersExtension;
  55923. },
  55924. enumerable: true,
  55925. configurable: true
  55926. });
  55927. // Public Methods
  55928. /**
  55929. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  55930. */
  55931. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  55932. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  55933. for (var i = 0; i < this._scene.cameras.length; i++) {
  55934. var camera = this._scene.cameras[i];
  55935. this._originalColorPostProcess.dispose(camera);
  55936. this._ssaoPostProcess.dispose(camera);
  55937. this._blurHPostProcess.dispose(camera);
  55938. this._blurVPostProcess.dispose(camera);
  55939. this._ssaoCombinePostProcess.dispose(camera);
  55940. }
  55941. this._randomTexture.dispose();
  55942. if (disableGeometryBufferRenderer)
  55943. this._scene.disableGeometryBufferRenderer();
  55944. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55945. _super.prototype.dispose.call(this);
  55946. };
  55947. // Private Methods
  55948. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  55949. var _this = this;
  55950. this._samplerOffsets = [];
  55951. var expensive = this.expensiveBlur;
  55952. for (var i = -8; i < 8; i++) {
  55953. this._samplerOffsets.push(i * 2 + 0.5);
  55954. }
  55955. 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");
  55956. this._blurHPostProcess.onApply = function (effect) {
  55957. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  55958. effect.setFloat("near", _this._scene.activeCamera.minZ);
  55959. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  55960. effect.setFloat("radius", _this.radius);
  55961. effect.setTexture("depthSampler", _this._depthTexture);
  55962. if (_this._firstUpdate) {
  55963. effect.setArray("samplerOffsets", _this._samplerOffsets);
  55964. }
  55965. };
  55966. 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");
  55967. this._blurVPostProcess.onApply = function (effect) {
  55968. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  55969. effect.setFloat("near", _this._scene.activeCamera.minZ);
  55970. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  55971. effect.setFloat("radius", _this.radius);
  55972. effect.setTexture("depthSampler", _this._depthTexture);
  55973. if (_this._firstUpdate) {
  55974. effect.setArray("samplerOffsets", _this._samplerOffsets);
  55975. _this._firstUpdate = false;
  55976. }
  55977. };
  55978. };
  55979. SSAO2RenderingPipeline.prototype._rebuild = function () {
  55980. this._firstUpdate = true;
  55981. _super.prototype._rebuild.call(this);
  55982. };
  55983. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  55984. var numSamples = this.samples;
  55985. var result = [];
  55986. var vector, scale;
  55987. var rand = function (min, max) {
  55988. return Math.random() * (max - min) + min;
  55989. };
  55990. var i = 0;
  55991. while (i < numSamples) {
  55992. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  55993. vector.normalize();
  55994. scale = i / numSamples;
  55995. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  55996. vector.scaleInPlace(scale);
  55997. result.push(vector.x, vector.y, vector.z);
  55998. i++;
  55999. }
  56000. return result;
  56001. };
  56002. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  56003. var _this = this;
  56004. var numSamples = this.samples;
  56005. this._sampleSphere = this._generateHemisphere();
  56006. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  56007. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  56008. "base", "range", "projection", "near", "far", "texelSize",
  56009. "xViewport", "yViewport", "maxZ", "minZAspect"
  56010. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  56011. this._ssaoPostProcess.onApply = function (effect) {
  56012. if (_this._firstUpdate) {
  56013. effect.setArray3("sampleSphere", _this._sampleSphere);
  56014. effect.setFloat("randTextureTiles", 4.0);
  56015. }
  56016. effect.setFloat("samplesFactor", 1 / _this.samples);
  56017. effect.setFloat("totalStrength", _this.totalStrength);
  56018. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  56019. effect.setFloat("radius", _this.radius);
  56020. effect.setFloat("maxZ", _this.maxZ);
  56021. effect.setFloat("minZAspect", _this.minZAspect);
  56022. effect.setFloat("base", _this.base);
  56023. effect.setFloat("near", _this._scene.activeCamera.minZ);
  56024. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  56025. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  56026. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  56027. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  56028. effect.setTexture("textureSampler", _this._depthTexture);
  56029. effect.setTexture("normalSampler", _this._normalTexture);
  56030. effect.setTexture("randomSampler", _this._randomTexture);
  56031. };
  56032. };
  56033. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  56034. var _this = this;
  56035. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  56036. this._ssaoCombinePostProcess.onApply = function (effect) {
  56037. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  56038. };
  56039. };
  56040. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  56041. var size = 512;
  56042. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  56043. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56044. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56045. var context = this._randomTexture.getContext();
  56046. var rand = function (min, max) {
  56047. return Math.random() * (max - min) + min;
  56048. };
  56049. var randVector = BABYLON.Vector3.Zero();
  56050. for (var x = 0; x < size; x++) {
  56051. for (var y = 0; y < size; y++) {
  56052. randVector.x = rand(0.0, 1.0);
  56053. randVector.y = rand(0.0, 1.0);
  56054. randVector.z = 0.0;
  56055. randVector.normalize();
  56056. randVector.scaleInPlace(255);
  56057. randVector.x = Math.floor(randVector.x);
  56058. randVector.y = Math.floor(randVector.y);
  56059. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  56060. context.fillRect(x, y, 1, 1);
  56061. }
  56062. }
  56063. this._randomTexture.update(false);
  56064. };
  56065. __decorate([
  56066. BABYLON.serialize()
  56067. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  56068. __decorate([
  56069. BABYLON.serialize()
  56070. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  56071. __decorate([
  56072. BABYLON.serialize()
  56073. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  56074. __decorate([
  56075. BABYLON.serialize("samples")
  56076. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  56077. __decorate([
  56078. BABYLON.serialize("expensiveBlur")
  56079. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  56080. __decorate([
  56081. BABYLON.serialize()
  56082. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  56083. __decorate([
  56084. BABYLON.serialize()
  56085. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  56086. __decorate([
  56087. BABYLON.serialize()
  56088. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  56089. return SSAO2RenderingPipeline;
  56090. }(BABYLON.PostProcessRenderPipeline));
  56091. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  56092. })(BABYLON || (BABYLON = {}));
  56093. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  56094. // BABYLON.JS Chromatic Aberration GLSL Shader
  56095. // Author: Olivier Guyot
  56096. // Separates very slightly R, G and B colors on the edges of the screen
  56097. // Inspired by Francois Tarlier & Martins Upitis
  56098. var BABYLON;
  56099. (function (BABYLON) {
  56100. var LensRenderingPipeline = (function (_super) {
  56101. __extends(LensRenderingPipeline, _super);
  56102. /**
  56103. * @constructor
  56104. *
  56105. * Effect parameters are as follow:
  56106. * {
  56107. * chromatic_aberration: number; // from 0 to x (1 for realism)
  56108. * edge_blur: number; // from 0 to x (1 for realism)
  56109. * distortion: number; // from 0 to x (1 for realism)
  56110. * grain_amount: number; // from 0 to 1
  56111. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  56112. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  56113. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  56114. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  56115. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  56116. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  56117. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  56118. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  56119. * }
  56120. * Note: if an effect parameter is unset, effect is disabled
  56121. *
  56122. * @param {string} name - The rendering pipeline name
  56123. * @param {object} parameters - An object containing all parameters (see above)
  56124. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  56125. * @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)
  56126. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  56127. */
  56128. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  56129. if (ratio === void 0) { ratio = 1.0; }
  56130. var _this = _super.call(this, scene.getEngine(), name) || this;
  56131. // Lens effects can be of the following:
  56132. // - chromatic aberration (slight shift of RGB colors)
  56133. // - blur on the edge of the lens
  56134. // - lens distortion
  56135. // - depth-of-field blur & highlights enhancing
  56136. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  56137. // - grain effect (noise or custom texture)
  56138. // Two additional texture samplers are needed:
  56139. // - depth map (for depth-of-field)
  56140. // - grain texture
  56141. /**
  56142. * The chromatic aberration PostProcess id in the pipeline
  56143. * @type {string}
  56144. */
  56145. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  56146. /**
  56147. * The highlights enhancing PostProcess id in the pipeline
  56148. * @type {string}
  56149. */
  56150. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  56151. /**
  56152. * The depth-of-field PostProcess id in the pipeline
  56153. * @type {string}
  56154. */
  56155. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  56156. _this._scene = scene;
  56157. // Fetch texture samplers
  56158. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  56159. if (parameters.grain_texture) {
  56160. _this._grainTexture = parameters.grain_texture;
  56161. }
  56162. else {
  56163. _this._createGrainTexture();
  56164. }
  56165. // save parameters
  56166. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  56167. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  56168. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  56169. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  56170. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  56171. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  56172. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  56173. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  56174. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  56175. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  56176. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  56177. // Create effects
  56178. _this._createChromaticAberrationPostProcess(ratio);
  56179. _this._createHighlightsPostProcess(ratio);
  56180. _this._createDepthOfFieldPostProcess(ratio / 4);
  56181. // Set up pipeline
  56182. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  56183. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  56184. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  56185. if (_this._highlightsGain === -1) {
  56186. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  56187. }
  56188. // Finish
  56189. scene.postProcessRenderPipelineManager.addPipeline(_this);
  56190. if (cameras) {
  56191. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  56192. }
  56193. return _this;
  56194. }
  56195. // public methods (self explanatory)
  56196. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  56197. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  56198. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  56199. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  56200. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  56201. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  56202. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  56203. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  56204. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  56205. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  56206. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  56207. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  56208. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  56209. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  56210. };
  56211. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  56212. this._highlightsPostProcess.updateEffect();
  56213. };
  56214. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  56215. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  56216. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  56217. this._highlightsGain = amount;
  56218. };
  56219. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  56220. if (this._highlightsGain === -1) {
  56221. this._highlightsGain = 1.0;
  56222. }
  56223. this._highlightsThreshold = amount;
  56224. };
  56225. LensRenderingPipeline.prototype.disableHighlights = function () {
  56226. this._highlightsGain = -1;
  56227. };
  56228. /**
  56229. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  56230. */
  56231. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  56232. if (disableDepthRender === void 0) { disableDepthRender = false; }
  56233. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  56234. this._chromaticAberrationPostProcess = undefined;
  56235. this._highlightsPostProcess = undefined;
  56236. this._depthOfFieldPostProcess = undefined;
  56237. this._grainTexture.dispose();
  56238. if (disableDepthRender)
  56239. this._scene.disableDepthRenderer();
  56240. };
  56241. // colors shifting and distortion
  56242. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  56243. var _this = this;
  56244. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  56245. [], // samplers
  56246. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  56247. this._chromaticAberrationPostProcess.onApply = function (effect) {
  56248. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  56249. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  56250. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  56251. };
  56252. };
  56253. // highlights enhancing
  56254. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  56255. var _this = this;
  56256. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  56257. [], // samplers
  56258. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  56259. this._highlightsPostProcess.onApply = function (effect) {
  56260. effect.setFloat('gain', _this._highlightsGain);
  56261. effect.setFloat('threshold', _this._highlightsThreshold);
  56262. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  56263. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  56264. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  56265. };
  56266. };
  56267. // colors shifting and distortion
  56268. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  56269. var _this = this;
  56270. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  56271. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  56272. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  56273. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  56274. this._depthOfFieldPostProcess.onApply = function (effect) {
  56275. effect.setTexture("depthSampler", _this._depthTexture);
  56276. effect.setTexture("grainSampler", _this._grainTexture);
  56277. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  56278. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  56279. effect.setFloat('grain_amount', _this._grainAmount);
  56280. effect.setBool('blur_noise', _this._blurNoise);
  56281. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  56282. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  56283. effect.setFloat('distortion', _this._distortion);
  56284. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  56285. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  56286. effect.setFloat('aperture', _this._dofAperture);
  56287. effect.setFloat('darken', _this._dofDarken);
  56288. effect.setFloat('edge_blur', _this._edgeBlur);
  56289. effect.setBool('highlights', (_this._highlightsGain !== -1));
  56290. effect.setFloat('near', _this._scene.activeCamera.minZ);
  56291. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  56292. };
  56293. };
  56294. // creates a black and white random noise texture, 512x512
  56295. LensRenderingPipeline.prototype._createGrainTexture = function () {
  56296. var size = 512;
  56297. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56298. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56299. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56300. var context = this._grainTexture.getContext();
  56301. var rand = function (min, max) {
  56302. return Math.random() * (max - min) + min;
  56303. };
  56304. var value;
  56305. for (var x = 0; x < size; x++) {
  56306. for (var y = 0; y < size; y++) {
  56307. value = Math.floor(rand(0.42, 0.58) * 255);
  56308. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  56309. context.fillRect(x, y, 1, 1);
  56310. }
  56311. }
  56312. this._grainTexture.update(false);
  56313. };
  56314. return LensRenderingPipeline;
  56315. }(BABYLON.PostProcessRenderPipeline));
  56316. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  56317. })(BABYLON || (BABYLON = {}));
  56318. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  56319. var BABYLON;
  56320. (function (BABYLON) {
  56321. var StandardRenderingPipeline = (function (_super) {
  56322. __extends(StandardRenderingPipeline, _super);
  56323. /**
  56324. * @constructor
  56325. * @param {string} name - The rendering pipeline name
  56326. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  56327. * @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)
  56328. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  56329. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  56330. */
  56331. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  56332. if (originalPostProcess === void 0) { originalPostProcess = null; }
  56333. var _this = _super.call(this, scene.getEngine(), name) || this;
  56334. _this.downSampleX4PostProcess = null;
  56335. _this.brightPassPostProcess = null;
  56336. _this.blurHPostProcesses = [];
  56337. _this.blurVPostProcesses = [];
  56338. _this.textureAdderPostProcess = null;
  56339. _this.volumetricLightPostProcess = null;
  56340. _this.volumetricLightSmoothXPostProcess = null;
  56341. _this.volumetricLightSmoothYPostProcess = null;
  56342. _this.volumetricLightMergePostProces = null;
  56343. _this.volumetricLightFinalPostProcess = null;
  56344. _this.luminancePostProcess = null;
  56345. _this.luminanceDownSamplePostProcesses = [];
  56346. _this.hdrPostProcess = null;
  56347. _this.textureAdderFinalPostProcess = null;
  56348. _this.lensFlareFinalPostProcess = null;
  56349. _this.hdrFinalPostProcess = null;
  56350. _this.lensFlarePostProcess = null;
  56351. _this.lensFlareComposePostProcess = null;
  56352. _this.motionBlurPostProcess = null;
  56353. _this.depthOfFieldPostProcess = null;
  56354. // Values
  56355. _this.brightThreshold = 1.0;
  56356. _this.blurWidth = 512.0;
  56357. _this.horizontalBlur = false;
  56358. _this.exposure = 1.0;
  56359. _this.lensTexture = null;
  56360. _this.volumetricLightCoefficient = 0.2;
  56361. _this.volumetricLightPower = 4.0;
  56362. _this.volumetricLightBlurScale = 64.0;
  56363. _this.sourceLight = null;
  56364. _this.hdrMinimumLuminance = 1.0;
  56365. _this.hdrDecreaseRate = 0.5;
  56366. _this.hdrIncreaseRate = 0.5;
  56367. _this.lensColorTexture = null;
  56368. _this.lensFlareStrength = 20.0;
  56369. _this.lensFlareGhostDispersal = 1.4;
  56370. _this.lensFlareHaloWidth = 0.7;
  56371. _this.lensFlareDistortionStrength = 16.0;
  56372. _this.lensStarTexture = null;
  56373. _this.lensFlareDirtTexture = null;
  56374. _this.depthOfFieldDistance = 10.0;
  56375. _this.depthOfFieldBlurWidth = 64.0;
  56376. _this.motionStrength = 1.0;
  56377. // IAnimatable
  56378. _this.animations = [];
  56379. _this._currentDepthOfFieldSource = null;
  56380. _this._hdrCurrentLuminance = 1.0;
  56381. // Getters and setters
  56382. _this._bloomEnabled = true;
  56383. _this._depthOfFieldEnabled = false;
  56384. _this._vlsEnabled = false;
  56385. _this._lensFlareEnabled = false;
  56386. _this._hdrEnabled = false;
  56387. _this._motionBlurEnabled = false;
  56388. _this._motionBlurSamples = 64.0;
  56389. _this._volumetricLightStepsCount = 50.0;
  56390. _this._cameras = cameras || [];
  56391. // Initialize
  56392. _this._scene = scene;
  56393. _this._basePostProcess = originalPostProcess;
  56394. _this._ratio = ratio;
  56395. // Misc
  56396. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56397. // Finish
  56398. scene.postProcessRenderPipelineManager.addPipeline(_this);
  56399. _this._buildPipeline();
  56400. return _this;
  56401. }
  56402. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  56403. get: function () {
  56404. return this._bloomEnabled;
  56405. },
  56406. set: function (enabled) {
  56407. if (this._bloomEnabled === enabled) {
  56408. return;
  56409. }
  56410. this._bloomEnabled = enabled;
  56411. this._buildPipeline();
  56412. },
  56413. enumerable: true,
  56414. configurable: true
  56415. });
  56416. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  56417. get: function () {
  56418. return this._depthOfFieldEnabled;
  56419. },
  56420. set: function (enabled) {
  56421. if (this._depthOfFieldEnabled === enabled) {
  56422. return;
  56423. }
  56424. this._depthOfFieldEnabled = enabled;
  56425. this._buildPipeline();
  56426. },
  56427. enumerable: true,
  56428. configurable: true
  56429. });
  56430. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  56431. get: function () {
  56432. return this._lensFlareEnabled;
  56433. },
  56434. set: function (enabled) {
  56435. if (this._lensFlareEnabled === enabled) {
  56436. return;
  56437. }
  56438. this._lensFlareEnabled = enabled;
  56439. this._buildPipeline();
  56440. },
  56441. enumerable: true,
  56442. configurable: true
  56443. });
  56444. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  56445. get: function () {
  56446. return this._hdrEnabled;
  56447. },
  56448. set: function (enabled) {
  56449. if (this._hdrEnabled === enabled) {
  56450. return;
  56451. }
  56452. this._hdrEnabled = enabled;
  56453. this._buildPipeline();
  56454. },
  56455. enumerable: true,
  56456. configurable: true
  56457. });
  56458. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  56459. get: function () {
  56460. return this._vlsEnabled;
  56461. },
  56462. set: function (enabled) {
  56463. if (this._vlsEnabled === enabled) {
  56464. return;
  56465. }
  56466. if (enabled) {
  56467. var geometry = this._scene.enableGeometryBufferRenderer();
  56468. if (!geometry) {
  56469. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  56470. return;
  56471. }
  56472. }
  56473. this._vlsEnabled = enabled;
  56474. this._buildPipeline();
  56475. },
  56476. enumerable: true,
  56477. configurable: true
  56478. });
  56479. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  56480. get: function () {
  56481. return this._motionBlurEnabled;
  56482. },
  56483. set: function (enabled) {
  56484. if (this._motionBlurEnabled === enabled) {
  56485. return;
  56486. }
  56487. this._motionBlurEnabled = enabled;
  56488. this._buildPipeline();
  56489. },
  56490. enumerable: true,
  56491. configurable: true
  56492. });
  56493. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  56494. get: function () {
  56495. return this._volumetricLightStepsCount;
  56496. },
  56497. set: function (count) {
  56498. if (this.volumetricLightPostProcess) {
  56499. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  56500. }
  56501. this._volumetricLightStepsCount = count;
  56502. },
  56503. enumerable: true,
  56504. configurable: true
  56505. });
  56506. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  56507. get: function () {
  56508. return this._motionBlurSamples;
  56509. },
  56510. set: function (samples) {
  56511. if (this.motionBlurPostProcess) {
  56512. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  56513. }
  56514. this._motionBlurSamples = samples;
  56515. },
  56516. enumerable: true,
  56517. configurable: true
  56518. });
  56519. StandardRenderingPipeline.prototype._buildPipeline = function () {
  56520. var _this = this;
  56521. var ratio = this._ratio;
  56522. var scene = this._scene;
  56523. this._disposePostProcesses();
  56524. this._reset();
  56525. // Create pass post-process
  56526. if (!this._basePostProcess) {
  56527. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  56528. this.originalPostProcess.onApply = function (effect) {
  56529. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  56530. };
  56531. }
  56532. else {
  56533. this.originalPostProcess = this._basePostProcess;
  56534. }
  56535. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  56536. this._currentDepthOfFieldSource = this.originalPostProcess;
  56537. if (this._vlsEnabled) {
  56538. // Create volumetric light
  56539. this._createVolumetricLightPostProcess(scene, ratio);
  56540. // Create volumetric light final post-process
  56541. 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);
  56542. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  56543. }
  56544. if (this._bloomEnabled) {
  56545. // Create down sample X4 post-process
  56546. this._createDownSampleX4PostProcess(scene, ratio / 2);
  56547. // Create bright pass post-process
  56548. this._createBrightPassPostProcess(scene, ratio / 2);
  56549. // Create gaussian blur post-processes (down sampling blurs)
  56550. this._createBlurPostProcesses(scene, ratio / 4, 1);
  56551. // Create texture adder post-process
  56552. this._createTextureAdderPostProcess(scene, ratio);
  56553. // Create depth-of-field source post-process
  56554. 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);
  56555. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  56556. }
  56557. if (this._lensFlareEnabled) {
  56558. // Create lens flare post-process
  56559. this._createLensFlarePostProcess(scene, ratio);
  56560. // Create depth-of-field source post-process post lens-flare and disable it now
  56561. 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);
  56562. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  56563. }
  56564. if (this._hdrEnabled) {
  56565. // Create luminance
  56566. this._createLuminancePostProcesses(scene, this._floatTextureType);
  56567. // Create HDR
  56568. this._createHdrPostProcess(scene, ratio);
  56569. // Create depth-of-field source post-process post hdr and disable it now
  56570. 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);
  56571. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  56572. }
  56573. if (this._depthOfFieldEnabled) {
  56574. // Create gaussian blur used by depth-of-field
  56575. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  56576. // Create depth-of-field post-process
  56577. this._createDepthOfFieldPostProcess(scene, ratio);
  56578. }
  56579. if (this._motionBlurEnabled) {
  56580. // Create motion blur post-process
  56581. this._createMotionBlurPostProcess(scene, ratio);
  56582. }
  56583. if (this._cameras !== null) {
  56584. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  56585. }
  56586. };
  56587. // Down Sample X4 Post-Processs
  56588. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  56589. var _this = this;
  56590. var downSampleX4Offsets = new Array(32);
  56591. 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);
  56592. this.downSampleX4PostProcess.onApply = function (effect) {
  56593. var id = 0;
  56594. for (var i = -2; i < 2; i++) {
  56595. for (var j = -2; j < 2; j++) {
  56596. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  56597. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  56598. id += 2;
  56599. }
  56600. }
  56601. effect.setArray2("dsOffsets", downSampleX4Offsets);
  56602. };
  56603. // Add to pipeline
  56604. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  56605. };
  56606. // Brightpass Post-Process
  56607. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  56608. var _this = this;
  56609. var brightOffsets = new Array(8);
  56610. 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);
  56611. this.brightPassPostProcess.onApply = function (effect) {
  56612. var sU = (1.0 / _this.brightPassPostProcess.width);
  56613. var sV = (1.0 / _this.brightPassPostProcess.height);
  56614. brightOffsets[0] = -0.5 * sU;
  56615. brightOffsets[1] = 0.5 * sV;
  56616. brightOffsets[2] = 0.5 * sU;
  56617. brightOffsets[3] = 0.5 * sV;
  56618. brightOffsets[4] = -0.5 * sU;
  56619. brightOffsets[5] = -0.5 * sV;
  56620. brightOffsets[6] = 0.5 * sU;
  56621. brightOffsets[7] = -0.5 * sV;
  56622. effect.setArray2("dsOffsets", brightOffsets);
  56623. effect.setFloat("brightThreshold", _this.brightThreshold);
  56624. };
  56625. // Add to pipeline
  56626. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  56627. };
  56628. // Create blur H&V post-processes
  56629. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  56630. var _this = this;
  56631. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  56632. var engine = scene.getEngine();
  56633. 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);
  56634. 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);
  56635. blurX.onActivateObservable.add(function () {
  56636. var dw = blurX.width / engine.getRenderingCanvas().width;
  56637. blurX.kernel = _this[blurWidthKey] * dw;
  56638. });
  56639. blurY.onActivateObservable.add(function () {
  56640. var dw = blurY.height / engine.getRenderingCanvas().height;
  56641. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  56642. });
  56643. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  56644. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  56645. this.blurHPostProcesses.push(blurX);
  56646. this.blurVPostProcesses.push(blurY);
  56647. };
  56648. // Create texture adder post-process
  56649. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  56650. var _this = this;
  56651. 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);
  56652. this.textureAdderPostProcess.onApply = function (effect) {
  56653. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  56654. effect.setTexture("lensSampler", _this.lensTexture);
  56655. effect.setFloat("exposure", _this.exposure);
  56656. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  56657. };
  56658. // Add to pipeline
  56659. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  56660. };
  56661. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  56662. var _this = this;
  56663. var geometryRenderer = scene.enableGeometryBufferRenderer();
  56664. geometryRenderer.enablePosition = true;
  56665. var geometry = geometryRenderer.getGBuffer();
  56666. // Base post-process
  56667. 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));
  56668. var depthValues = BABYLON.Vector2.Zero();
  56669. this.volumetricLightPostProcess.onApply = function (effect) {
  56670. if (_this.sourceLight && _this.sourceLight.getShadowGenerator()) {
  56671. var generator = _this.sourceLight.getShadowGenerator();
  56672. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  56673. effect.setTexture("positionSampler", geometry.textures[2]);
  56674. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  56675. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  56676. effect.setVector3("cameraPosition", scene.activeCamera.globalPosition);
  56677. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  56678. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  56679. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  56680. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  56681. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  56682. effect.setVector2("depthValues", depthValues);
  56683. }
  56684. };
  56685. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  56686. // Smooth
  56687. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  56688. // Merge
  56689. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  56690. this.volumetricLightMergePostProces.onApply = function (effect) {
  56691. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  56692. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  56693. };
  56694. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  56695. };
  56696. // Create luminance
  56697. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  56698. var _this = this;
  56699. // Create luminance
  56700. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  56701. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  56702. var offsets = [];
  56703. this.luminancePostProcess.onApply = function (effect) {
  56704. var sU = (1.0 / _this.luminancePostProcess.width);
  56705. var sV = (1.0 / _this.luminancePostProcess.height);
  56706. offsets[0] = -0.5 * sU;
  56707. offsets[1] = 0.5 * sV;
  56708. offsets[2] = 0.5 * sU;
  56709. offsets[3] = 0.5 * sV;
  56710. offsets[4] = -0.5 * sU;
  56711. offsets[5] = -0.5 * sV;
  56712. offsets[6] = 0.5 * sU;
  56713. offsets[7] = -0.5 * sV;
  56714. effect.setArray2("lumOffsets", offsets);
  56715. };
  56716. // Add to pipeline
  56717. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  56718. // Create down sample luminance
  56719. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  56720. var size = Math.pow(3, i);
  56721. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  56722. if (i === 0) {
  56723. defines += "#define FINAL_DOWN_SAMPLER";
  56724. }
  56725. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  56726. this.luminanceDownSamplePostProcesses.push(postProcess);
  56727. }
  56728. // Create callbacks and add effects
  56729. var lastLuminance = this.luminancePostProcess;
  56730. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  56731. var downSampleOffsets = new Array(18);
  56732. pp.onApply = function (effect) {
  56733. var id = 0;
  56734. for (var x = -1; x < 2; x++) {
  56735. for (var y = -1; y < 2; y++) {
  56736. downSampleOffsets[id] = x / lastLuminance.width;
  56737. downSampleOffsets[id + 1] = y / lastLuminance.height;
  56738. id += 2;
  56739. }
  56740. }
  56741. effect.setArray2("dsOffsets", downSampleOffsets);
  56742. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  56743. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  56744. lastLuminance = _this.luminancePostProcess;
  56745. }
  56746. else {
  56747. lastLuminance = pp;
  56748. }
  56749. };
  56750. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  56751. pp.onAfterRender = function (effect) {
  56752. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  56753. 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);
  56754. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  56755. };
  56756. }
  56757. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  56758. });
  56759. };
  56760. // Create HDR post-process
  56761. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  56762. var _this = this;
  56763. 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);
  56764. var outputLiminance = 1;
  56765. var time = 0;
  56766. var lastTime = 0;
  56767. this.hdrPostProcess.onApply = function (effect) {
  56768. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  56769. time += scene.getEngine().getDeltaTime();
  56770. if (outputLiminance < 0) {
  56771. outputLiminance = _this._hdrCurrentLuminance;
  56772. }
  56773. else {
  56774. var dt = (lastTime - time) / 1000.0;
  56775. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  56776. outputLiminance += _this.hdrDecreaseRate * dt;
  56777. }
  56778. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  56779. outputLiminance -= _this.hdrIncreaseRate * dt;
  56780. }
  56781. else {
  56782. outputLiminance = _this._hdrCurrentLuminance;
  56783. }
  56784. }
  56785. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  56786. effect.setFloat("averageLuminance", outputLiminance);
  56787. lastTime = time;
  56788. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  56789. };
  56790. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  56791. };
  56792. // Create lens flare post-process
  56793. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  56794. var _this = this;
  56795. 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);
  56796. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  56797. this._createBlurPostProcesses(scene, ratio / 4, 2);
  56798. 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);
  56799. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  56800. var resolution = new BABYLON.Vector2(0, 0);
  56801. // Lens flare
  56802. this.lensFlarePostProcess.onApply = function (effect) {
  56803. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  56804. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  56805. effect.setFloat("strength", _this.lensFlareStrength);
  56806. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  56807. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  56808. // Shift
  56809. resolution.x = _this.lensFlarePostProcess.width;
  56810. resolution.y = _this.lensFlarePostProcess.height;
  56811. effect.setVector2("resolution", resolution);
  56812. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  56813. };
  56814. // Compose
  56815. 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);
  56816. 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);
  56817. this.lensFlareComposePostProcess.onApply = function (effect) {
  56818. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  56819. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  56820. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  56821. // Lens start rotation matrix
  56822. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  56823. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  56824. 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));
  56825. camRot *= 4.0;
  56826. 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);
  56827. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  56828. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  56829. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  56830. };
  56831. };
  56832. // Create depth-of-field post-process
  56833. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  56834. var _this = this;
  56835. 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);
  56836. this.depthOfFieldPostProcess.onApply = function (effect) {
  56837. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  56838. effect.setTexture("depthSampler", _this._getDepthTexture());
  56839. effect.setFloat("distance", _this.depthOfFieldDistance);
  56840. };
  56841. // Add to pipeline
  56842. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  56843. };
  56844. // Create motion blur post-process
  56845. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  56846. var _this = this;
  56847. 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);
  56848. var motionScale = 0;
  56849. var prevViewProjection = BABYLON.Matrix.Identity();
  56850. var invViewProjection = BABYLON.Matrix.Identity();
  56851. var viewProjection = BABYLON.Matrix.Identity();
  56852. var screenSize = BABYLON.Vector2.Zero();
  56853. this.motionBlurPostProcess.onApply = function (effect) {
  56854. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  56855. viewProjection.invertToRef(invViewProjection);
  56856. effect.setMatrix("inverseViewProjection", invViewProjection);
  56857. effect.setMatrix("prevViewProjection", prevViewProjection);
  56858. prevViewProjection = viewProjection;
  56859. screenSize.x = _this.motionBlurPostProcess.width;
  56860. screenSize.y = _this.motionBlurPostProcess.height;
  56861. effect.setVector2("screenSize", screenSize);
  56862. motionScale = scene.getEngine().getFps() / 60.0;
  56863. effect.setFloat("motionScale", motionScale);
  56864. effect.setFloat("motionStrength", _this.motionStrength);
  56865. effect.setTexture("depthSampler", _this._getDepthTexture());
  56866. };
  56867. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  56868. };
  56869. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  56870. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  56871. return this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  56872. }
  56873. return this._scene.enableDepthRenderer().getDepthMap();
  56874. };
  56875. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  56876. for (var i = 0; i < this._cameras.length; i++) {
  56877. var camera = this._cameras[i];
  56878. if (this.originalPostProcess) {
  56879. this.originalPostProcess.dispose(camera);
  56880. }
  56881. if (this.downSampleX4PostProcess) {
  56882. this.downSampleX4PostProcess.dispose(camera);
  56883. }
  56884. if (this.brightPassPostProcess) {
  56885. this.brightPassPostProcess.dispose(camera);
  56886. }
  56887. if (this.textureAdderPostProcess) {
  56888. this.textureAdderPostProcess.dispose(camera);
  56889. }
  56890. if (this.textureAdderFinalPostProcess) {
  56891. this.textureAdderFinalPostProcess.dispose(camera);
  56892. }
  56893. if (this.volumetricLightPostProcess) {
  56894. this.volumetricLightPostProcess.dispose(camera);
  56895. }
  56896. if (this.volumetricLightSmoothXPostProcess) {
  56897. this.volumetricLightSmoothXPostProcess.dispose(camera);
  56898. }
  56899. if (this.volumetricLightSmoothYPostProcess) {
  56900. this.volumetricLightSmoothYPostProcess.dispose(camera);
  56901. }
  56902. if (this.volumetricLightMergePostProces) {
  56903. this.volumetricLightMergePostProces.dispose(camera);
  56904. }
  56905. if (this.volumetricLightFinalPostProcess) {
  56906. this.volumetricLightFinalPostProcess.dispose(camera);
  56907. }
  56908. if (this.lensFlarePostProcess) {
  56909. this.lensFlarePostProcess.dispose(camera);
  56910. }
  56911. if (this.lensFlareComposePostProcess) {
  56912. this.lensFlareComposePostProcess.dispose(camera);
  56913. }
  56914. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  56915. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  56916. }
  56917. if (this.luminancePostProcess) {
  56918. this.luminancePostProcess.dispose(camera);
  56919. }
  56920. if (this.hdrPostProcess) {
  56921. this.hdrPostProcess.dispose(camera);
  56922. }
  56923. if (this.hdrFinalPostProcess) {
  56924. this.hdrFinalPostProcess.dispose(camera);
  56925. }
  56926. if (this.depthOfFieldPostProcess) {
  56927. this.depthOfFieldPostProcess.dispose(camera);
  56928. }
  56929. if (this.motionBlurPostProcess) {
  56930. this.motionBlurPostProcess.dispose(camera);
  56931. }
  56932. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  56933. this.blurHPostProcesses[j].dispose(camera);
  56934. }
  56935. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  56936. this.blurVPostProcesses[j].dispose(camera);
  56937. }
  56938. }
  56939. this.originalPostProcess = null;
  56940. this.downSampleX4PostProcess = null;
  56941. this.brightPassPostProcess = null;
  56942. this.textureAdderPostProcess = null;
  56943. this.textureAdderFinalPostProcess = null;
  56944. this.volumetricLightPostProcess = null;
  56945. this.volumetricLightSmoothXPostProcess = null;
  56946. this.volumetricLightSmoothYPostProcess = null;
  56947. this.volumetricLightMergePostProces = null;
  56948. this.volumetricLightFinalPostProcess = null;
  56949. this.lensFlarePostProcess = null;
  56950. this.lensFlareComposePostProcess = null;
  56951. this.luminancePostProcess = null;
  56952. this.hdrPostProcess = null;
  56953. this.hdrFinalPostProcess = null;
  56954. this.depthOfFieldPostProcess = null;
  56955. this.motionBlurPostProcess = null;
  56956. this.luminanceDownSamplePostProcesses = [];
  56957. this.blurHPostProcesses = [];
  56958. this.blurVPostProcesses = [];
  56959. };
  56960. // Dispose
  56961. StandardRenderingPipeline.prototype.dispose = function () {
  56962. this._disposePostProcesses();
  56963. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  56964. _super.prototype.dispose.call(this);
  56965. };
  56966. // Serialize rendering pipeline
  56967. StandardRenderingPipeline.prototype.serialize = function () {
  56968. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  56969. serializationObject.customType = "StandardRenderingPipeline";
  56970. return serializationObject;
  56971. };
  56972. /**
  56973. * Static members
  56974. */
  56975. // Parse serialized pipeline
  56976. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  56977. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  56978. };
  56979. // Luminance steps
  56980. StandardRenderingPipeline.LuminanceSteps = 6;
  56981. __decorate([
  56982. BABYLON.serialize()
  56983. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  56984. __decorate([
  56985. BABYLON.serialize()
  56986. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  56987. __decorate([
  56988. BABYLON.serialize()
  56989. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  56990. __decorate([
  56991. BABYLON.serialize()
  56992. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  56993. __decorate([
  56994. BABYLON.serializeAsTexture("lensTexture")
  56995. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  56996. __decorate([
  56997. BABYLON.serialize()
  56998. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  56999. __decorate([
  57000. BABYLON.serialize()
  57001. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  57002. __decorate([
  57003. BABYLON.serialize()
  57004. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  57005. __decorate([
  57006. BABYLON.serialize()
  57007. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  57008. __decorate([
  57009. BABYLON.serialize()
  57010. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  57011. __decorate([
  57012. BABYLON.serialize()
  57013. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  57014. __decorate([
  57015. BABYLON.serializeAsTexture("lensColorTexture")
  57016. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  57017. __decorate([
  57018. BABYLON.serialize()
  57019. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  57020. __decorate([
  57021. BABYLON.serialize()
  57022. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  57023. __decorate([
  57024. BABYLON.serialize()
  57025. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  57026. __decorate([
  57027. BABYLON.serialize()
  57028. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  57029. __decorate([
  57030. BABYLON.serializeAsTexture("lensStarTexture")
  57031. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  57032. __decorate([
  57033. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  57034. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  57035. __decorate([
  57036. BABYLON.serialize()
  57037. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  57038. __decorate([
  57039. BABYLON.serialize()
  57040. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  57041. __decorate([
  57042. BABYLON.serialize()
  57043. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  57044. __decorate([
  57045. BABYLON.serialize()
  57046. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  57047. __decorate([
  57048. BABYLON.serialize()
  57049. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  57050. __decorate([
  57051. BABYLON.serialize()
  57052. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  57053. __decorate([
  57054. BABYLON.serialize()
  57055. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  57056. __decorate([
  57057. BABYLON.serialize()
  57058. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  57059. __decorate([
  57060. BABYLON.serialize()
  57061. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  57062. __decorate([
  57063. BABYLON.serialize()
  57064. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  57065. __decorate([
  57066. BABYLON.serialize()
  57067. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  57068. return StandardRenderingPipeline;
  57069. }(BABYLON.PostProcessRenderPipeline));
  57070. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  57071. })(BABYLON || (BABYLON = {}));
  57072. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  57073. var BABYLON;
  57074. (function (BABYLON) {
  57075. var FxaaPostProcess = (function (_super) {
  57076. __extends(FxaaPostProcess, _super);
  57077. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  57078. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57079. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  57080. _this.onApplyObservable.add(function (effect) {
  57081. var texelSize = _this.texelSize;
  57082. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  57083. });
  57084. return _this;
  57085. }
  57086. return FxaaPostProcess;
  57087. }(BABYLON.PostProcess));
  57088. BABYLON.FxaaPostProcess = FxaaPostProcess;
  57089. })(BABYLON || (BABYLON = {}));
  57090. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  57091. var BABYLON;
  57092. (function (BABYLON) {
  57093. var DefaultRenderingPipeline = (function (_super) {
  57094. __extends(DefaultRenderingPipeline, _super);
  57095. /**
  57096. * @constructor
  57097. * @param {string} name - The rendering pipeline name
  57098. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57099. * @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)
  57100. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57101. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  57102. */
  57103. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  57104. if (automaticBuild === void 0) { automaticBuild = true; }
  57105. var _this = _super.call(this, scene.getEngine(), name) || this;
  57106. _this.PassPostProcessId = "PassPostProcessEffect";
  57107. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  57108. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  57109. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  57110. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  57111. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  57112. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  57113. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  57114. // IAnimatable
  57115. _this.animations = [];
  57116. // Values
  57117. _this._bloomEnabled = false;
  57118. _this._fxaaEnabled = false;
  57119. _this._imageProcessingEnabled = true;
  57120. _this._bloomScale = 0.6;
  57121. _this._buildAllowed = true;
  57122. /**
  57123. * Specifies the size of the bloom blur kernel, relative to the final output size
  57124. */
  57125. _this.bloomKernel = 64;
  57126. /**
  57127. * Specifies the weight of the bloom in the final rendering
  57128. */
  57129. _this._bloomWeight = 0.15;
  57130. _this._cameras = cameras || [];
  57131. _this._buildAllowed = automaticBuild;
  57132. // Initialize
  57133. _this._scene = scene;
  57134. var caps = _this._scene.getEngine().getCaps();
  57135. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  57136. // Misc
  57137. if (_this._hdr) {
  57138. if (caps.textureHalfFloatRender) {
  57139. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57140. }
  57141. else if (caps.textureFloatRender) {
  57142. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  57143. }
  57144. }
  57145. else {
  57146. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  57147. }
  57148. // Attach
  57149. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57150. _this._buildPipeline();
  57151. return _this;
  57152. }
  57153. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  57154. get: function () {
  57155. return this._bloomWeight;
  57156. },
  57157. set: function (value) {
  57158. if (this._bloomWeight === value) {
  57159. return;
  57160. }
  57161. this._bloomWeight = value;
  57162. if (this._hdr && this.copyBack) {
  57163. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  57164. }
  57165. },
  57166. enumerable: true,
  57167. configurable: true
  57168. });
  57169. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  57170. get: function () {
  57171. return this._bloomScale;
  57172. },
  57173. set: function (value) {
  57174. if (this._bloomScale === value) {
  57175. return;
  57176. }
  57177. this._bloomScale = value;
  57178. this._buildPipeline();
  57179. },
  57180. enumerable: true,
  57181. configurable: true
  57182. });
  57183. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  57184. get: function () {
  57185. return this._bloomEnabled;
  57186. },
  57187. set: function (enabled) {
  57188. if (this._bloomEnabled === enabled) {
  57189. return;
  57190. }
  57191. this._bloomEnabled = enabled;
  57192. this._buildPipeline();
  57193. },
  57194. enumerable: true,
  57195. configurable: true
  57196. });
  57197. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  57198. get: function () {
  57199. return this._fxaaEnabled;
  57200. },
  57201. set: function (enabled) {
  57202. if (this._fxaaEnabled === enabled) {
  57203. return;
  57204. }
  57205. this._fxaaEnabled = enabled;
  57206. this._buildPipeline();
  57207. },
  57208. enumerable: true,
  57209. configurable: true
  57210. });
  57211. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  57212. get: function () {
  57213. return this._imageProcessingEnabled;
  57214. },
  57215. set: function (enabled) {
  57216. if (this._imageProcessingEnabled === enabled) {
  57217. return;
  57218. }
  57219. this._imageProcessingEnabled = enabled;
  57220. this._buildPipeline();
  57221. },
  57222. enumerable: true,
  57223. configurable: true
  57224. });
  57225. /**
  57226. * Force the compilation of the entire pipeline.
  57227. */
  57228. DefaultRenderingPipeline.prototype.prepare = function () {
  57229. var previousState = this._buildAllowed;
  57230. this._buildAllowed = true;
  57231. this._buildPipeline();
  57232. this._buildAllowed = previousState;
  57233. };
  57234. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  57235. var _this = this;
  57236. if (!this._buildAllowed) {
  57237. return;
  57238. }
  57239. var engine = this._scene.getEngine();
  57240. this._disposePostProcesses();
  57241. this._reset();
  57242. if (this.bloomEnabled) {
  57243. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  57244. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  57245. if (!this._hdr) {
  57246. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  57247. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  57248. this.highlights.autoClear = false;
  57249. this.highlights.alwaysForcePOT = true;
  57250. }
  57251. 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);
  57252. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  57253. this.blurX.alwaysForcePOT = true;
  57254. this.blurX.autoClear = false;
  57255. this.blurX.onActivateObservable.add(function () {
  57256. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  57257. _this.blurX.kernel = _this.bloomKernel * dw;
  57258. });
  57259. 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);
  57260. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  57261. this.blurY.alwaysForcePOT = true;
  57262. this.blurY.autoClear = false;
  57263. this.blurY.onActivateObservable.add(function () {
  57264. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  57265. _this.blurY.kernel = _this.bloomKernel * dh;
  57266. });
  57267. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  57268. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  57269. this.copyBack.alwaysForcePOT = true;
  57270. if (this._hdr) {
  57271. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  57272. var w = this.bloomWeight;
  57273. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  57274. }
  57275. else {
  57276. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  57277. }
  57278. this.copyBack.autoClear = false;
  57279. }
  57280. if (this._imageProcessingEnabled) {
  57281. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  57282. if (this._hdr) {
  57283. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  57284. }
  57285. else {
  57286. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  57287. }
  57288. }
  57289. if (this.fxaaEnabled) {
  57290. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  57291. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  57292. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  57293. }
  57294. else {
  57295. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  57296. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  57297. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  57298. }
  57299. if (this.bloomEnabled) {
  57300. if (this._hdr) {
  57301. this.copyBack.shareOutputWith(this.blurX);
  57302. if (this.imageProcessing) {
  57303. this.imageProcessing.shareOutputWith(this.pass);
  57304. this.imageProcessing.autoClear = false;
  57305. }
  57306. else if (this.fxaa) {
  57307. this.fxaa.shareOutputWith(this.pass);
  57308. }
  57309. else {
  57310. this.finalMerge.shareOutputWith(this.pass);
  57311. }
  57312. }
  57313. else {
  57314. if (this.fxaa) {
  57315. this.fxaa.shareOutputWith(this.pass);
  57316. }
  57317. else {
  57318. this.finalMerge.shareOutputWith(this.pass);
  57319. }
  57320. }
  57321. }
  57322. if (this._cameras !== null) {
  57323. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  57324. }
  57325. };
  57326. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  57327. for (var i = 0; i < this._cameras.length; i++) {
  57328. var camera = this._cameras[i];
  57329. if (this.pass) {
  57330. this.pass.dispose(camera);
  57331. }
  57332. if (this.highlights) {
  57333. this.highlights.dispose(camera);
  57334. }
  57335. if (this.blurX) {
  57336. this.blurX.dispose(camera);
  57337. }
  57338. if (this.blurY) {
  57339. this.blurY.dispose(camera);
  57340. }
  57341. if (this.copyBack) {
  57342. this.copyBack.dispose(camera);
  57343. }
  57344. if (this.imageProcessing) {
  57345. this.imageProcessing.dispose(camera);
  57346. }
  57347. if (this.fxaa) {
  57348. this.fxaa.dispose(camera);
  57349. }
  57350. if (this.finalMerge) {
  57351. this.finalMerge.dispose(camera);
  57352. }
  57353. }
  57354. this.pass = null;
  57355. this.highlights = null;
  57356. this.blurX = null;
  57357. this.blurY = null;
  57358. this.copyBack = null;
  57359. this.imageProcessing = null;
  57360. this.fxaa = null;
  57361. this.finalMerge = null;
  57362. };
  57363. // Dispose
  57364. DefaultRenderingPipeline.prototype.dispose = function () {
  57365. this._disposePostProcesses();
  57366. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  57367. _super.prototype.dispose.call(this);
  57368. };
  57369. // Serialize rendering pipeline
  57370. DefaultRenderingPipeline.prototype.serialize = function () {
  57371. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  57372. serializationObject.customType = "DefaultRenderingPipeline";
  57373. return serializationObject;
  57374. };
  57375. // Parse serialized pipeline
  57376. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  57377. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  57378. };
  57379. __decorate([
  57380. BABYLON.serialize()
  57381. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  57382. __decorate([
  57383. BABYLON.serialize()
  57384. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  57385. __decorate([
  57386. BABYLON.serialize()
  57387. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  57388. __decorate([
  57389. BABYLON.serialize()
  57390. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  57391. __decorate([
  57392. BABYLON.serialize()
  57393. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  57394. __decorate([
  57395. BABYLON.serialize()
  57396. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  57397. __decorate([
  57398. BABYLON.serialize()
  57399. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  57400. __decorate([
  57401. BABYLON.serialize()
  57402. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  57403. return DefaultRenderingPipeline;
  57404. }(BABYLON.PostProcessRenderPipeline));
  57405. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  57406. })(BABYLON || (BABYLON = {}));
  57407. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  57408. var BABYLON;
  57409. (function (BABYLON) {
  57410. var GeometryBufferRenderer = (function () {
  57411. function GeometryBufferRenderer(scene, ratio) {
  57412. if (ratio === void 0) { ratio = 1; }
  57413. this._enablePosition = false;
  57414. this._scene = scene;
  57415. this._ratio = ratio;
  57416. // Render target
  57417. this._createRenderTargets();
  57418. }
  57419. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  57420. set: function (meshes) {
  57421. this._multiRenderTarget.renderList = meshes;
  57422. },
  57423. enumerable: true,
  57424. configurable: true
  57425. });
  57426. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  57427. get: function () {
  57428. return this._multiRenderTarget.isSupported;
  57429. },
  57430. enumerable: true,
  57431. configurable: true
  57432. });
  57433. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  57434. get: function () {
  57435. return this._enablePosition;
  57436. },
  57437. set: function (enable) {
  57438. this._enablePosition = enable;
  57439. this.dispose();
  57440. this._createRenderTargets();
  57441. },
  57442. enumerable: true,
  57443. configurable: true
  57444. });
  57445. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  57446. var material = subMesh.getMaterial();
  57447. if (material && material.disableDepthWrite) {
  57448. return false;
  57449. }
  57450. var defines = [];
  57451. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  57452. var mesh = subMesh.getMesh();
  57453. // Alpha test
  57454. if (material && material.needAlphaTesting()) {
  57455. defines.push("#define ALPHATEST");
  57456. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57457. attribs.push(BABYLON.VertexBuffer.UVKind);
  57458. defines.push("#define UV1");
  57459. }
  57460. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  57461. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  57462. defines.push("#define UV2");
  57463. }
  57464. }
  57465. // Buffers
  57466. if (this._enablePosition) {
  57467. defines.push("#define POSITION");
  57468. }
  57469. // Bones
  57470. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57471. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57472. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57473. if (mesh.numBoneInfluencers > 4) {
  57474. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57475. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57476. }
  57477. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57478. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  57479. }
  57480. else {
  57481. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57482. }
  57483. // Instances
  57484. if (useInstances) {
  57485. defines.push("#define INSTANCES");
  57486. attribs.push("world0");
  57487. attribs.push("world1");
  57488. attribs.push("world2");
  57489. attribs.push("world3");
  57490. }
  57491. // Get correct effect
  57492. var join = defines.join("\n");
  57493. if (this._cachedDefines !== join) {
  57494. this._cachedDefines = join;
  57495. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, null, null, null, { buffersCount: this._enablePosition ? 3 : 2 });
  57496. }
  57497. return this._effect.isReady();
  57498. };
  57499. GeometryBufferRenderer.prototype.getGBuffer = function () {
  57500. return this._multiRenderTarget;
  57501. };
  57502. // Methods
  57503. GeometryBufferRenderer.prototype.dispose = function () {
  57504. this.getGBuffer().dispose();
  57505. };
  57506. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  57507. var _this = this;
  57508. var engine = this._scene.getEngine();
  57509. var count = this._enablePosition ? 3 : 2;
  57510. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  57511. if (!this.isSupported) {
  57512. return null;
  57513. }
  57514. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57515. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57516. this._multiRenderTarget.refreshRate = 1;
  57517. this._multiRenderTarget.renderParticles = false;
  57518. this._multiRenderTarget.renderList = null;
  57519. // set default depth value to 1.0 (far away)
  57520. this._multiRenderTarget.onClearObservable.add(function (engine) {
  57521. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  57522. });
  57523. // Custom render function
  57524. var renderSubMesh = function (subMesh) {
  57525. var mesh = subMesh.getRenderingMesh();
  57526. var scene = _this._scene;
  57527. var engine = scene.getEngine();
  57528. // Culling
  57529. engine.setState(subMesh.getMaterial().backFaceCulling);
  57530. // Managing instances
  57531. var batch = mesh._getInstancesRenderList(subMesh._id);
  57532. if (batch.mustReturn) {
  57533. return;
  57534. }
  57535. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  57536. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  57537. engine.enableEffect(_this._effect);
  57538. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  57539. var material = subMesh.getMaterial();
  57540. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  57541. _this._effect.setMatrix("view", scene.getViewMatrix());
  57542. // Alpha test
  57543. if (material && material.needAlphaTesting()) {
  57544. var alphaTexture = material.getAlphaTestTexture();
  57545. _this._effect.setTexture("diffuseSampler", alphaTexture);
  57546. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  57547. }
  57548. // Bones
  57549. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57550. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  57551. }
  57552. // Draw
  57553. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  57554. }
  57555. };
  57556. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  57557. var index;
  57558. if (depthOnlySubMeshes.length) {
  57559. engine.setColorWrite(false);
  57560. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  57561. renderSubMesh(depthOnlySubMeshes.data[index]);
  57562. }
  57563. engine.setColorWrite(true);
  57564. }
  57565. for (index = 0; index < opaqueSubMeshes.length; index++) {
  57566. renderSubMesh(opaqueSubMeshes.data[index]);
  57567. }
  57568. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  57569. renderSubMesh(alphaTestSubMeshes.data[index]);
  57570. }
  57571. };
  57572. };
  57573. return GeometryBufferRenderer;
  57574. }());
  57575. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  57576. })(BABYLON || (BABYLON = {}));
  57577. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  57578. var BABYLON;
  57579. (function (BABYLON) {
  57580. var RefractionPostProcess = (function (_super) {
  57581. __extends(RefractionPostProcess, _super);
  57582. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  57583. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  57584. _this.color = color;
  57585. _this.depth = depth;
  57586. _this.colorLevel = colorLevel;
  57587. _this.onActivateObservable.add(function (cam) {
  57588. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  57589. });
  57590. _this.onApplyObservable.add(function (effect) {
  57591. effect.setColor3("baseColor", _this.color);
  57592. effect.setFloat("depth", _this.depth);
  57593. effect.setFloat("colorLevel", _this.colorLevel);
  57594. effect.setTexture("refractionSampler", _this._refRexture);
  57595. });
  57596. return _this;
  57597. }
  57598. // Methods
  57599. RefractionPostProcess.prototype.dispose = function (camera) {
  57600. if (this._refRexture) {
  57601. this._refRexture.dispose();
  57602. }
  57603. _super.prototype.dispose.call(this, camera);
  57604. };
  57605. return RefractionPostProcess;
  57606. }(BABYLON.PostProcess));
  57607. BABYLON.RefractionPostProcess = RefractionPostProcess;
  57608. })(BABYLON || (BABYLON = {}));
  57609. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  57610. var BABYLON;
  57611. (function (BABYLON) {
  57612. var BlackAndWhitePostProcess = (function (_super) {
  57613. __extends(BlackAndWhitePostProcess, _super);
  57614. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  57615. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  57616. _this.degree = 1;
  57617. _this.onApplyObservable.add(function (effect) {
  57618. effect.setFloat("degree", _this.degree);
  57619. });
  57620. return _this;
  57621. }
  57622. return BlackAndWhitePostProcess;
  57623. }(BABYLON.PostProcess));
  57624. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  57625. })(BABYLON || (BABYLON = {}));
  57626. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  57627. var BABYLON;
  57628. (function (BABYLON) {
  57629. var ConvolutionPostProcess = (function (_super) {
  57630. __extends(ConvolutionPostProcess, _super);
  57631. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  57632. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  57633. _this.kernel = kernel;
  57634. _this.onApply = function (effect) {
  57635. effect.setFloat2("screenSize", _this.width, _this.height);
  57636. effect.setArray("kernel", _this.kernel);
  57637. };
  57638. return _this;
  57639. }
  57640. // Statics
  57641. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  57642. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  57643. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  57644. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  57645. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  57646. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  57647. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  57648. return ConvolutionPostProcess;
  57649. }(BABYLON.PostProcess));
  57650. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  57651. })(BABYLON || (BABYLON = {}));
  57652. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  57653. var BABYLON;
  57654. (function (BABYLON) {
  57655. var FilterPostProcess = (function (_super) {
  57656. __extends(FilterPostProcess, _super);
  57657. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  57658. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  57659. _this.kernelMatrix = kernelMatrix;
  57660. _this.onApply = function (effect) {
  57661. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  57662. };
  57663. return _this;
  57664. }
  57665. return FilterPostProcess;
  57666. }(BABYLON.PostProcess));
  57667. BABYLON.FilterPostProcess = FilterPostProcess;
  57668. })(BABYLON || (BABYLON = {}));
  57669. //# sourceMappingURL=babylon.filterPostProcess.js.map
  57670. var BABYLON;
  57671. (function (BABYLON) {
  57672. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  57673. var VolumetricLightScatteringPostProcess = (function (_super) {
  57674. __extends(VolumetricLightScatteringPostProcess, _super);
  57675. /**
  57676. * @constructor
  57677. * @param {string} name - The post-process name
  57678. * @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)
  57679. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  57680. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  57681. * @param {number} samples - The post-process quality, default 100
  57682. * @param {number} samplingMode - The post-process filtering mode
  57683. * @param {BABYLON.Engine} engine - The babylon engine
  57684. * @param {boolean} reusable - If the post-process is reusable
  57685. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  57686. */
  57687. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  57688. if (samples === void 0) { samples = 100; }
  57689. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  57690. 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;
  57691. _this._screenCoordinates = BABYLON.Vector2.Zero();
  57692. /**
  57693. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  57694. * @type {Vector3}
  57695. */
  57696. _this.customMeshPosition = BABYLON.Vector3.Zero();
  57697. /**
  57698. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  57699. * @type {boolean}
  57700. */
  57701. _this.useCustomMeshPosition = false;
  57702. /**
  57703. * If the post-process should inverse the light scattering direction
  57704. * @type {boolean}
  57705. */
  57706. _this.invert = true;
  57707. /**
  57708. * Array containing the excluded meshes not rendered in the internal pass
  57709. */
  57710. _this.excludedMeshes = new Array();
  57711. /**
  57712. * Controls the overall intensity of the post-process
  57713. * @type {number}
  57714. */
  57715. _this.exposure = 0.3;
  57716. /**
  57717. * Dissipates each sample's contribution in range [0, 1]
  57718. * @type {number}
  57719. */
  57720. _this.decay = 0.96815;
  57721. /**
  57722. * Controls the overall intensity of each sample
  57723. * @type {number}
  57724. */
  57725. _this.weight = 0.58767;
  57726. /**
  57727. * Controls the density of each sample
  57728. * @type {number}
  57729. */
  57730. _this.density = 0.926;
  57731. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  57732. var engine = scene.getEngine();
  57733. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  57734. // Configure mesh
  57735. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  57736. // Configure
  57737. _this._createPass(scene, ratio.passRatio || ratio);
  57738. _this.onActivate = function (camera) {
  57739. if (!_this.isSupported) {
  57740. _this.dispose(camera);
  57741. }
  57742. _this.onActivate = null;
  57743. };
  57744. _this.onApplyObservable.add(function (effect) {
  57745. _this._updateMeshScreenCoordinates(scene);
  57746. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  57747. effect.setFloat("exposure", _this.exposure);
  57748. effect.setFloat("decay", _this.decay);
  57749. effect.setFloat("weight", _this.weight);
  57750. effect.setFloat("density", _this.density);
  57751. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  57752. });
  57753. return _this;
  57754. }
  57755. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  57756. get: function () {
  57757. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  57758. return false;
  57759. },
  57760. set: function (useDiffuseColor) {
  57761. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  57762. },
  57763. enumerable: true,
  57764. configurable: true
  57765. });
  57766. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  57767. return "VolumetricLightScatteringPostProcess";
  57768. };
  57769. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  57770. var mesh = subMesh.getMesh();
  57771. // Render this.mesh as default
  57772. if (mesh === this.mesh) {
  57773. return mesh.material.isReady(mesh);
  57774. }
  57775. var defines = [];
  57776. var attribs = [BABYLON.VertexBuffer.PositionKind];
  57777. var material = subMesh.getMaterial();
  57778. // Alpha test
  57779. if (material) {
  57780. if (material.needAlphaTesting()) {
  57781. defines.push("#define ALPHATEST");
  57782. }
  57783. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57784. attribs.push(BABYLON.VertexBuffer.UVKind);
  57785. defines.push("#define UV1");
  57786. }
  57787. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  57788. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  57789. defines.push("#define UV2");
  57790. }
  57791. }
  57792. // Bones
  57793. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57794. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57795. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57796. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57797. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  57798. }
  57799. else {
  57800. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57801. }
  57802. // Instances
  57803. if (useInstances) {
  57804. defines.push("#define INSTANCES");
  57805. attribs.push("world0");
  57806. attribs.push("world1");
  57807. attribs.push("world2");
  57808. attribs.push("world3");
  57809. }
  57810. // Get correct effect
  57811. var join = defines.join("\n");
  57812. if (this._cachedDefines !== join) {
  57813. this._cachedDefines = join;
  57814. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  57815. }
  57816. return this._volumetricLightScatteringPass.isReady();
  57817. };
  57818. /**
  57819. * Sets the new light position for light scattering effect
  57820. * @param {BABYLON.Vector3} The new custom light position
  57821. */
  57822. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  57823. this.customMeshPosition = position;
  57824. };
  57825. /**
  57826. * Returns the light position for light scattering effect
  57827. * @return {BABYLON.Vector3} The custom light position
  57828. */
  57829. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  57830. return this.customMeshPosition;
  57831. };
  57832. /**
  57833. * Disposes the internal assets and detaches the post-process from the camera
  57834. */
  57835. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  57836. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  57837. if (rttIndex !== -1) {
  57838. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  57839. }
  57840. this._volumetricLightScatteringRTT.dispose();
  57841. _super.prototype.dispose.call(this, camera);
  57842. };
  57843. /**
  57844. * Returns the render target texture used by the post-process
  57845. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  57846. */
  57847. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  57848. return this._volumetricLightScatteringRTT;
  57849. };
  57850. // Private methods
  57851. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  57852. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  57853. return true;
  57854. }
  57855. return false;
  57856. };
  57857. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  57858. var _this = this;
  57859. var engine = scene.getEngine();
  57860. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  57861. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57862. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57863. this._volumetricLightScatteringRTT.renderList = null;
  57864. this._volumetricLightScatteringRTT.renderParticles = false;
  57865. var camera = this.getCamera();
  57866. if (camera) {
  57867. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  57868. }
  57869. else {
  57870. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  57871. }
  57872. // Custom render function for submeshes
  57873. var renderSubMesh = function (subMesh) {
  57874. var mesh = subMesh.getRenderingMesh();
  57875. if (_this._meshExcluded(mesh)) {
  57876. return;
  57877. }
  57878. var scene = mesh.getScene();
  57879. var engine = scene.getEngine();
  57880. // Culling
  57881. engine.setState(subMesh.getMaterial().backFaceCulling);
  57882. // Managing instances
  57883. var batch = mesh._getInstancesRenderList(subMesh._id);
  57884. if (batch.mustReturn) {
  57885. return;
  57886. }
  57887. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  57888. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  57889. var effect = _this._volumetricLightScatteringPass;
  57890. if (mesh === _this.mesh) {
  57891. if (subMesh.effect) {
  57892. effect = subMesh.effect;
  57893. }
  57894. else {
  57895. effect = subMesh.getMaterial().getEffect();
  57896. }
  57897. }
  57898. engine.enableEffect(effect);
  57899. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  57900. if (mesh === _this.mesh) {
  57901. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  57902. }
  57903. else {
  57904. var material = subMesh.getMaterial();
  57905. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  57906. // Alpha test
  57907. if (material && material.needAlphaTesting()) {
  57908. var alphaTexture = material.getAlphaTestTexture();
  57909. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  57910. if (alphaTexture) {
  57911. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  57912. }
  57913. }
  57914. // Bones
  57915. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57916. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  57917. }
  57918. }
  57919. // Draw
  57920. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  57921. }
  57922. };
  57923. // Render target texture callbacks
  57924. var savedSceneClearColor;
  57925. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  57926. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  57927. savedSceneClearColor = scene.clearColor;
  57928. scene.clearColor = sceneClearColor;
  57929. });
  57930. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  57931. scene.clearColor = savedSceneClearColor;
  57932. });
  57933. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  57934. var engine = scene.getEngine();
  57935. var index;
  57936. if (depthOnlySubMeshes.length) {
  57937. engine.setColorWrite(false);
  57938. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  57939. renderSubMesh(depthOnlySubMeshes.data[index]);
  57940. }
  57941. engine.setColorWrite(true);
  57942. }
  57943. for (index = 0; index < opaqueSubMeshes.length; index++) {
  57944. renderSubMesh(opaqueSubMeshes.data[index]);
  57945. }
  57946. engine.setAlphaTesting(true);
  57947. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  57948. renderSubMesh(alphaTestSubMeshes.data[index]);
  57949. }
  57950. engine.setAlphaTesting(false);
  57951. if (transparentSubMeshes.length) {
  57952. // Sort sub meshes
  57953. for (index = 0; index < transparentSubMeshes.length; index++) {
  57954. var submesh = transparentSubMeshes.data[index];
  57955. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  57956. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  57957. }
  57958. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  57959. sortedArray.sort(function (a, b) {
  57960. // Alpha index first
  57961. if (a._alphaIndex > b._alphaIndex) {
  57962. return 1;
  57963. }
  57964. if (a._alphaIndex < b._alphaIndex) {
  57965. return -1;
  57966. }
  57967. // Then distance to camera
  57968. if (a._distanceToCamera < b._distanceToCamera) {
  57969. return 1;
  57970. }
  57971. if (a._distanceToCamera > b._distanceToCamera) {
  57972. return -1;
  57973. }
  57974. return 0;
  57975. });
  57976. // Render sub meshes
  57977. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57978. for (index = 0; index < sortedArray.length; index++) {
  57979. renderSubMesh(sortedArray[index]);
  57980. }
  57981. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57982. }
  57983. };
  57984. };
  57985. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  57986. var transform = scene.getTransformMatrix();
  57987. var meshPosition;
  57988. if (this.useCustomMeshPosition) {
  57989. meshPosition = this.customMeshPosition;
  57990. }
  57991. else if (this.attachedNode) {
  57992. meshPosition = this.attachedNode.position;
  57993. }
  57994. else {
  57995. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  57996. }
  57997. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  57998. this._screenCoordinates.x = pos.x / this._viewPort.width;
  57999. this._screenCoordinates.y = pos.y / this._viewPort.height;
  58000. if (this.invert)
  58001. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  58002. };
  58003. // Static methods
  58004. /**
  58005. * Creates a default mesh for the Volumeric Light Scattering post-process
  58006. * @param {string} The mesh name
  58007. * @param {BABYLON.Scene} The scene where to create the mesh
  58008. * @return {BABYLON.Mesh} the default mesh
  58009. */
  58010. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  58011. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  58012. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  58013. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  58014. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  58015. mesh.material = material;
  58016. return mesh;
  58017. };
  58018. __decorate([
  58019. BABYLON.serializeAsVector3()
  58020. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  58021. __decorate([
  58022. BABYLON.serialize()
  58023. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  58024. __decorate([
  58025. BABYLON.serialize()
  58026. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  58027. __decorate([
  58028. BABYLON.serializeAsMeshReference()
  58029. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  58030. __decorate([
  58031. BABYLON.serialize()
  58032. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  58033. __decorate([
  58034. BABYLON.serialize()
  58035. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  58036. __decorate([
  58037. BABYLON.serialize()
  58038. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  58039. __decorate([
  58040. BABYLON.serialize()
  58041. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  58042. __decorate([
  58043. BABYLON.serialize()
  58044. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  58045. return VolumetricLightScatteringPostProcess;
  58046. }(BABYLON.PostProcess));
  58047. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  58048. })(BABYLON || (BABYLON = {}));
  58049. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  58050. //
  58051. // This post-process allows the modification of rendered colors by using
  58052. // a 'look-up table' (LUT). This effect is also called Color Grading.
  58053. //
  58054. // The object needs to be provided an url to a texture containing the color
  58055. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  58056. // Use an image editing software to tweak the LUT to match your needs.
  58057. //
  58058. // For an example of a color LUT, see here:
  58059. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  58060. // For explanations on color grading, see here:
  58061. // http://udn.epicgames.com/Three/ColorGrading.html
  58062. //
  58063. var BABYLON;
  58064. (function (BABYLON) {
  58065. var ColorCorrectionPostProcess = (function (_super) {
  58066. __extends(ColorCorrectionPostProcess, _super);
  58067. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  58068. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  58069. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  58070. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  58071. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58072. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58073. _this.onApply = function (effect) {
  58074. effect.setTexture("colorTable", _this._colorTableTexture);
  58075. };
  58076. return _this;
  58077. }
  58078. return ColorCorrectionPostProcess;
  58079. }(BABYLON.PostProcess));
  58080. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  58081. })(BABYLON || (BABYLON = {}));
  58082. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  58083. var BABYLON;
  58084. (function (BABYLON) {
  58085. var TonemappingOperator;
  58086. (function (TonemappingOperator) {
  58087. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  58088. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  58089. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  58090. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  58091. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  58092. ;
  58093. var TonemapPostProcess = (function (_super) {
  58094. __extends(TonemapPostProcess, _super);
  58095. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  58096. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58097. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58098. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  58099. _this._operator = _operator;
  58100. _this.exposureAdjustment = exposureAdjustment;
  58101. var defines = "#define ";
  58102. if (_this._operator === TonemappingOperator.Hable)
  58103. defines += "HABLE_TONEMAPPING";
  58104. else if (_this._operator === TonemappingOperator.Reinhard)
  58105. defines += "REINHARD_TONEMAPPING";
  58106. else if (_this._operator === TonemappingOperator.HejiDawson)
  58107. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  58108. else if (_this._operator === TonemappingOperator.Photographic)
  58109. defines += "PHOTOGRAPHIC_TONEMAPPING";
  58110. //sadly a second call to create the effect.
  58111. _this.updateEffect(defines);
  58112. _this.onApply = function (effect) {
  58113. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  58114. };
  58115. return _this;
  58116. }
  58117. return TonemapPostProcess;
  58118. }(BABYLON.PostProcess));
  58119. BABYLON.TonemapPostProcess = TonemapPostProcess;
  58120. })(BABYLON || (BABYLON = {}));
  58121. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  58122. var BABYLON;
  58123. (function (BABYLON) {
  58124. var DisplayPassPostProcess = (function (_super) {
  58125. __extends(DisplayPassPostProcess, _super);
  58126. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  58127. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  58128. }
  58129. return DisplayPassPostProcess;
  58130. }(BABYLON.PostProcess));
  58131. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  58132. })(BABYLON || (BABYLON = {}));
  58133. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  58134. var BABYLON;
  58135. (function (BABYLON) {
  58136. var HighlightsPostProcess = (function (_super) {
  58137. __extends(HighlightsPostProcess, _super);
  58138. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  58139. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58140. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  58141. }
  58142. return HighlightsPostProcess;
  58143. }(BABYLON.PostProcess));
  58144. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  58145. })(BABYLON || (BABYLON = {}));
  58146. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  58147. var BABYLON;
  58148. (function (BABYLON) {
  58149. var ImageProcessingPostProcess = (function (_super) {
  58150. __extends(ImageProcessingPostProcess, _super);
  58151. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  58152. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58153. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  58154. _this._fromLinearSpace = true;
  58155. /**
  58156. * Defines cache preventing GC.
  58157. */
  58158. _this._defines = {
  58159. IMAGEPROCESSING: false,
  58160. VIGNETTE: false,
  58161. VIGNETTEBLENDMODEMULTIPLY: false,
  58162. VIGNETTEBLENDMODEOPAQUE: false,
  58163. TONEMAPPING: false,
  58164. CONTRAST: false,
  58165. COLORCURVES: false,
  58166. COLORGRADING: false,
  58167. FROMLINEARSPACE: false,
  58168. SAMPLER3DGREENDEPTH: false,
  58169. SAMPLER3DBGRMAP: false,
  58170. IMAGEPROCESSINGPOSTPROCESS: false,
  58171. EXPOSURE: false,
  58172. };
  58173. // Setup the default processing configuration to the scene.
  58174. _this._attachImageProcessingConfiguration(null, true);
  58175. _this.imageProcessingConfiguration.applyByPostProcess = true;
  58176. _this.onApply = function (effect) {
  58177. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  58178. };
  58179. return _this;
  58180. }
  58181. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  58182. /**
  58183. * Gets the image processing configuration used either in this material.
  58184. */
  58185. get: function () {
  58186. return this._imageProcessingConfiguration;
  58187. },
  58188. /**
  58189. * Sets the Default image processing configuration used either in the this material.
  58190. *
  58191. * If sets to null, the scene one is in use.
  58192. */
  58193. set: function (value) {
  58194. this._attachImageProcessingConfiguration(value);
  58195. },
  58196. enumerable: true,
  58197. configurable: true
  58198. });
  58199. /**
  58200. * Attaches a new image processing configuration to the PBR Material.
  58201. * @param configuration
  58202. */
  58203. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  58204. var _this = this;
  58205. if (doNotBuild === void 0) { doNotBuild = false; }
  58206. if (configuration === this._imageProcessingConfiguration) {
  58207. return;
  58208. }
  58209. // Detaches observer.
  58210. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  58211. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  58212. }
  58213. // Pick the scene configuration if needed.
  58214. if (!configuration) {
  58215. var scene = null;
  58216. var engine = this.getEngine();
  58217. var camera = this.getCamera();
  58218. if (camera) {
  58219. scene = camera.getScene();
  58220. }
  58221. else if (engine && engine.scenes) {
  58222. var scenes = engine.scenes;
  58223. scene = scenes[scenes.length - 1];
  58224. }
  58225. else {
  58226. scene = BABYLON.Engine.LastCreatedScene;
  58227. }
  58228. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  58229. }
  58230. else {
  58231. this._imageProcessingConfiguration = configuration;
  58232. }
  58233. // Attaches observer.
  58234. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  58235. _this._updateParameters();
  58236. });
  58237. // Ensure the effect will be rebuilt.
  58238. if (!doNotBuild) {
  58239. this._updateParameters();
  58240. }
  58241. };
  58242. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  58243. /**
  58244. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  58245. */
  58246. get: function () {
  58247. return this.imageProcessingConfiguration.colorCurves;
  58248. },
  58249. /**
  58250. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  58251. */
  58252. set: function (value) {
  58253. this.imageProcessingConfiguration.colorCurves = value;
  58254. },
  58255. enumerable: true,
  58256. configurable: true
  58257. });
  58258. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  58259. /**
  58260. * Gets wether the color curves effect is enabled.
  58261. */
  58262. get: function () {
  58263. return this.imageProcessingConfiguration.colorCurvesEnabled;
  58264. },
  58265. /**
  58266. * Sets wether the color curves effect is enabled.
  58267. */
  58268. set: function (value) {
  58269. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  58270. },
  58271. enumerable: true,
  58272. configurable: true
  58273. });
  58274. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  58275. /**
  58276. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  58277. */
  58278. get: function () {
  58279. return this.imageProcessingConfiguration.colorGradingTexture;
  58280. },
  58281. /**
  58282. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  58283. */
  58284. set: function (value) {
  58285. this.imageProcessingConfiguration.colorGradingTexture = value;
  58286. },
  58287. enumerable: true,
  58288. configurable: true
  58289. });
  58290. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  58291. /**
  58292. * Gets wether the color grading effect is enabled.
  58293. */
  58294. get: function () {
  58295. return this.imageProcessingConfiguration.colorGradingEnabled;
  58296. },
  58297. /**
  58298. * Gets wether the color grading effect is enabled.
  58299. */
  58300. set: function (value) {
  58301. this.imageProcessingConfiguration.colorGradingEnabled = value;
  58302. },
  58303. enumerable: true,
  58304. configurable: true
  58305. });
  58306. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  58307. /**
  58308. * Gets exposure used in the effect.
  58309. */
  58310. get: function () {
  58311. return this.imageProcessingConfiguration.exposure;
  58312. },
  58313. /**
  58314. * Sets exposure used in the effect.
  58315. */
  58316. set: function (value) {
  58317. this.imageProcessingConfiguration.exposure = value;
  58318. },
  58319. enumerable: true,
  58320. configurable: true
  58321. });
  58322. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  58323. /**
  58324. * Gets wether tonemapping is enabled or not.
  58325. */
  58326. get: function () {
  58327. return this._imageProcessingConfiguration.toneMappingEnabled;
  58328. },
  58329. /**
  58330. * Sets wether tonemapping is enabled or not
  58331. */
  58332. set: function (value) {
  58333. this._imageProcessingConfiguration.toneMappingEnabled = value;
  58334. },
  58335. enumerable: true,
  58336. configurable: true
  58337. });
  58338. ;
  58339. ;
  58340. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  58341. /**
  58342. * Gets contrast used in the effect.
  58343. */
  58344. get: function () {
  58345. return this.imageProcessingConfiguration.contrast;
  58346. },
  58347. /**
  58348. * Sets contrast used in the effect.
  58349. */
  58350. set: function (value) {
  58351. this.imageProcessingConfiguration.contrast = value;
  58352. },
  58353. enumerable: true,
  58354. configurable: true
  58355. });
  58356. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  58357. /**
  58358. * Gets Vignette stretch size.
  58359. */
  58360. get: function () {
  58361. return this.imageProcessingConfiguration.vignetteStretch;
  58362. },
  58363. /**
  58364. * Sets Vignette stretch size.
  58365. */
  58366. set: function (value) {
  58367. this.imageProcessingConfiguration.vignetteStretch = value;
  58368. },
  58369. enumerable: true,
  58370. configurable: true
  58371. });
  58372. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  58373. /**
  58374. * Gets Vignette centre X Offset.
  58375. */
  58376. get: function () {
  58377. return this.imageProcessingConfiguration.vignetteCentreX;
  58378. },
  58379. /**
  58380. * Sets Vignette centre X Offset.
  58381. */
  58382. set: function (value) {
  58383. this.imageProcessingConfiguration.vignetteCentreX = value;
  58384. },
  58385. enumerable: true,
  58386. configurable: true
  58387. });
  58388. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  58389. /**
  58390. * Gets Vignette centre Y Offset.
  58391. */
  58392. get: function () {
  58393. return this.imageProcessingConfiguration.vignetteCentreY;
  58394. },
  58395. /**
  58396. * Sets Vignette centre Y Offset.
  58397. */
  58398. set: function (value) {
  58399. this.imageProcessingConfiguration.vignetteCentreY = value;
  58400. },
  58401. enumerable: true,
  58402. configurable: true
  58403. });
  58404. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  58405. /**
  58406. * Gets Vignette weight or intensity of the vignette effect.
  58407. */
  58408. get: function () {
  58409. return this.imageProcessingConfiguration.vignetteWeight;
  58410. },
  58411. /**
  58412. * Sets Vignette weight or intensity of the vignette effect.
  58413. */
  58414. set: function (value) {
  58415. this.imageProcessingConfiguration.vignetteWeight = value;
  58416. },
  58417. enumerable: true,
  58418. configurable: true
  58419. });
  58420. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  58421. /**
  58422. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  58423. * if vignetteEnabled is set to true.
  58424. */
  58425. get: function () {
  58426. return this.imageProcessingConfiguration.vignetteColor;
  58427. },
  58428. /**
  58429. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  58430. * if vignetteEnabled is set to true.
  58431. */
  58432. set: function (value) {
  58433. this.imageProcessingConfiguration.vignetteColor = value;
  58434. },
  58435. enumerable: true,
  58436. configurable: true
  58437. });
  58438. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  58439. /**
  58440. * Gets Camera field of view used by the Vignette effect.
  58441. */
  58442. get: function () {
  58443. return this.imageProcessingConfiguration.vignetteCameraFov;
  58444. },
  58445. /**
  58446. * Sets Camera field of view used by the Vignette effect.
  58447. */
  58448. set: function (value) {
  58449. this.imageProcessingConfiguration.vignetteCameraFov = value;
  58450. },
  58451. enumerable: true,
  58452. configurable: true
  58453. });
  58454. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  58455. /**
  58456. * Gets the vignette blend mode allowing different kind of effect.
  58457. */
  58458. get: function () {
  58459. return this.imageProcessingConfiguration.vignetteBlendMode;
  58460. },
  58461. /**
  58462. * Sets the vignette blend mode allowing different kind of effect.
  58463. */
  58464. set: function (value) {
  58465. this.imageProcessingConfiguration.vignetteBlendMode = value;
  58466. },
  58467. enumerable: true,
  58468. configurable: true
  58469. });
  58470. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  58471. /**
  58472. * Gets wether the vignette effect is enabled.
  58473. */
  58474. get: function () {
  58475. return this.imageProcessingConfiguration.vignetteEnabled;
  58476. },
  58477. /**
  58478. * Sets wether the vignette effect is enabled.
  58479. */
  58480. set: function (value) {
  58481. this.imageProcessingConfiguration.vignetteEnabled = value;
  58482. },
  58483. enumerable: true,
  58484. configurable: true
  58485. });
  58486. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  58487. /**
  58488. * Gets wether the input of the processing is in Gamma or Linear Space.
  58489. */
  58490. get: function () {
  58491. return this._fromLinearSpace;
  58492. },
  58493. /**
  58494. * Sets wether the input of the processing is in Gamma or Linear Space.
  58495. */
  58496. set: function (value) {
  58497. if (this._fromLinearSpace === value) {
  58498. return;
  58499. }
  58500. this._fromLinearSpace = value;
  58501. this._updateParameters();
  58502. },
  58503. enumerable: true,
  58504. configurable: true
  58505. });
  58506. ImageProcessingPostProcess.prototype.getClassName = function () {
  58507. return "ImageProcessingPostProcess";
  58508. };
  58509. ImageProcessingPostProcess.prototype._updateParameters = function () {
  58510. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  58511. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  58512. var defines = "";
  58513. for (var define in this._defines) {
  58514. if (this._defines[define]) {
  58515. defines += "#define " + define + ";\r\n";
  58516. }
  58517. }
  58518. var samplers = ["textureSampler"];
  58519. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  58520. var uniforms = ["scale"];
  58521. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  58522. this.updateEffect(defines, uniforms, samplers);
  58523. };
  58524. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  58525. _super.prototype.dispose.call(this, camera);
  58526. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  58527. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  58528. }
  58529. this.imageProcessingConfiguration.applyByPostProcess = false;
  58530. };
  58531. __decorate([
  58532. BABYLON.serialize()
  58533. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  58534. return ImageProcessingPostProcess;
  58535. }(BABYLON.PostProcess));
  58536. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  58537. })(BABYLON || (BABYLON = {}));
  58538. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  58539. var BABYLON;
  58540. (function (BABYLON) {
  58541. var BlurPostProcess = (function (_super) {
  58542. __extends(BlurPostProcess, _super);
  58543. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  58544. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58545. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58546. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  58547. _this.direction = direction;
  58548. _this._packedFloat = false;
  58549. _this.onApplyObservable.add(function (effect) {
  58550. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  58551. });
  58552. _this.kernel = kernel;
  58553. return _this;
  58554. }
  58555. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  58556. /**
  58557. * Gets the length in pixels of the blur sample region
  58558. */
  58559. get: function () {
  58560. return this._idealKernel;
  58561. },
  58562. /**
  58563. * Sets the length in pixels of the blur sample region
  58564. */
  58565. set: function (v) {
  58566. if (this._idealKernel === v) {
  58567. return;
  58568. }
  58569. v = Math.max(v, 1);
  58570. this._idealKernel = v;
  58571. this._kernel = this._nearestBestKernel(v);
  58572. this._updateParameters();
  58573. },
  58574. enumerable: true,
  58575. configurable: true
  58576. });
  58577. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  58578. /**
  58579. * Gets wether or not the blur is unpacking/repacking floats
  58580. */
  58581. get: function () {
  58582. return this._packedFloat;
  58583. },
  58584. /**
  58585. * Sets wether or not the blur needs to unpack/repack floats
  58586. */
  58587. set: function (v) {
  58588. if (this._packedFloat === v) {
  58589. return;
  58590. }
  58591. this._packedFloat = v;
  58592. this._updateParameters();
  58593. },
  58594. enumerable: true,
  58595. configurable: true
  58596. });
  58597. BlurPostProcess.prototype._updateParameters = function () {
  58598. // Generate sampling offsets and weights
  58599. var N = this._kernel;
  58600. var centerIndex = (N - 1) / 2;
  58601. // Generate Gaussian sampling weights over kernel
  58602. var offsets = [];
  58603. var weights = [];
  58604. var totalWeight = 0;
  58605. for (var i = 0; i < N; i++) {
  58606. var u = i / (N - 1);
  58607. var w = this._gaussianWeight(u * 2.0 - 1);
  58608. offsets[i] = (i - centerIndex);
  58609. weights[i] = w;
  58610. totalWeight += w;
  58611. }
  58612. // Normalize weights
  58613. for (var i = 0; i < weights.length; i++) {
  58614. weights[i] /= totalWeight;
  58615. }
  58616. // Optimize: combine samples to take advantage of hardware linear sampling
  58617. // Walk from left to center, combining pairs (symmetrically)
  58618. var linearSamplingWeights = [];
  58619. var linearSamplingOffsets = [];
  58620. var linearSamplingMap = [];
  58621. for (var i = 0; i <= centerIndex; i += 2) {
  58622. var j = Math.min(i + 1, Math.floor(centerIndex));
  58623. var singleCenterSample = i === j;
  58624. if (singleCenterSample) {
  58625. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  58626. }
  58627. else {
  58628. var sharedCell = j === centerIndex;
  58629. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  58630. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  58631. if (offsetLinear === 0) {
  58632. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  58633. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  58634. }
  58635. else {
  58636. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  58637. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  58638. }
  58639. }
  58640. }
  58641. for (var i = 0; i < linearSamplingMap.length; i++) {
  58642. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  58643. linearSamplingWeights[i] = linearSamplingMap[i].w;
  58644. }
  58645. // Replace with optimized
  58646. offsets = linearSamplingOffsets;
  58647. weights = linearSamplingWeights;
  58648. // Generate shaders
  58649. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  58650. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  58651. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  58652. var defines = "";
  58653. for (var i = 0; i < varyingCount; i++) {
  58654. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  58655. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  58656. }
  58657. var depCount = 0;
  58658. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  58659. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  58660. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  58661. depCount++;
  58662. }
  58663. if (this.packedFloat) {
  58664. defines += "#define PACKEDFLOAT 1";
  58665. }
  58666. this.updateEffect(defines, null, null, {
  58667. varyingCount: varyingCount,
  58668. depCount: depCount
  58669. });
  58670. };
  58671. /**
  58672. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  58673. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  58674. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  58675. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  58676. * The gaps between physical kernels are compensated for in the weighting of the samples
  58677. * @param idealKernel Ideal blur kernel.
  58678. * @return Nearest best kernel.
  58679. */
  58680. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  58681. var v = Math.round(idealKernel);
  58682. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  58683. var k = _a[_i];
  58684. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  58685. return Math.max(k, 3);
  58686. }
  58687. }
  58688. return Math.max(v, 3);
  58689. };
  58690. /**
  58691. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  58692. * @param x The point on the Gaussian distribution to sample.
  58693. * @return the value of the Gaussian function at x.
  58694. */
  58695. BlurPostProcess.prototype._gaussianWeight = function (x) {
  58696. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  58697. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  58698. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  58699. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  58700. // truncated at around 1.3% of peak strength.
  58701. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  58702. var sigma = (1 / 3);
  58703. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  58704. var exponent = -((x * x) / (2.0 * sigma * sigma));
  58705. var weight = (1.0 / denominator) * Math.exp(exponent);
  58706. return weight;
  58707. };
  58708. /**
  58709. * Generates a string that can be used as a floating point number in GLSL.
  58710. * @param x Value to print.
  58711. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  58712. * @return GLSL float string.
  58713. */
  58714. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  58715. if (decimalFigures === void 0) { decimalFigures = 8; }
  58716. return x.toFixed(decimalFigures).replace(/0+$/, '');
  58717. };
  58718. return BlurPostProcess;
  58719. }(BABYLON.PostProcess));
  58720. BABYLON.BlurPostProcess = BlurPostProcess;
  58721. })(BABYLON || (BABYLON = {}));
  58722. //# sourceMappingURL=babylon.blurPostProcess.js.map
  58723. /// <reference path="..\babylon.node.ts" />
  58724. var BABYLON;
  58725. (function (BABYLON) {
  58726. var Bone = (function (_super) {
  58727. __extends(Bone, _super);
  58728. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  58729. if (parentBone === void 0) { parentBone = null; }
  58730. var _this = _super.call(this, name, skeleton.getScene()) || this;
  58731. _this.name = name;
  58732. _this.children = new Array();
  58733. _this.animations = new Array();
  58734. _this._worldTransform = new BABYLON.Matrix();
  58735. _this._absoluteTransform = new BABYLON.Matrix();
  58736. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  58737. _this._scaleMatrix = BABYLON.Matrix.Identity();
  58738. _this._scaleVector = BABYLON.Vector3.One();
  58739. _this._negateScaleChildren = BABYLON.Vector3.One();
  58740. _this._scalingDeterminant = 1;
  58741. _this._skeleton = skeleton;
  58742. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  58743. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  58744. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  58745. _this._index = index;
  58746. skeleton.bones.push(_this);
  58747. _this.setParent(parentBone, false);
  58748. _this._updateDifferenceMatrix();
  58749. return _this;
  58750. }
  58751. Object.defineProperty(Bone.prototype, "_matrix", {
  58752. get: function () {
  58753. return this._localMatrix;
  58754. },
  58755. set: function (val) {
  58756. if (this._localMatrix) {
  58757. this._localMatrix.copyFrom(val);
  58758. }
  58759. else {
  58760. this._localMatrix = val;
  58761. }
  58762. },
  58763. enumerable: true,
  58764. configurable: true
  58765. });
  58766. // Members
  58767. Bone.prototype.getSkeleton = function () {
  58768. return this._skeleton;
  58769. };
  58770. Bone.prototype.getParent = function () {
  58771. return this._parent;
  58772. };
  58773. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  58774. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  58775. if (this._parent === parent) {
  58776. return;
  58777. }
  58778. if (this._parent) {
  58779. var index = this._parent.children.indexOf(this);
  58780. if (index !== -1) {
  58781. this._parent.children.splice(index);
  58782. }
  58783. }
  58784. this._parent = parent;
  58785. if (this._parent) {
  58786. this._parent.children.push(this);
  58787. }
  58788. if (updateDifferenceMatrix) {
  58789. this._updateDifferenceMatrix();
  58790. }
  58791. };
  58792. Bone.prototype.getLocalMatrix = function () {
  58793. return this._localMatrix;
  58794. };
  58795. Bone.prototype.getBaseMatrix = function () {
  58796. return this._baseMatrix;
  58797. };
  58798. Bone.prototype.getRestPose = function () {
  58799. return this._restPose;
  58800. };
  58801. Bone.prototype.returnToRest = function () {
  58802. this.updateMatrix(this._restPose.clone());
  58803. };
  58804. Bone.prototype.getWorldMatrix = function () {
  58805. return this._worldTransform;
  58806. };
  58807. Bone.prototype.getInvertedAbsoluteTransform = function () {
  58808. return this._invertedAbsoluteTransform;
  58809. };
  58810. Bone.prototype.getAbsoluteTransform = function () {
  58811. return this._absoluteTransform;
  58812. };
  58813. Object.defineProperty(Bone.prototype, "position", {
  58814. // Properties (matches AbstractMesh properties)
  58815. get: function () {
  58816. return this.getPosition();
  58817. },
  58818. set: function (newPosition) {
  58819. this.setPosition(newPosition);
  58820. },
  58821. enumerable: true,
  58822. configurable: true
  58823. });
  58824. Object.defineProperty(Bone.prototype, "rotation", {
  58825. get: function () {
  58826. return this.getRotation();
  58827. },
  58828. set: function (newRotation) {
  58829. this.setRotation(newRotation);
  58830. },
  58831. enumerable: true,
  58832. configurable: true
  58833. });
  58834. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  58835. get: function () {
  58836. return this.getRotationQuaternion();
  58837. },
  58838. set: function (newRotation) {
  58839. this.setRotationQuaternion(newRotation);
  58840. },
  58841. enumerable: true,
  58842. configurable: true
  58843. });
  58844. Object.defineProperty(Bone.prototype, "scaling", {
  58845. get: function () {
  58846. return this.getScale();
  58847. },
  58848. set: function (newScaling) {
  58849. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  58850. },
  58851. enumerable: true,
  58852. configurable: true
  58853. });
  58854. // Methods
  58855. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  58856. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  58857. this._baseMatrix = matrix.clone();
  58858. this._localMatrix = matrix.clone();
  58859. this._skeleton._markAsDirty();
  58860. if (updateDifferenceMatrix) {
  58861. this._updateDifferenceMatrix();
  58862. }
  58863. };
  58864. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  58865. if (!rootMatrix) {
  58866. rootMatrix = this._baseMatrix;
  58867. }
  58868. if (this._parent) {
  58869. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  58870. }
  58871. else {
  58872. this._absoluteTransform.copyFrom(rootMatrix);
  58873. }
  58874. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  58875. for (var index = 0; index < this.children.length; index++) {
  58876. this.children[index]._updateDifferenceMatrix();
  58877. }
  58878. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  58879. };
  58880. Bone.prototype.markAsDirty = function () {
  58881. this._currentRenderId++;
  58882. this._skeleton._markAsDirty();
  58883. };
  58884. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  58885. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  58886. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  58887. // all animation may be coming from a library skeleton, so may need to create animation
  58888. if (this.animations.length === 0) {
  58889. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  58890. this.animations[0].setKeys([]);
  58891. }
  58892. // get animation info / verify there is such a range from the source bone
  58893. var sourceRange = source.animations[0].getRange(rangeName);
  58894. if (!sourceRange) {
  58895. return false;
  58896. }
  58897. var from = sourceRange.from;
  58898. var to = sourceRange.to;
  58899. var sourceKeys = source.animations[0].getKeys();
  58900. // rescaling prep
  58901. var sourceBoneLength = source.length;
  58902. var sourceParent = source.getParent();
  58903. var parent = this.getParent();
  58904. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  58905. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  58906. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  58907. var destKeys = this.animations[0].getKeys();
  58908. // loop vars declaration
  58909. var orig;
  58910. var origTranslation;
  58911. var mat;
  58912. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  58913. orig = sourceKeys[key];
  58914. if (orig.frame >= from && orig.frame <= to) {
  58915. if (rescaleAsRequired) {
  58916. mat = orig.value.clone();
  58917. // scale based on parent ratio, when bone has parent
  58918. if (parentScalingReqd) {
  58919. origTranslation = mat.getTranslation();
  58920. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  58921. // scale based on skeleton dimension ratio when root bone, and value is passed
  58922. }
  58923. else if (dimensionsScalingReqd) {
  58924. origTranslation = mat.getTranslation();
  58925. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  58926. // use original when root bone, and no data for skelDimensionsRatio
  58927. }
  58928. else {
  58929. mat = orig.value;
  58930. }
  58931. }
  58932. else {
  58933. mat = orig.value;
  58934. }
  58935. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  58936. }
  58937. }
  58938. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  58939. return true;
  58940. };
  58941. /**
  58942. * Translate the bone in local or world space.
  58943. * @param vec The amount to translate the bone.
  58944. * @param space The space that the translation is in.
  58945. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  58946. */
  58947. Bone.prototype.translate = function (vec, space, mesh) {
  58948. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  58949. var lm = this.getLocalMatrix();
  58950. if (space == BABYLON.Space.LOCAL) {
  58951. lm.m[12] += vec.x;
  58952. lm.m[13] += vec.y;
  58953. lm.m[14] += vec.z;
  58954. }
  58955. else {
  58956. var wm;
  58957. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  58958. if (mesh) {
  58959. wm = mesh.getWorldMatrix();
  58960. }
  58961. this._skeleton.computeAbsoluteTransforms();
  58962. var tmat = Bone._tmpMats[0];
  58963. var tvec = Bone._tmpVecs[0];
  58964. if (mesh) {
  58965. tmat.copyFrom(this._parent.getAbsoluteTransform());
  58966. tmat.multiplyToRef(wm, tmat);
  58967. }
  58968. else {
  58969. tmat.copyFrom(this._parent.getAbsoluteTransform());
  58970. }
  58971. tmat.m[12] = 0;
  58972. tmat.m[13] = 0;
  58973. tmat.m[14] = 0;
  58974. tmat.invert();
  58975. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  58976. lm.m[12] += tvec.x;
  58977. lm.m[13] += tvec.y;
  58978. lm.m[14] += tvec.z;
  58979. }
  58980. this.markAsDirty();
  58981. };
  58982. /**
  58983. * Set the postion of the bone in local or world space.
  58984. * @param position The position to set the bone.
  58985. * @param space The space that the position is in.
  58986. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  58987. */
  58988. Bone.prototype.setPosition = function (position, space, mesh) {
  58989. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  58990. var lm = this.getLocalMatrix();
  58991. if (space == BABYLON.Space.LOCAL) {
  58992. lm.m[12] = position.x;
  58993. lm.m[13] = position.y;
  58994. lm.m[14] = position.z;
  58995. }
  58996. else {
  58997. var wm;
  58998. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  58999. if (mesh) {
  59000. wm = mesh.getWorldMatrix();
  59001. }
  59002. this._skeleton.computeAbsoluteTransforms();
  59003. var tmat = Bone._tmpMats[0];
  59004. var vec = Bone._tmpVecs[0];
  59005. if (mesh) {
  59006. tmat.copyFrom(this._parent.getAbsoluteTransform());
  59007. tmat.multiplyToRef(wm, tmat);
  59008. }
  59009. else {
  59010. tmat.copyFrom(this._parent.getAbsoluteTransform());
  59011. }
  59012. tmat.invert();
  59013. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  59014. lm.m[12] = vec.x;
  59015. lm.m[13] = vec.y;
  59016. lm.m[14] = vec.z;
  59017. }
  59018. this.markAsDirty();
  59019. };
  59020. /**
  59021. * Set the absolute postion of the bone (world space).
  59022. * @param position The position to set the bone.
  59023. * @param mesh The mesh that this bone is attached to.
  59024. */
  59025. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  59026. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  59027. };
  59028. /**
  59029. * Set the scale of the bone on the x, y and z axes.
  59030. * @param x The scale of the bone on the x axis.
  59031. * @param x The scale of the bone on the y axis.
  59032. * @param z The scale of the bone on the z axis.
  59033. * @param scaleChildren Set this to true if children of the bone should be scaled.
  59034. */
  59035. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  59036. if (scaleChildren === void 0) { scaleChildren = false; }
  59037. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  59038. if (!scaleChildren) {
  59039. this._negateScaleChildren.x = 1 / x;
  59040. this._negateScaleChildren.y = 1 / y;
  59041. this._negateScaleChildren.z = 1 / z;
  59042. }
  59043. this._syncScaleVector();
  59044. }
  59045. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  59046. };
  59047. /**
  59048. * Scale the bone on the x, y and z axes.
  59049. * @param x The amount to scale the bone on the x axis.
  59050. * @param x The amount to scale the bone on the y axis.
  59051. * @param z The amount to scale the bone on the z axis.
  59052. * @param scaleChildren Set this to true if children of the bone should be scaled.
  59053. */
  59054. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  59055. if (scaleChildren === void 0) { scaleChildren = false; }
  59056. var locMat = this.getLocalMatrix();
  59057. var origLocMat = Bone._tmpMats[0];
  59058. origLocMat.copyFrom(locMat);
  59059. var origLocMatInv = Bone._tmpMats[1];
  59060. origLocMatInv.copyFrom(origLocMat);
  59061. origLocMatInv.invert();
  59062. var scaleMat = Bone._tmpMats[2];
  59063. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  59064. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  59065. this._scaleVector.x *= x;
  59066. this._scaleVector.y *= y;
  59067. this._scaleVector.z *= z;
  59068. locMat.multiplyToRef(origLocMatInv, locMat);
  59069. locMat.multiplyToRef(scaleMat, locMat);
  59070. locMat.multiplyToRef(origLocMat, locMat);
  59071. var parent = this.getParent();
  59072. if (parent) {
  59073. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  59074. }
  59075. else {
  59076. this.getAbsoluteTransform().copyFrom(locMat);
  59077. }
  59078. var len = this.children.length;
  59079. scaleMat.invert();
  59080. for (var i = 0; i < len; i++) {
  59081. var child = this.children[i];
  59082. var cm = child.getLocalMatrix();
  59083. cm.multiplyToRef(scaleMat, cm);
  59084. var lm = child.getLocalMatrix();
  59085. lm.m[12] *= x;
  59086. lm.m[13] *= y;
  59087. lm.m[14] *= z;
  59088. }
  59089. this.computeAbsoluteTransforms();
  59090. if (scaleChildren) {
  59091. for (var i = 0; i < len; i++) {
  59092. this.children[i].scale(x, y, z, scaleChildren);
  59093. }
  59094. }
  59095. this.markAsDirty();
  59096. };
  59097. /**
  59098. * Set the yaw, pitch, and roll of the bone in local or world space.
  59099. * @param yaw The rotation of the bone on the y axis.
  59100. * @param pitch The rotation of the bone on the x axis.
  59101. * @param roll The rotation of the bone on the z axis.
  59102. * @param space The space that the axes of rotation are in.
  59103. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59104. */
  59105. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  59106. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59107. var rotMat = Bone._tmpMats[0];
  59108. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  59109. var rotMatInv = Bone._tmpMats[1];
  59110. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  59111. rotMatInv.multiplyToRef(rotMat, rotMat);
  59112. this._rotateWithMatrix(rotMat, space, mesh);
  59113. };
  59114. /**
  59115. * Rotate the bone on an axis in local or world space.
  59116. * @param axis The axis to rotate the bone on.
  59117. * @param amount The amount to rotate the bone.
  59118. * @param space The space that the axis is in.
  59119. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59120. */
  59121. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  59122. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59123. var rmat = Bone._tmpMats[0];
  59124. rmat.m[12] = 0;
  59125. rmat.m[13] = 0;
  59126. rmat.m[14] = 0;
  59127. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  59128. this._rotateWithMatrix(rmat, space, mesh);
  59129. };
  59130. /**
  59131. * Set the rotation of the bone to a particular axis angle in local or world space.
  59132. * @param axis The axis to rotate the bone on.
  59133. * @param angle The angle that the bone should be rotated to.
  59134. * @param space The space that the axis is in.
  59135. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59136. */
  59137. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  59138. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59139. var rotMat = Bone._tmpMats[0];
  59140. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  59141. var rotMatInv = Bone._tmpMats[1];
  59142. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  59143. rotMatInv.multiplyToRef(rotMat, rotMat);
  59144. this._rotateWithMatrix(rotMat, space, mesh);
  59145. };
  59146. /**
  59147. * Set the euler rotation of the bone in local of world space.
  59148. * @param rotation The euler rotation that the bone should be set to.
  59149. * @param space The space that the rotation is in.
  59150. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59151. */
  59152. Bone.prototype.setRotation = function (rotation, space, mesh) {
  59153. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59154. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  59155. };
  59156. /**
  59157. * Set the quaternion rotation of the bone in local of world space.
  59158. * @param quat The quaternion rotation that the bone should be set to.
  59159. * @param space The space that the rotation is in.
  59160. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59161. */
  59162. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  59163. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59164. var rotMatInv = Bone._tmpMats[0];
  59165. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  59166. var rotMat = Bone._tmpMats[1];
  59167. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  59168. rotMatInv.multiplyToRef(rotMat, rotMat);
  59169. this._rotateWithMatrix(rotMat, space, mesh);
  59170. };
  59171. /**
  59172. * Set the rotation matrix of the bone in local of world space.
  59173. * @param rotMat The rotation matrix that the bone should be set to.
  59174. * @param space The space that the rotation is in.
  59175. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59176. */
  59177. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  59178. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59179. var rotMatInv = Bone._tmpMats[0];
  59180. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  59181. var rotMat2 = Bone._tmpMats[1];
  59182. rotMat2.copyFrom(rotMat);
  59183. rotMatInv.multiplyToRef(rotMat, rotMat2);
  59184. this._rotateWithMatrix(rotMat2, space, mesh);
  59185. };
  59186. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  59187. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59188. var lmat = this.getLocalMatrix();
  59189. var lx = lmat.m[12];
  59190. var ly = lmat.m[13];
  59191. var lz = lmat.m[14];
  59192. var parent = this.getParent();
  59193. var parentScale = Bone._tmpMats[3];
  59194. var parentScaleInv = Bone._tmpMats[4];
  59195. if (parent) {
  59196. if (space == BABYLON.Space.WORLD) {
  59197. if (mesh) {
  59198. parentScale.copyFrom(mesh.getWorldMatrix());
  59199. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  59200. }
  59201. else {
  59202. parentScale.copyFrom(parent.getAbsoluteTransform());
  59203. }
  59204. }
  59205. else {
  59206. parentScale = parent._scaleMatrix;
  59207. }
  59208. parentScaleInv.copyFrom(parentScale);
  59209. parentScaleInv.invert();
  59210. lmat.multiplyToRef(parentScale, lmat);
  59211. lmat.multiplyToRef(rmat, lmat);
  59212. lmat.multiplyToRef(parentScaleInv, lmat);
  59213. }
  59214. else {
  59215. if (space == BABYLON.Space.WORLD && mesh) {
  59216. parentScale.copyFrom(mesh.getWorldMatrix());
  59217. parentScaleInv.copyFrom(parentScale);
  59218. parentScaleInv.invert();
  59219. lmat.multiplyToRef(parentScale, lmat);
  59220. lmat.multiplyToRef(rmat, lmat);
  59221. lmat.multiplyToRef(parentScaleInv, lmat);
  59222. }
  59223. else {
  59224. lmat.multiplyToRef(rmat, lmat);
  59225. }
  59226. }
  59227. lmat.m[12] = lx;
  59228. lmat.m[13] = ly;
  59229. lmat.m[14] = lz;
  59230. this.computeAbsoluteTransforms();
  59231. this.markAsDirty();
  59232. };
  59233. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  59234. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59235. if (space == BABYLON.Space.WORLD) {
  59236. var scaleMatrix = Bone._tmpMats[2];
  59237. scaleMatrix.copyFrom(this._scaleMatrix);
  59238. rotMatInv.copyFrom(this.getAbsoluteTransform());
  59239. if (mesh) {
  59240. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  59241. var meshScale = Bone._tmpMats[3];
  59242. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  59243. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  59244. }
  59245. rotMatInv.invert();
  59246. scaleMatrix.m[0] *= this._scalingDeterminant;
  59247. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  59248. }
  59249. else {
  59250. rotMatInv.copyFrom(this.getLocalMatrix());
  59251. rotMatInv.invert();
  59252. var scaleMatrix = Bone._tmpMats[2];
  59253. scaleMatrix.copyFrom(this._scaleMatrix);
  59254. if (this._parent) {
  59255. var pscaleMatrix = Bone._tmpMats[3];
  59256. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  59257. pscaleMatrix.invert();
  59258. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  59259. }
  59260. else {
  59261. scaleMatrix.m[0] *= this._scalingDeterminant;
  59262. }
  59263. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  59264. }
  59265. };
  59266. /**
  59267. * Get the scale of the bone
  59268. * @returns the scale of the bone
  59269. */
  59270. Bone.prototype.getScale = function () {
  59271. return this._scaleVector.clone();
  59272. };
  59273. /**
  59274. * Copy the scale of the bone to a vector3.
  59275. * @param result The vector3 to copy the scale to
  59276. */
  59277. Bone.prototype.getScaleToRef = function (result) {
  59278. result.copyFrom(this._scaleVector);
  59279. };
  59280. /**
  59281. * Get the position of the bone in local or world space.
  59282. * @param space The space that the returned position is in.
  59283. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59284. * @returns The position of the bone
  59285. */
  59286. Bone.prototype.getPosition = function (space, mesh) {
  59287. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59288. var pos = BABYLON.Vector3.Zero();
  59289. this.getPositionToRef(space, mesh, pos);
  59290. return pos;
  59291. };
  59292. /**
  59293. * Copy the position of the bone to a vector3 in local or world space.
  59294. * @param space The space that the returned position is in.
  59295. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59296. * @param result The vector3 to copy the position to.
  59297. */
  59298. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  59299. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59300. if (space == BABYLON.Space.LOCAL) {
  59301. var lm = this.getLocalMatrix();
  59302. result.x = lm.m[12];
  59303. result.y = lm.m[13];
  59304. result.z = lm.m[14];
  59305. }
  59306. else {
  59307. var wm;
  59308. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  59309. if (mesh) {
  59310. wm = mesh.getWorldMatrix();
  59311. }
  59312. this._skeleton.computeAbsoluteTransforms();
  59313. var tmat = Bone._tmpMats[0];
  59314. if (mesh) {
  59315. tmat.copyFrom(this.getAbsoluteTransform());
  59316. tmat.multiplyToRef(wm, tmat);
  59317. }
  59318. else {
  59319. tmat = this.getAbsoluteTransform();
  59320. }
  59321. result.x = tmat.m[12];
  59322. result.y = tmat.m[13];
  59323. result.z = tmat.m[14];
  59324. }
  59325. };
  59326. /**
  59327. * Get the absolute position of the bone (world space).
  59328. * @param mesh The mesh that this bone is attached to.
  59329. * @returns The absolute position of the bone
  59330. */
  59331. Bone.prototype.getAbsolutePosition = function (mesh) {
  59332. var pos = BABYLON.Vector3.Zero();
  59333. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  59334. return pos;
  59335. };
  59336. /**
  59337. * Copy the absolute position of the bone (world space) to the result param.
  59338. * @param mesh The mesh that this bone is attached to.
  59339. * @param result The vector3 to copy the absolute position to.
  59340. */
  59341. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  59342. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  59343. };
  59344. /**
  59345. * Compute the absolute transforms of this bone and its children.
  59346. */
  59347. Bone.prototype.computeAbsoluteTransforms = function () {
  59348. if (this._parent) {
  59349. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  59350. }
  59351. else {
  59352. this._absoluteTransform.copyFrom(this._localMatrix);
  59353. var poseMatrix = this._skeleton.getPoseMatrix();
  59354. if (poseMatrix) {
  59355. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  59356. }
  59357. }
  59358. var children = this.children;
  59359. var len = children.length;
  59360. for (var i = 0; i < len; i++) {
  59361. children[i].computeAbsoluteTransforms();
  59362. }
  59363. };
  59364. Bone.prototype._syncScaleVector = function () {
  59365. var lm = this.getLocalMatrix();
  59366. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  59367. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  59368. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  59369. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  59370. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  59371. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  59372. this._scaleVector.x = xs * Math.sqrt(xsq);
  59373. this._scaleVector.y = ys * Math.sqrt(ysq);
  59374. this._scaleVector.z = zs * Math.sqrt(zsq);
  59375. if (this._parent) {
  59376. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  59377. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  59378. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  59379. }
  59380. 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);
  59381. };
  59382. /**
  59383. * Get the world direction from an axis that is in the local space of the bone.
  59384. * @param localAxis The local direction that is used to compute the world direction.
  59385. * @param mesh The mesh that this bone is attached to.
  59386. * @returns The world direction
  59387. */
  59388. Bone.prototype.getDirection = function (localAxis, mesh) {
  59389. var result = BABYLON.Vector3.Zero();
  59390. this.getDirectionToRef(localAxis, mesh, result);
  59391. return result;
  59392. };
  59393. /**
  59394. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  59395. * @param localAxis The local direction that is used to compute the world direction.
  59396. * @param mesh The mesh that this bone is attached to.
  59397. * @param result The vector3 that the world direction will be copied to.
  59398. */
  59399. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  59400. var wm;
  59401. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  59402. if (mesh) {
  59403. wm = mesh.getWorldMatrix();
  59404. }
  59405. this._skeleton.computeAbsoluteTransforms();
  59406. var mat = Bone._tmpMats[0];
  59407. mat.copyFrom(this.getAbsoluteTransform());
  59408. if (mesh) {
  59409. mat.multiplyToRef(wm, mat);
  59410. }
  59411. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  59412. result.normalize();
  59413. };
  59414. /**
  59415. * Get the euler rotation of the bone in local or world space.
  59416. * @param space The space that the rotation should be in.
  59417. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59418. * @returns The euler rotation
  59419. */
  59420. Bone.prototype.getRotation = function (space, mesh) {
  59421. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59422. var result = BABYLON.Vector3.Zero();
  59423. this.getRotationToRef(space, mesh, result);
  59424. return result;
  59425. };
  59426. /**
  59427. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  59428. * @param space The space that the rotation should be in.
  59429. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59430. * @param result The vector3 that the rotation should be copied to.
  59431. */
  59432. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  59433. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59434. var quat = Bone._tmpQuat;
  59435. this.getRotationQuaternionToRef(space, mesh, quat);
  59436. quat.toEulerAnglesToRef(result);
  59437. };
  59438. /**
  59439. * Get the quaternion rotation of the bone in either local or world space.
  59440. * @param space The space that the rotation should be in.
  59441. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59442. * @returns The quaternion rotation
  59443. */
  59444. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  59445. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59446. var result = BABYLON.Quaternion.Identity();
  59447. this.getRotationQuaternionToRef(space, mesh, result);
  59448. return result;
  59449. };
  59450. /**
  59451. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  59452. * @param space The space that the rotation should be in.
  59453. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59454. * @param result The quaternion that the rotation should be copied to.
  59455. */
  59456. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  59457. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59458. if (space == BABYLON.Space.LOCAL) {
  59459. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  59460. }
  59461. else {
  59462. var mat = Bone._tmpMats[0];
  59463. var amat = this.getAbsoluteTransform();
  59464. if (mesh) {
  59465. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  59466. }
  59467. else {
  59468. mat.copyFrom(amat);
  59469. }
  59470. mat.m[0] *= this._scalingDeterminant;
  59471. mat.m[1] *= this._scalingDeterminant;
  59472. mat.m[2] *= this._scalingDeterminant;
  59473. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  59474. }
  59475. };
  59476. /**
  59477. * Get the rotation matrix of the bone in local or world space.
  59478. * @param space The space that the rotation should be in.
  59479. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59480. * @returns The rotation matrix
  59481. */
  59482. Bone.prototype.getRotationMatrix = function (space, mesh) {
  59483. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59484. var result = BABYLON.Matrix.Identity();
  59485. this.getRotationMatrixToRef(space, mesh, result);
  59486. return result;
  59487. };
  59488. /**
  59489. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  59490. * @param space The space that the rotation should be in.
  59491. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59492. * @param result The quaternion that the rotation should be copied to.
  59493. */
  59494. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  59495. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59496. if (space == BABYLON.Space.LOCAL) {
  59497. this.getLocalMatrix().getRotationMatrixToRef(result);
  59498. }
  59499. else {
  59500. var mat = Bone._tmpMats[0];
  59501. var amat = this.getAbsoluteTransform();
  59502. if (mesh) {
  59503. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  59504. }
  59505. else {
  59506. mat.copyFrom(amat);
  59507. }
  59508. mat.m[0] *= this._scalingDeterminant;
  59509. mat.m[1] *= this._scalingDeterminant;
  59510. mat.m[2] *= this._scalingDeterminant;
  59511. mat.getRotationMatrixToRef(result);
  59512. }
  59513. };
  59514. /**
  59515. * Get the world position of a point that is in the local space of the bone.
  59516. * @param position The local position
  59517. * @param mesh The mesh that this bone is attached to.
  59518. * @returns The world position
  59519. */
  59520. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  59521. var result = BABYLON.Vector3.Zero();
  59522. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  59523. return result;
  59524. };
  59525. /**
  59526. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  59527. * @param position The local position
  59528. * @param mesh The mesh that this bone is attached to.
  59529. * @param result The vector3 that the world position should be copied to.
  59530. */
  59531. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  59532. var wm;
  59533. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  59534. if (mesh) {
  59535. wm = mesh.getWorldMatrix();
  59536. }
  59537. this._skeleton.computeAbsoluteTransforms();
  59538. var tmat = Bone._tmpMats[0];
  59539. if (mesh) {
  59540. tmat.copyFrom(this.getAbsoluteTransform());
  59541. tmat.multiplyToRef(wm, tmat);
  59542. }
  59543. else {
  59544. tmat = this.getAbsoluteTransform();
  59545. }
  59546. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  59547. };
  59548. /**
  59549. * Get the local position of a point that is in world space.
  59550. * @param position The world position
  59551. * @param mesh The mesh that this bone is attached to.
  59552. * @returns The local position
  59553. */
  59554. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  59555. var result = BABYLON.Vector3.Zero();
  59556. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  59557. return result;
  59558. };
  59559. /**
  59560. * Get the local position of a point that is in world space and copy it to the result param.
  59561. * @param position The world position
  59562. * @param mesh The mesh that this bone is attached to.
  59563. * @param result The vector3 that the local position should be copied to.
  59564. */
  59565. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  59566. var wm;
  59567. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  59568. if (mesh) {
  59569. wm = mesh.getWorldMatrix();
  59570. }
  59571. this._skeleton.computeAbsoluteTransforms();
  59572. var tmat = Bone._tmpMats[0];
  59573. tmat.copyFrom(this.getAbsoluteTransform());
  59574. if (mesh) {
  59575. tmat.multiplyToRef(wm, tmat);
  59576. }
  59577. tmat.invert();
  59578. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  59579. };
  59580. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59581. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  59582. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  59583. return Bone;
  59584. }(BABYLON.Node));
  59585. BABYLON.Bone = Bone;
  59586. })(BABYLON || (BABYLON = {}));
  59587. //# sourceMappingURL=babylon.bone.js.map
  59588. var BABYLON;
  59589. (function (BABYLON) {
  59590. var BoneIKController = (function () {
  59591. function BoneIKController(mesh, bone, options) {
  59592. this.targetPosition = BABYLON.Vector3.Zero();
  59593. this.poleTargetPosition = BABYLON.Vector3.Zero();
  59594. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  59595. this.poleAngle = 0;
  59596. this.slerpAmount = 1;
  59597. this._bone1Quat = BABYLON.Quaternion.Identity();
  59598. this._bone1Mat = BABYLON.Matrix.Identity();
  59599. this._bone2Ang = Math.PI;
  59600. this._maxAngle = Math.PI;
  59601. this._rightHandedSystem = false;
  59602. this._bendAxis = BABYLON.Vector3.Right();
  59603. this._slerping = false;
  59604. this._adjustRoll = 0;
  59605. this._bone2 = bone;
  59606. this._bone1 = bone.getParent();
  59607. this.mesh = mesh;
  59608. var bonePos = bone.getPosition();
  59609. if (bone.getAbsoluteTransform().determinant() > 0) {
  59610. this._rightHandedSystem = true;
  59611. this._bendAxis.x = 0;
  59612. this._bendAxis.y = 0;
  59613. this._bendAxis.z = -1;
  59614. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  59615. this._adjustRoll = Math.PI * .5;
  59616. this._bendAxis.z = 1;
  59617. }
  59618. }
  59619. if (this._bone1.length) {
  59620. var boneScale1 = this._bone1.getScale();
  59621. var boneScale2 = this._bone2.getScale();
  59622. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  59623. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  59624. }
  59625. else if (this._bone1.children[0]) {
  59626. mesh.computeWorldMatrix(true);
  59627. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  59628. var pos2 = this._bone2.getAbsolutePosition(mesh);
  59629. var pos3 = this._bone1.getAbsolutePosition(mesh);
  59630. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  59631. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  59632. }
  59633. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  59634. this.maxAngle = Math.PI;
  59635. if (options) {
  59636. if (options.targetMesh) {
  59637. this.targetMesh = options.targetMesh;
  59638. this.targetMesh.computeWorldMatrix(true);
  59639. }
  59640. if (options.poleTargetMesh) {
  59641. this.poleTargetMesh = options.poleTargetMesh;
  59642. this.poleTargetMesh.computeWorldMatrix(true);
  59643. }
  59644. else if (options.poleTargetBone) {
  59645. this.poleTargetBone = options.poleTargetBone;
  59646. }
  59647. else if (this._bone1.getParent()) {
  59648. this.poleTargetBone = this._bone1.getParent();
  59649. }
  59650. if (options.poleTargetLocalOffset) {
  59651. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  59652. }
  59653. if (options.poleAngle) {
  59654. this.poleAngle = options.poleAngle;
  59655. }
  59656. if (options.bendAxis) {
  59657. this._bendAxis.copyFrom(options.bendAxis);
  59658. }
  59659. if (options.maxAngle) {
  59660. this.maxAngle = options.maxAngle;
  59661. }
  59662. if (options.slerpAmount) {
  59663. this.slerpAmount = options.slerpAmount;
  59664. }
  59665. }
  59666. }
  59667. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  59668. get: function () {
  59669. return this._maxAngle;
  59670. },
  59671. set: function (value) {
  59672. this._setMaxAngle(value);
  59673. },
  59674. enumerable: true,
  59675. configurable: true
  59676. });
  59677. BoneIKController.prototype._setMaxAngle = function (ang) {
  59678. if (ang < 0) {
  59679. ang = 0;
  59680. }
  59681. if (ang > Math.PI || ang == undefined) {
  59682. ang = Math.PI;
  59683. }
  59684. this._maxAngle = ang;
  59685. var a = this._bone1Length;
  59686. var b = this._bone2Length;
  59687. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  59688. };
  59689. BoneIKController.prototype.update = function () {
  59690. var bone1 = this._bone1;
  59691. var target = this.targetPosition;
  59692. var poleTarget = this.poleTargetPosition;
  59693. var mat1 = BoneIKController._tmpMats[0];
  59694. var mat2 = BoneIKController._tmpMats[1];
  59695. if (this.targetMesh) {
  59696. target.copyFrom(this.targetMesh.getAbsolutePosition());
  59697. }
  59698. if (this.poleTargetBone) {
  59699. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  59700. }
  59701. else if (this.poleTargetMesh) {
  59702. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  59703. }
  59704. var bonePos = BoneIKController._tmpVecs[0];
  59705. var zaxis = BoneIKController._tmpVecs[1];
  59706. var xaxis = BoneIKController._tmpVecs[2];
  59707. var yaxis = BoneIKController._tmpVecs[3];
  59708. var upAxis = BoneIKController._tmpVecs[4];
  59709. var _tmpQuat = BoneIKController._tmpQuat;
  59710. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  59711. poleTarget.subtractToRef(bonePos, upAxis);
  59712. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  59713. upAxis.y = 1;
  59714. }
  59715. else {
  59716. upAxis.normalize();
  59717. }
  59718. target.subtractToRef(bonePos, yaxis);
  59719. yaxis.normalize();
  59720. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  59721. zaxis.normalize();
  59722. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  59723. xaxis.normalize();
  59724. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  59725. var a = this._bone1Length;
  59726. var b = this._bone2Length;
  59727. var c = BABYLON.Vector3.Distance(bonePos, target);
  59728. if (this._maxReach > 0) {
  59729. c = Math.min(this._maxReach, c);
  59730. }
  59731. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  59732. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  59733. if (acosa > 1) {
  59734. acosa = 1;
  59735. }
  59736. if (acosb > 1) {
  59737. acosb = 1;
  59738. }
  59739. if (acosa < -1) {
  59740. acosa = -1;
  59741. }
  59742. if (acosb < -1) {
  59743. acosb = -1;
  59744. }
  59745. var angA = Math.acos(acosa);
  59746. var angB = Math.acos(acosb);
  59747. var angC = -angA - angB;
  59748. if (this._rightHandedSystem) {
  59749. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  59750. mat2.multiplyToRef(mat1, mat1);
  59751. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  59752. mat2.multiplyToRef(mat1, mat1);
  59753. }
  59754. else {
  59755. var _tmpVec = BoneIKController._tmpVecs[5];
  59756. _tmpVec.copyFrom(this._bendAxis);
  59757. _tmpVec.x *= -1;
  59758. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  59759. mat2.multiplyToRef(mat1, mat1);
  59760. }
  59761. if (this.poleAngle) {
  59762. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  59763. mat1.multiplyToRef(mat2, mat1);
  59764. }
  59765. if (this.slerpAmount < 1) {
  59766. if (!this._slerping) {
  59767. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  59768. }
  59769. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  59770. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  59771. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  59772. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  59773. this._slerping = true;
  59774. }
  59775. else {
  59776. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  59777. this._bone1Mat.copyFrom(mat1);
  59778. this._slerping = false;
  59779. }
  59780. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  59781. this._bone2Ang = angC;
  59782. };
  59783. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59784. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  59785. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  59786. return BoneIKController;
  59787. }());
  59788. BABYLON.BoneIKController = BoneIKController;
  59789. })(BABYLON || (BABYLON = {}));
  59790. //# sourceMappingURL=babylon.boneIKController.js.map
  59791. var BABYLON;
  59792. (function (BABYLON) {
  59793. var BoneLookController = (function () {
  59794. /**
  59795. * Create a BoneLookController
  59796. * @param mesh the mesh that the bone belongs to
  59797. * @param bone the bone that will be looking to the target
  59798. * @param target the target Vector3 to look at
  59799. * @param settings optional settings:
  59800. * - maxYaw: the maximum angle the bone will yaw to
  59801. * - minYaw: the minimum angle the bone will yaw to
  59802. * - maxPitch: the maximum angle the bone will pitch to
  59803. * - minPitch: the minimum angle the bone will yaw to
  59804. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  59805. * - upAxis: the up axis of the coordinate system
  59806. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  59807. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  59808. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  59809. * - adjustYaw: used to make an adjustment to the yaw of the bone
  59810. * - adjustPitch: used to make an adjustment to the pitch of the bone
  59811. * - adjustRoll: used to make an adjustment to the roll of the bone
  59812. **/
  59813. function BoneLookController(mesh, bone, target, options) {
  59814. /**
  59815. * The up axis of the coordinate system that is used when the bone is rotated.
  59816. */
  59817. this.upAxis = BABYLON.Vector3.Up();
  59818. /**
  59819. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  59820. */
  59821. this.upAxisSpace = BABYLON.Space.LOCAL;
  59822. /**
  59823. * Used to make an adjustment to the yaw of the bone.
  59824. */
  59825. this.adjustYaw = 0;
  59826. /**
  59827. * Used to make an adjustment to the pitch of the bone.
  59828. */
  59829. this.adjustPitch = 0;
  59830. /**
  59831. * Used to make an adjustment to the roll of the bone.
  59832. */
  59833. this.adjustRoll = 0;
  59834. /**
  59835. * 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).
  59836. */
  59837. this.slerpAmount = 1;
  59838. this._boneQuat = BABYLON.Quaternion.Identity();
  59839. this._slerping = false;
  59840. this._firstFrameSkipped = false;
  59841. this._fowardAxis = BABYLON.Vector3.Forward();
  59842. this.mesh = mesh;
  59843. this.bone = bone;
  59844. this.target = target;
  59845. if (options) {
  59846. if (options.adjustYaw) {
  59847. this.adjustYaw = options.adjustYaw;
  59848. }
  59849. if (options.adjustPitch) {
  59850. this.adjustPitch = options.adjustPitch;
  59851. }
  59852. if (options.adjustRoll) {
  59853. this.adjustRoll = options.adjustRoll;
  59854. }
  59855. if (options.maxYaw != null) {
  59856. this.maxYaw = options.maxYaw;
  59857. }
  59858. else {
  59859. this.maxYaw = Math.PI;
  59860. }
  59861. if (options.minYaw != null) {
  59862. this.minYaw = options.minYaw;
  59863. }
  59864. else {
  59865. this.minYaw = -Math.PI;
  59866. }
  59867. if (options.maxPitch != null) {
  59868. this.maxPitch = options.maxPitch;
  59869. }
  59870. else {
  59871. this.maxPitch = Math.PI;
  59872. }
  59873. if (options.minPitch != null) {
  59874. this.minPitch = options.minPitch;
  59875. }
  59876. else {
  59877. this.minPitch = -Math.PI;
  59878. }
  59879. if (options.slerpAmount != null) {
  59880. this.slerpAmount = options.slerpAmount;
  59881. }
  59882. if (options.upAxis != null) {
  59883. this.upAxis = options.upAxis;
  59884. }
  59885. if (options.upAxisSpace != null) {
  59886. this.upAxisSpace = options.upAxisSpace;
  59887. }
  59888. if (options.yawAxis != null || options.pitchAxis != null) {
  59889. var newYawAxis = BABYLON.Axis.Y;
  59890. var newPitchAxis = BABYLON.Axis.X;
  59891. if (options.yawAxis != null) {
  59892. newYawAxis = options.yawAxis.clone();
  59893. newYawAxis.normalize();
  59894. }
  59895. if (options.pitchAxis != null) {
  59896. newPitchAxis = options.pitchAxis.clone();
  59897. newPitchAxis.normalize();
  59898. }
  59899. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  59900. this._transformYawPitch = BABYLON.Matrix.Identity();
  59901. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  59902. this._transformYawPitchInv = this._transformYawPitch.clone();
  59903. this._transformYawPitch.invert();
  59904. }
  59905. }
  59906. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  59907. this.upAxisSpace = BABYLON.Space.LOCAL;
  59908. }
  59909. }
  59910. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  59911. /**
  59912. * Get/set the minimum yaw angle that the bone can look to.
  59913. */
  59914. get: function () {
  59915. return this._minYaw;
  59916. },
  59917. set: function (value) {
  59918. this._minYaw = value;
  59919. this._minYawSin = Math.sin(value);
  59920. this._minYawCos = Math.cos(value);
  59921. if (this._maxYaw != null) {
  59922. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  59923. this._yawRange = this._maxYaw - this._minYaw;
  59924. }
  59925. },
  59926. enumerable: true,
  59927. configurable: true
  59928. });
  59929. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  59930. /**
  59931. * Get/set the maximum yaw angle that the bone can look to.
  59932. */
  59933. get: function () {
  59934. return this._maxYaw;
  59935. },
  59936. set: function (value) {
  59937. this._maxYaw = value;
  59938. this._maxYawSin = Math.sin(value);
  59939. this._maxYawCos = Math.cos(value);
  59940. if (this._minYaw != null) {
  59941. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  59942. this._yawRange = this._maxYaw - this._minYaw;
  59943. }
  59944. },
  59945. enumerable: true,
  59946. configurable: true
  59947. });
  59948. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  59949. /**
  59950. * Get/set the minimum pitch angle that the bone can look to.
  59951. */
  59952. get: function () {
  59953. return this._minPitch;
  59954. },
  59955. set: function (value) {
  59956. this._minPitch = value;
  59957. this._minPitchTan = Math.tan(value);
  59958. },
  59959. enumerable: true,
  59960. configurable: true
  59961. });
  59962. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  59963. /**
  59964. * Get/set the maximum pitch angle that the bone can look to.
  59965. */
  59966. get: function () {
  59967. return this._maxPitch;
  59968. },
  59969. set: function (value) {
  59970. this._maxPitch = value;
  59971. this._maxPitchTan = Math.tan(value);
  59972. },
  59973. enumerable: true,
  59974. configurable: true
  59975. });
  59976. /**
  59977. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  59978. */
  59979. BoneLookController.prototype.update = function () {
  59980. //skip the first frame when slerping so that the mesh rotation is correct
  59981. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  59982. this._firstFrameSkipped = true;
  59983. return;
  59984. }
  59985. var bone = this.bone;
  59986. var bonePos = BoneLookController._tmpVecs[0];
  59987. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  59988. var target = this.target;
  59989. var _tmpMat1 = BoneLookController._tmpMats[0];
  59990. var _tmpMat2 = BoneLookController._tmpMats[1];
  59991. var mesh = this.mesh;
  59992. var parentBone = bone.getParent();
  59993. var upAxis = BoneLookController._tmpVecs[1];
  59994. upAxis.copyFrom(this.upAxis);
  59995. if (this.upAxisSpace == BABYLON.Space.BONE) {
  59996. if (this._transformYawPitch) {
  59997. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  59998. }
  59999. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  60000. }
  60001. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  60002. mesh.getDirectionToRef(upAxis, upAxis);
  60003. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  60004. upAxis.normalize();
  60005. }
  60006. }
  60007. var checkYaw = false;
  60008. var checkPitch = false;
  60009. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  60010. checkYaw = true;
  60011. }
  60012. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  60013. checkPitch = true;
  60014. }
  60015. if (checkYaw || checkPitch) {
  60016. var spaceMat = BoneLookController._tmpMats[2];
  60017. var spaceMatInv = BoneLookController._tmpMats[3];
  60018. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  60019. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  60020. }
  60021. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  60022. spaceMat.copyFrom(mesh.getWorldMatrix());
  60023. }
  60024. else {
  60025. var forwardAxis = BoneLookController._tmpVecs[2];
  60026. forwardAxis.copyFrom(this._fowardAxis);
  60027. if (this._transformYawPitch) {
  60028. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  60029. }
  60030. if (parentBone) {
  60031. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  60032. }
  60033. else {
  60034. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  60035. }
  60036. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  60037. rightAxis.normalize();
  60038. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  60039. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  60040. }
  60041. spaceMat.invertToRef(spaceMatInv);
  60042. var xzlen;
  60043. if (checkPitch) {
  60044. var localTarget = BoneLookController._tmpVecs[3];
  60045. target.subtractToRef(bonePos, localTarget);
  60046. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  60047. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  60048. var pitch = Math.atan2(localTarget.y, xzlen);
  60049. var newPitch = pitch;
  60050. if (pitch > this._maxPitch) {
  60051. localTarget.y = this._maxPitchTan * xzlen;
  60052. newPitch = this._maxPitch;
  60053. }
  60054. else if (pitch < this._minPitch) {
  60055. localTarget.y = this._minPitchTan * xzlen;
  60056. newPitch = this._minPitch;
  60057. }
  60058. if (pitch != newPitch) {
  60059. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  60060. localTarget.addInPlace(bonePos);
  60061. target = localTarget;
  60062. }
  60063. }
  60064. if (checkYaw) {
  60065. var localTarget = BoneLookController._tmpVecs[4];
  60066. target.subtractToRef(bonePos, localTarget);
  60067. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  60068. var yaw = Math.atan2(localTarget.x, localTarget.z);
  60069. var newYaw = yaw;
  60070. if (yaw > this._maxYaw || yaw < this._minYaw) {
  60071. if (xzlen == null) {
  60072. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  60073. }
  60074. if (this._yawRange > Math.PI) {
  60075. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  60076. localTarget.z = this._maxYawCos * xzlen;
  60077. localTarget.x = this._maxYawSin * xzlen;
  60078. newYaw = this._maxYaw;
  60079. }
  60080. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  60081. localTarget.z = this._minYawCos * xzlen;
  60082. localTarget.x = this._minYawSin * xzlen;
  60083. newYaw = this._minYaw;
  60084. }
  60085. }
  60086. else {
  60087. if (yaw > this._maxYaw) {
  60088. localTarget.z = this._maxYawCos * xzlen;
  60089. localTarget.x = this._maxYawSin * xzlen;
  60090. newYaw = this._maxYaw;
  60091. }
  60092. else if (yaw < this._minYaw) {
  60093. localTarget.z = this._minYawCos * xzlen;
  60094. localTarget.x = this._minYawSin * xzlen;
  60095. newYaw = this._minYaw;
  60096. }
  60097. }
  60098. }
  60099. if (this._slerping && this._yawRange > Math.PI) {
  60100. //are we going to be crossing into the min/max region?
  60101. var boneFwd = BoneLookController._tmpVecs[8];
  60102. boneFwd.copyFrom(BABYLON.Axis.Z);
  60103. if (this._transformYawPitch) {
  60104. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  60105. }
  60106. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  60107. this._boneQuat.toRotationMatrix(boneRotMat);
  60108. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  60109. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  60110. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  60111. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  60112. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  60113. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  60114. if (angBtwTar > angBtwMidYaw) {
  60115. if (xzlen == null) {
  60116. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  60117. }
  60118. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  60119. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  60120. if (angBtwMin < angBtwMax) {
  60121. newYaw = boneYaw + Math.PI * .75;
  60122. localTarget.z = Math.cos(newYaw) * xzlen;
  60123. localTarget.x = Math.sin(newYaw) * xzlen;
  60124. }
  60125. else {
  60126. newYaw = boneYaw - Math.PI * .75;
  60127. localTarget.z = Math.cos(newYaw) * xzlen;
  60128. localTarget.x = Math.sin(newYaw) * xzlen;
  60129. }
  60130. }
  60131. }
  60132. if (yaw != newYaw) {
  60133. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  60134. localTarget.addInPlace(bonePos);
  60135. target = localTarget;
  60136. }
  60137. }
  60138. }
  60139. var zaxis = BoneLookController._tmpVecs[5];
  60140. var xaxis = BoneLookController._tmpVecs[6];
  60141. var yaxis = BoneLookController._tmpVecs[7];
  60142. var _tmpQuat = BoneLookController._tmpQuat;
  60143. target.subtractToRef(bonePos, zaxis);
  60144. zaxis.normalize();
  60145. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  60146. xaxis.normalize();
  60147. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  60148. yaxis.normalize();
  60149. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  60150. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  60151. return;
  60152. }
  60153. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  60154. return;
  60155. }
  60156. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  60157. return;
  60158. }
  60159. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  60160. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  60161. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  60162. }
  60163. if (this.slerpAmount < 1) {
  60164. if (!this._slerping) {
  60165. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  60166. }
  60167. if (this._transformYawPitch) {
  60168. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  60169. }
  60170. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  60171. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  60172. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  60173. this._slerping = true;
  60174. }
  60175. else {
  60176. if (this._transformYawPitch) {
  60177. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  60178. }
  60179. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  60180. this._slerping = false;
  60181. }
  60182. };
  60183. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  60184. var angDiff = ang2 - ang1;
  60185. angDiff %= Math.PI * 2;
  60186. if (angDiff > Math.PI) {
  60187. angDiff -= Math.PI * 2;
  60188. }
  60189. else if (angDiff < -Math.PI) {
  60190. angDiff += Math.PI * 2;
  60191. }
  60192. return angDiff;
  60193. };
  60194. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  60195. ang1 %= (2 * Math.PI);
  60196. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  60197. ang2 %= (2 * Math.PI);
  60198. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  60199. var ab = 0;
  60200. if (ang1 < ang2) {
  60201. ab = ang2 - ang1;
  60202. }
  60203. else {
  60204. ab = ang1 - ang2;
  60205. }
  60206. if (ab > Math.PI) {
  60207. ab = Math.PI * 2 - ab;
  60208. }
  60209. return ab;
  60210. };
  60211. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  60212. ang %= (2 * Math.PI);
  60213. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  60214. ang1 %= (2 * Math.PI);
  60215. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  60216. ang2 %= (2 * Math.PI);
  60217. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  60218. if (ang1 < ang2) {
  60219. if (ang > ang1 && ang < ang2) {
  60220. return true;
  60221. }
  60222. }
  60223. else {
  60224. if (ang > ang2 && ang < ang1) {
  60225. return true;
  60226. }
  60227. }
  60228. return false;
  60229. };
  60230. 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()];
  60231. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  60232. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  60233. return BoneLookController;
  60234. }());
  60235. BABYLON.BoneLookController = BoneLookController;
  60236. })(BABYLON || (BABYLON = {}));
  60237. //# sourceMappingURL=babylon.boneLookController.js.map
  60238. var BABYLON;
  60239. (function (BABYLON) {
  60240. var Skeleton = (function () {
  60241. function Skeleton(name, id, scene) {
  60242. this.name = name;
  60243. this.id = id;
  60244. this.bones = new Array();
  60245. this.needInitialSkinMatrix = false;
  60246. this._isDirty = true;
  60247. this._meshesWithPoseMatrix = new Array();
  60248. this._identity = BABYLON.Matrix.Identity();
  60249. this._ranges = {};
  60250. this._lastAbsoluteTransformsUpdateId = -1;
  60251. // Events
  60252. /**
  60253. * An event triggered before computing the skeleton's matrices
  60254. * @type {BABYLON.Observable}
  60255. */
  60256. this.onBeforeComputeObservable = new BABYLON.Observable();
  60257. this.bones = [];
  60258. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60259. scene.skeletons.push(this);
  60260. //make sure it will recalculate the matrix next time prepare is called.
  60261. this._isDirty = true;
  60262. }
  60263. // Members
  60264. Skeleton.prototype.getTransformMatrices = function (mesh) {
  60265. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  60266. return mesh._bonesTransformMatrices;
  60267. }
  60268. if (!this._transformMatrices) {
  60269. this.prepare();
  60270. }
  60271. return this._transformMatrices;
  60272. };
  60273. Skeleton.prototype.getScene = function () {
  60274. return this._scene;
  60275. };
  60276. // Methods
  60277. /**
  60278. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  60279. */
  60280. Skeleton.prototype.toString = function (fullDetails) {
  60281. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  60282. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  60283. if (fullDetails) {
  60284. ret += ", Ranges: {";
  60285. var first = true;
  60286. for (var name_1 in this._ranges) {
  60287. if (first) {
  60288. ret += ", ";
  60289. first = false;
  60290. }
  60291. ret += name_1;
  60292. }
  60293. ret += "}";
  60294. }
  60295. return ret;
  60296. };
  60297. /**
  60298. * Get bone's index searching by name
  60299. * @param {string} name is bone's name to search for
  60300. * @return {number} Indice of the bone. Returns -1 if not found
  60301. */
  60302. Skeleton.prototype.getBoneIndexByName = function (name) {
  60303. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  60304. if (this.bones[boneIndex].name === name) {
  60305. return boneIndex;
  60306. }
  60307. }
  60308. return -1;
  60309. };
  60310. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  60311. // check name not already in use
  60312. if (!this._ranges[name]) {
  60313. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  60314. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  60315. if (this.bones[i].animations[0]) {
  60316. this.bones[i].animations[0].createRange(name, from, to);
  60317. }
  60318. }
  60319. }
  60320. };
  60321. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  60322. if (deleteFrames === void 0) { deleteFrames = true; }
  60323. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  60324. if (this.bones[i].animations[0]) {
  60325. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  60326. }
  60327. }
  60328. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  60329. };
  60330. Skeleton.prototype.getAnimationRange = function (name) {
  60331. return this._ranges[name];
  60332. };
  60333. /**
  60334. * Returns as an Array, all AnimationRanges defined on this skeleton
  60335. */
  60336. Skeleton.prototype.getAnimationRanges = function () {
  60337. var animationRanges = [];
  60338. var name;
  60339. var i = 0;
  60340. for (name in this._ranges) {
  60341. animationRanges[i] = this._ranges[name];
  60342. i++;
  60343. }
  60344. return animationRanges;
  60345. };
  60346. /**
  60347. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  60348. */
  60349. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  60350. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  60351. if (this._ranges[name] || !source.getAnimationRange(name)) {
  60352. return false;
  60353. }
  60354. var ret = true;
  60355. var frameOffset = this._getHighestAnimationFrame() + 1;
  60356. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  60357. var boneDict = {};
  60358. var sourceBones = source.bones;
  60359. var nBones;
  60360. var i;
  60361. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  60362. boneDict[sourceBones[i].name] = sourceBones[i];
  60363. }
  60364. if (this.bones.length !== sourceBones.length) {
  60365. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  60366. ret = false;
  60367. }
  60368. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  60369. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  60370. var boneName = this.bones[i].name;
  60371. var sourceBone = boneDict[boneName];
  60372. if (sourceBone) {
  60373. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  60374. }
  60375. else {
  60376. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  60377. ret = false;
  60378. }
  60379. }
  60380. // do not call createAnimationRange(), since it also is done to bones, which was already done
  60381. var range = source.getAnimationRange(name);
  60382. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  60383. return ret;
  60384. };
  60385. Skeleton.prototype.returnToRest = function () {
  60386. for (var index = 0; index < this.bones.length; index++) {
  60387. this.bones[index].returnToRest();
  60388. }
  60389. };
  60390. Skeleton.prototype._getHighestAnimationFrame = function () {
  60391. var ret = 0;
  60392. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  60393. if (this.bones[i].animations[0]) {
  60394. var highest = this.bones[i].animations[0].getHighestFrame();
  60395. if (ret < highest) {
  60396. ret = highest;
  60397. }
  60398. }
  60399. }
  60400. return ret;
  60401. };
  60402. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  60403. var range = this.getAnimationRange(name);
  60404. if (!range) {
  60405. return null;
  60406. }
  60407. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  60408. };
  60409. Skeleton.prototype._markAsDirty = function () {
  60410. this._isDirty = true;
  60411. };
  60412. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  60413. this._meshesWithPoseMatrix.push(mesh);
  60414. };
  60415. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  60416. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  60417. if (index > -1) {
  60418. this._meshesWithPoseMatrix.splice(index, 1);
  60419. }
  60420. };
  60421. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  60422. this.onBeforeComputeObservable.notifyObservers(this);
  60423. for (var index = 0; index < this.bones.length; index++) {
  60424. var bone = this.bones[index];
  60425. var parentBone = bone.getParent();
  60426. if (parentBone) {
  60427. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  60428. }
  60429. else {
  60430. if (initialSkinMatrix) {
  60431. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  60432. }
  60433. else {
  60434. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  60435. }
  60436. }
  60437. if (bone._index !== -1) {
  60438. var mappedIndex = bone._index === undefined ? index : bone._index;
  60439. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  60440. }
  60441. }
  60442. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  60443. };
  60444. Skeleton.prototype.prepare = function () {
  60445. if (!this._isDirty) {
  60446. return;
  60447. }
  60448. if (this.needInitialSkinMatrix) {
  60449. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  60450. var mesh = this._meshesWithPoseMatrix[index];
  60451. var poseMatrix = mesh.getPoseMatrix();
  60452. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  60453. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  60454. }
  60455. if (this._synchronizedWithMesh !== mesh) {
  60456. this._synchronizedWithMesh = mesh;
  60457. // Prepare bones
  60458. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  60459. var bone = this.bones[boneIndex];
  60460. if (!bone.getParent()) {
  60461. var matrix = bone.getBaseMatrix();
  60462. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  60463. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  60464. }
  60465. }
  60466. }
  60467. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  60468. }
  60469. }
  60470. else {
  60471. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  60472. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  60473. }
  60474. this._computeTransformMatrices(this._transformMatrices, null);
  60475. }
  60476. this._isDirty = false;
  60477. this._scene._activeBones.addCount(this.bones.length, false);
  60478. };
  60479. Skeleton.prototype.getAnimatables = function () {
  60480. if (!this._animatables || this._animatables.length !== this.bones.length) {
  60481. this._animatables = [];
  60482. for (var index = 0; index < this.bones.length; index++) {
  60483. this._animatables.push(this.bones[index]);
  60484. }
  60485. }
  60486. return this._animatables;
  60487. };
  60488. Skeleton.prototype.clone = function (name, id) {
  60489. var result = new Skeleton(name, id || name, this._scene);
  60490. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  60491. for (var index = 0; index < this.bones.length; index++) {
  60492. var source = this.bones[index];
  60493. var parentBone = null;
  60494. if (source.getParent()) {
  60495. var parentIndex = this.bones.indexOf(source.getParent());
  60496. parentBone = result.bones[parentIndex];
  60497. }
  60498. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  60499. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  60500. }
  60501. if (this._ranges) {
  60502. result._ranges = {};
  60503. for (var rangeName in this._ranges) {
  60504. result._ranges[rangeName] = this._ranges[rangeName].clone();
  60505. }
  60506. }
  60507. this._isDirty = true;
  60508. return result;
  60509. };
  60510. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  60511. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  60512. this.bones.forEach(function (bone) {
  60513. bone.animations.forEach(function (animation) {
  60514. animation.enableBlending = true;
  60515. animation.blendingSpeed = blendingSpeed;
  60516. });
  60517. });
  60518. };
  60519. Skeleton.prototype.dispose = function () {
  60520. this._meshesWithPoseMatrix = [];
  60521. // Animations
  60522. this.getScene().stopAnimation(this);
  60523. // Remove from scene
  60524. this.getScene().removeSkeleton(this);
  60525. };
  60526. Skeleton.prototype.serialize = function () {
  60527. var serializationObject = {};
  60528. serializationObject.name = this.name;
  60529. serializationObject.id = this.id;
  60530. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  60531. serializationObject.bones = [];
  60532. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  60533. for (var index = 0; index < this.bones.length; index++) {
  60534. var bone = this.bones[index];
  60535. var serializedBone = {
  60536. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  60537. name: bone.name,
  60538. matrix: bone.getBaseMatrix().toArray(),
  60539. rest: bone.getRestPose().toArray()
  60540. };
  60541. serializationObject.bones.push(serializedBone);
  60542. if (bone.length) {
  60543. serializedBone.length = bone.length;
  60544. }
  60545. if (bone.animations && bone.animations.length > 0) {
  60546. serializedBone.animation = bone.animations[0].serialize();
  60547. }
  60548. serializationObject.ranges = [];
  60549. for (var name in this._ranges) {
  60550. var range = {};
  60551. range.name = name;
  60552. range.from = this._ranges[name].from;
  60553. range.to = this._ranges[name].to;
  60554. serializationObject.ranges.push(range);
  60555. }
  60556. }
  60557. return serializationObject;
  60558. };
  60559. Skeleton.Parse = function (parsedSkeleton, scene) {
  60560. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  60561. if (parsedSkeleton.dimensionsAtRest) {
  60562. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  60563. }
  60564. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  60565. var index;
  60566. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  60567. var parsedBone = parsedSkeleton.bones[index];
  60568. var parentBone = null;
  60569. if (parsedBone.parentBoneIndex > -1) {
  60570. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  60571. }
  60572. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  60573. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  60574. if (parsedBone.length) {
  60575. bone.length = parsedBone.length;
  60576. }
  60577. if (parsedBone.animation) {
  60578. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  60579. }
  60580. }
  60581. // placed after bones, so createAnimationRange can cascade down
  60582. if (parsedSkeleton.ranges) {
  60583. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  60584. var data = parsedSkeleton.ranges[index];
  60585. skeleton.createAnimationRange(data.name, data.from, data.to);
  60586. }
  60587. }
  60588. return skeleton;
  60589. };
  60590. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  60591. if (forceUpdate === void 0) { forceUpdate = false; }
  60592. var renderId = this._scene.getRenderId();
  60593. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  60594. this.bones[0].computeAbsoluteTransforms();
  60595. this._lastAbsoluteTransformsUpdateId = renderId;
  60596. }
  60597. };
  60598. Skeleton.prototype.getPoseMatrix = function () {
  60599. var poseMatrix;
  60600. if (this._meshesWithPoseMatrix.length > 0) {
  60601. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  60602. }
  60603. return poseMatrix;
  60604. };
  60605. Skeleton.prototype.sortBones = function () {
  60606. var bones = new Array();
  60607. var visited = new Array(this.bones.length);
  60608. for (var index = 0; index < this.bones.length; index++) {
  60609. this._sortBones(index, bones, visited);
  60610. }
  60611. this.bones = bones;
  60612. };
  60613. Skeleton.prototype._sortBones = function (index, bones, visited) {
  60614. if (visited[index]) {
  60615. return;
  60616. }
  60617. visited[index] = true;
  60618. var bone = this.bones[index];
  60619. if (bone._index === undefined) {
  60620. bone._index = index;
  60621. }
  60622. var parentBone = bone.getParent();
  60623. if (parentBone) {
  60624. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  60625. }
  60626. bones.push(bone);
  60627. };
  60628. return Skeleton;
  60629. }());
  60630. BABYLON.Skeleton = Skeleton;
  60631. })(BABYLON || (BABYLON = {}));
  60632. //# sourceMappingURL=babylon.skeleton.js.map
  60633. var BABYLON;
  60634. (function (BABYLON) {
  60635. var SphericalPolynomial = (function () {
  60636. function SphericalPolynomial() {
  60637. this.x = BABYLON.Vector3.Zero();
  60638. this.y = BABYLON.Vector3.Zero();
  60639. this.z = BABYLON.Vector3.Zero();
  60640. this.xx = BABYLON.Vector3.Zero();
  60641. this.yy = BABYLON.Vector3.Zero();
  60642. this.zz = BABYLON.Vector3.Zero();
  60643. this.xy = BABYLON.Vector3.Zero();
  60644. this.yz = BABYLON.Vector3.Zero();
  60645. this.zx = BABYLON.Vector3.Zero();
  60646. }
  60647. SphericalPolynomial.prototype.addAmbient = function (color) {
  60648. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  60649. this.xx = this.xx.add(colorVector);
  60650. this.yy = this.yy.add(colorVector);
  60651. this.zz = this.zz.add(colorVector);
  60652. };
  60653. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  60654. var result = new SphericalPolynomial();
  60655. result.x = harmonics.L11.scale(1.02333);
  60656. result.y = harmonics.L1_1.scale(1.02333);
  60657. result.z = harmonics.L10.scale(1.02333);
  60658. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  60659. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  60660. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  60661. result.yz = harmonics.L2_1.scale(0.858086);
  60662. result.zx = harmonics.L21.scale(0.858086);
  60663. result.xy = harmonics.L2_2.scale(0.858086);
  60664. result.scale(1.0 / Math.PI);
  60665. return result;
  60666. };
  60667. SphericalPolynomial.prototype.scale = function (scale) {
  60668. this.x = this.x.scale(scale);
  60669. this.y = this.y.scale(scale);
  60670. this.z = this.z.scale(scale);
  60671. this.xx = this.xx.scale(scale);
  60672. this.yy = this.yy.scale(scale);
  60673. this.zz = this.zz.scale(scale);
  60674. this.yz = this.yz.scale(scale);
  60675. this.zx = this.zx.scale(scale);
  60676. this.xy = this.xy.scale(scale);
  60677. };
  60678. return SphericalPolynomial;
  60679. }());
  60680. BABYLON.SphericalPolynomial = SphericalPolynomial;
  60681. var SphericalHarmonics = (function () {
  60682. function SphericalHarmonics() {
  60683. this.L00 = BABYLON.Vector3.Zero();
  60684. this.L1_1 = BABYLON.Vector3.Zero();
  60685. this.L10 = BABYLON.Vector3.Zero();
  60686. this.L11 = BABYLON.Vector3.Zero();
  60687. this.L2_2 = BABYLON.Vector3.Zero();
  60688. this.L2_1 = BABYLON.Vector3.Zero();
  60689. this.L20 = BABYLON.Vector3.Zero();
  60690. this.L21 = BABYLON.Vector3.Zero();
  60691. this.L22 = BABYLON.Vector3.Zero();
  60692. }
  60693. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  60694. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  60695. var c = colorVector.scale(deltaSolidAngle);
  60696. this.L00 = this.L00.add(c.scale(0.282095));
  60697. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  60698. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  60699. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  60700. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  60701. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  60702. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  60703. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  60704. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  60705. };
  60706. SphericalHarmonics.prototype.scale = function (scale) {
  60707. this.L00 = this.L00.scale(scale);
  60708. this.L1_1 = this.L1_1.scale(scale);
  60709. this.L10 = this.L10.scale(scale);
  60710. this.L11 = this.L11.scale(scale);
  60711. this.L2_2 = this.L2_2.scale(scale);
  60712. this.L2_1 = this.L2_1.scale(scale);
  60713. this.L20 = this.L20.scale(scale);
  60714. this.L21 = this.L21.scale(scale);
  60715. this.L22 = this.L22.scale(scale);
  60716. };
  60717. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  60718. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  60719. //
  60720. // E_lm = A_l * L_lm
  60721. //
  60722. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  60723. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  60724. // the scaling factors are given in equation 9.
  60725. // Constant (Band 0)
  60726. this.L00 = this.L00.scale(3.141593);
  60727. // Linear (Band 1)
  60728. this.L1_1 = this.L1_1.scale(2.094395);
  60729. this.L10 = this.L10.scale(2.094395);
  60730. this.L11 = this.L11.scale(2.094395);
  60731. // Quadratic (Band 2)
  60732. this.L2_2 = this.L2_2.scale(0.785398);
  60733. this.L2_1 = this.L2_1.scale(0.785398);
  60734. this.L20 = this.L20.scale(0.785398);
  60735. this.L21 = this.L21.scale(0.785398);
  60736. this.L22 = this.L22.scale(0.785398);
  60737. };
  60738. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  60739. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  60740. // L = (1/pi) * E * rho
  60741. //
  60742. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  60743. this.scale(1.0 / Math.PI);
  60744. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  60745. // (The pixel shader must apply albedo after texture fetches, etc).
  60746. };
  60747. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  60748. var result = new SphericalHarmonics();
  60749. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  60750. result.L1_1 = polynomial.y.scale(0.977204);
  60751. result.L10 = polynomial.z.scale(0.977204);
  60752. result.L11 = polynomial.x.scale(0.977204);
  60753. result.L2_2 = polynomial.xy.scale(1.16538);
  60754. result.L2_1 = polynomial.yz.scale(1.16538);
  60755. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  60756. result.L21 = polynomial.zx.scale(1.16538);
  60757. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  60758. result.scale(Math.PI);
  60759. return result;
  60760. };
  60761. return SphericalHarmonics;
  60762. }());
  60763. BABYLON.SphericalHarmonics = SphericalHarmonics;
  60764. })(BABYLON || (BABYLON = {}));
  60765. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  60766. var BABYLON;
  60767. (function (BABYLON) {
  60768. var Internals;
  60769. (function (Internals) {
  60770. var FileFaceOrientation = (function () {
  60771. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  60772. this.name = name;
  60773. this.worldAxisForNormal = worldAxisForNormal;
  60774. this.worldAxisForFileX = worldAxisForFileX;
  60775. this.worldAxisForFileY = worldAxisForFileY;
  60776. }
  60777. return FileFaceOrientation;
  60778. }());
  60779. ;
  60780. /**
  60781. * Helper class dealing with the extraction of spherical polynomial dataArray
  60782. * from a cube map.
  60783. */
  60784. var CubeMapToSphericalPolynomialTools = (function () {
  60785. function CubeMapToSphericalPolynomialTools() {
  60786. }
  60787. /**
  60788. * Converts a texture to the according Spherical Polynomial data.
  60789. * This extracts the first 3 orders only as they are the only one used in the lighting.
  60790. *
  60791. * @param texture The texture to extract the information from.
  60792. * @return The Spherical Polynomial data.
  60793. */
  60794. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  60795. if (!texture.isCube) {
  60796. // Only supports cube Textures currently.
  60797. return null;
  60798. }
  60799. var size = texture.getSize().width;
  60800. var right = texture.readPixels(0);
  60801. var left = texture.readPixels(1);
  60802. var up;
  60803. var down;
  60804. if (texture.isRenderTarget) {
  60805. up = texture.readPixels(3);
  60806. down = texture.readPixels(2);
  60807. }
  60808. else {
  60809. up = texture.readPixels(2);
  60810. down = texture.readPixels(3);
  60811. }
  60812. var front = texture.readPixels(4);
  60813. var back = texture.readPixels(5);
  60814. var gammaSpace = texture.gammaSpace;
  60815. // Always read as RGBA.
  60816. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  60817. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60818. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60819. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60820. }
  60821. var cubeInfo = {
  60822. size: size,
  60823. right: right,
  60824. left: left,
  60825. up: up,
  60826. down: down,
  60827. front: front,
  60828. back: back,
  60829. format: format,
  60830. type: type,
  60831. gammaSpace: gammaSpace,
  60832. };
  60833. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  60834. };
  60835. /**
  60836. * Converts a cubemap to the according Spherical Polynomial data.
  60837. * This extracts the first 3 orders only as they are the only one used in the lighting.
  60838. *
  60839. * @param cubeInfo The Cube map to extract the information from.
  60840. * @return The Spherical Polynomial data.
  60841. */
  60842. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  60843. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  60844. var totalSolidAngle = 0.0;
  60845. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  60846. var du = 2.0 / cubeInfo.size;
  60847. var dv = du;
  60848. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  60849. var minUV = du * 0.5 - 1.0;
  60850. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  60851. var fileFace = this.FileFaces[faceIndex];
  60852. var dataArray = cubeInfo[fileFace.name];
  60853. var v = minUV;
  60854. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  60855. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  60856. // Because SP is still linear, so summation is fine in that basis.
  60857. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  60858. for (var y = 0; y < cubeInfo.size; y++) {
  60859. var u = minUV;
  60860. for (var x = 0; x < cubeInfo.size; x++) {
  60861. // World direction (not normalised)
  60862. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  60863. worldDirection.normalize();
  60864. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  60865. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  60866. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  60867. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  60868. // Handle Integer types.
  60869. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60870. r /= 255;
  60871. g /= 255;
  60872. b /= 255;
  60873. }
  60874. // Handle Gamma space textures.
  60875. if (cubeInfo.gammaSpace) {
  60876. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  60877. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  60878. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  60879. }
  60880. var color = new BABYLON.Color3(r, g, b);
  60881. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  60882. totalSolidAngle += deltaSolidAngle;
  60883. u += du;
  60884. }
  60885. v += dv;
  60886. }
  60887. }
  60888. // Solid angle for entire sphere is 4*pi
  60889. var sphereSolidAngle = 4.0 * Math.PI;
  60890. // Adjust the solid angle to allow for how many faces we processed.
  60891. var facesProcessed = 6.0;
  60892. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  60893. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  60894. // This is needed because the numerical integration over the cube uses a
  60895. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  60896. // and also to compensate for accumulative error due to float precision in the summation.
  60897. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  60898. sphericalHarmonics.scale(correctionFactor);
  60899. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  60900. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  60901. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  60902. };
  60903. CubeMapToSphericalPolynomialTools.FileFaces = [
  60904. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  60905. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  60906. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  60907. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  60908. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  60909. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  60910. ];
  60911. return CubeMapToSphericalPolynomialTools;
  60912. }());
  60913. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  60914. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60915. })(BABYLON || (BABYLON = {}));
  60916. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  60917. var BABYLON;
  60918. (function (BABYLON) {
  60919. var Internals;
  60920. (function (Internals) {
  60921. /**
  60922. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  60923. */
  60924. var PanoramaToCubeMapTools = (function () {
  60925. function PanoramaToCubeMapTools() {
  60926. }
  60927. /**
  60928. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  60929. *
  60930. * @param float32Array The source data.
  60931. * @param inputWidth The width of the input panorama.
  60932. * @param inputhHeight The height of the input panorama.
  60933. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  60934. * @return The cubemap data
  60935. */
  60936. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  60937. if (!float32Array) {
  60938. throw "ConvertPanoramaToCubemap: input cannot be null";
  60939. }
  60940. if (float32Array.length != inputWidth * inputHeight * 3) {
  60941. throw "ConvertPanoramaToCubemap: input size is wrong";
  60942. }
  60943. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  60944. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  60945. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  60946. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  60947. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  60948. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  60949. return {
  60950. front: textureFront,
  60951. back: textureBack,
  60952. left: textureLeft,
  60953. right: textureRight,
  60954. up: textureUp,
  60955. down: textureDown,
  60956. size: size,
  60957. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  60958. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  60959. gammaSpace: false,
  60960. };
  60961. };
  60962. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  60963. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  60964. var textureArray = new Float32Array(buffer);
  60965. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  60966. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  60967. var dy = 1 / texSize;
  60968. var fy = 0;
  60969. for (var y = 0; y < texSize; y++) {
  60970. var xv1 = faceData[0];
  60971. var xv2 = faceData[2];
  60972. for (var x = 0; x < texSize; x++) {
  60973. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  60974. v.normalize();
  60975. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  60976. // 3 channels per pixels
  60977. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  60978. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  60979. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  60980. xv1 = xv1.add(rotDX1);
  60981. xv2 = xv2.add(rotDX2);
  60982. }
  60983. fy += dy;
  60984. }
  60985. return textureArray;
  60986. };
  60987. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  60988. var theta = Math.atan2(vDir.z, vDir.x);
  60989. var phi = Math.acos(vDir.y);
  60990. while (theta < -Math.PI)
  60991. theta += 2 * Math.PI;
  60992. while (theta > Math.PI)
  60993. theta -= 2 * Math.PI;
  60994. var dx = theta / Math.PI;
  60995. var dy = phi / Math.PI;
  60996. // recenter.
  60997. dx = dx * 0.5 + 0.5;
  60998. var px = Math.round(dx * inputWidth);
  60999. if (px < 0)
  61000. px = 0;
  61001. else if (px >= inputWidth)
  61002. px = inputWidth - 1;
  61003. var py = Math.round(dy * inputHeight);
  61004. if (py < 0)
  61005. py = 0;
  61006. else if (py >= inputHeight)
  61007. py = inputHeight - 1;
  61008. var inputY = (inputHeight - py - 1);
  61009. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  61010. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  61011. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  61012. return {
  61013. r: r,
  61014. g: g,
  61015. b: b
  61016. };
  61017. };
  61018. PanoramaToCubeMapTools.FACE_FRONT = [
  61019. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  61020. new BABYLON.Vector3(1.0, -1.0, -1.0),
  61021. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  61022. new BABYLON.Vector3(1.0, 1.0, -1.0)
  61023. ];
  61024. PanoramaToCubeMapTools.FACE_BACK = [
  61025. new BABYLON.Vector3(1.0, -1.0, 1.0),
  61026. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  61027. new BABYLON.Vector3(1.0, 1.0, 1.0),
  61028. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  61029. ];
  61030. PanoramaToCubeMapTools.FACE_RIGHT = [
  61031. new BABYLON.Vector3(1.0, -1.0, -1.0),
  61032. new BABYLON.Vector3(1.0, -1.0, 1.0),
  61033. new BABYLON.Vector3(1.0, 1.0, -1.0),
  61034. new BABYLON.Vector3(1.0, 1.0, 1.0)
  61035. ];
  61036. PanoramaToCubeMapTools.FACE_LEFT = [
  61037. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  61038. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  61039. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  61040. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  61041. ];
  61042. PanoramaToCubeMapTools.FACE_DOWN = [
  61043. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  61044. new BABYLON.Vector3(1.0, 1.0, -1.0),
  61045. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  61046. new BABYLON.Vector3(1.0, 1.0, 1.0)
  61047. ];
  61048. PanoramaToCubeMapTools.FACE_UP = [
  61049. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  61050. new BABYLON.Vector3(1.0, -1.0, 1.0),
  61051. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  61052. new BABYLON.Vector3(1.0, -1.0, -1.0)
  61053. ];
  61054. return PanoramaToCubeMapTools;
  61055. }());
  61056. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  61057. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  61058. })(BABYLON || (BABYLON = {}));
  61059. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  61060. var BABYLON;
  61061. (function (BABYLON) {
  61062. var Internals;
  61063. (function (Internals) {
  61064. ;
  61065. /**
  61066. * This groups tools to convert HDR texture to native colors array.
  61067. */
  61068. var HDRTools = (function () {
  61069. function HDRTools() {
  61070. }
  61071. HDRTools.Ldexp = function (mantissa, exponent) {
  61072. if (exponent > 1023) {
  61073. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  61074. }
  61075. if (exponent < -1074) {
  61076. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  61077. }
  61078. return mantissa * Math.pow(2, exponent);
  61079. };
  61080. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  61081. if (exponent > 0) {
  61082. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  61083. float32array[index + 0] = red * exponent;
  61084. float32array[index + 1] = green * exponent;
  61085. float32array[index + 2] = blue * exponent;
  61086. }
  61087. else {
  61088. float32array[index + 0] = 0;
  61089. float32array[index + 1] = 0;
  61090. float32array[index + 2] = 0;
  61091. }
  61092. };
  61093. HDRTools.readStringLine = function (uint8array, startIndex) {
  61094. var line = "";
  61095. var character = "";
  61096. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  61097. character = String.fromCharCode(uint8array[i]);
  61098. if (character == "\n") {
  61099. break;
  61100. }
  61101. line += character;
  61102. }
  61103. return line;
  61104. };
  61105. /**
  61106. * Reads header information from an RGBE texture stored in a native array.
  61107. * More information on this format are available here:
  61108. * https://en.wikipedia.org/wiki/RGBE_image_format
  61109. *
  61110. * @param uint8array The binary file stored in native array.
  61111. * @return The header information.
  61112. */
  61113. HDRTools.RGBE_ReadHeader = function (uint8array) {
  61114. var height = 0;
  61115. var width = 0;
  61116. var line = this.readStringLine(uint8array, 0);
  61117. if (line[0] != '#' || line[1] != '?') {
  61118. throw "Bad HDR Format.";
  61119. }
  61120. var endOfHeader = false;
  61121. var findFormat = false;
  61122. var lineIndex = 0;
  61123. do {
  61124. lineIndex += (line.length + 1);
  61125. line = this.readStringLine(uint8array, lineIndex);
  61126. if (line == "FORMAT=32-bit_rle_rgbe") {
  61127. findFormat = true;
  61128. }
  61129. else if (line.length == 0) {
  61130. endOfHeader = true;
  61131. }
  61132. } while (!endOfHeader);
  61133. if (!findFormat) {
  61134. throw "HDR Bad header format, unsupported FORMAT";
  61135. }
  61136. lineIndex += (line.length + 1);
  61137. line = this.readStringLine(uint8array, lineIndex);
  61138. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  61139. var match = sizeRegexp.exec(line);
  61140. // TODO. Support +Y and -X if needed.
  61141. if (match.length < 3) {
  61142. throw "HDR Bad header format, no size";
  61143. }
  61144. width = parseInt(match[2]);
  61145. height = parseInt(match[1]);
  61146. if (width < 8 || width > 0x7fff) {
  61147. throw "HDR Bad header format, unsupported size";
  61148. }
  61149. lineIndex += (line.length + 1);
  61150. return {
  61151. height: height,
  61152. width: width,
  61153. dataPosition: lineIndex
  61154. };
  61155. };
  61156. /**
  61157. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  61158. * This RGBE texture needs to store the information as a panorama.
  61159. *
  61160. * More information on this format are available here:
  61161. * https://en.wikipedia.org/wiki/RGBE_image_format
  61162. *
  61163. * @param buffer The binary file stored in an array buffer.
  61164. * @param size The expected size of the extracted cubemap.
  61165. * @return The Cube Map information.
  61166. */
  61167. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  61168. var uint8array = new Uint8Array(buffer);
  61169. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  61170. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  61171. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  61172. return cubeMapData;
  61173. };
  61174. /**
  61175. * Returns the pixels data extracted from an RGBE texture.
  61176. * This pixels will be stored left to right up to down in the R G B order in one array.
  61177. *
  61178. * More information on this format are available here:
  61179. * https://en.wikipedia.org/wiki/RGBE_image_format
  61180. *
  61181. * @param uint8array The binary file stored in an array buffer.
  61182. * @param hdrInfo The header information of the file.
  61183. * @return The pixels data in RGB right to left up to down order.
  61184. */
  61185. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  61186. // Keep for multi format supports.
  61187. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  61188. };
  61189. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  61190. var num_scanlines = hdrInfo.height;
  61191. var scanline_width = hdrInfo.width;
  61192. var a, b, c, d, count;
  61193. var dataIndex = hdrInfo.dataPosition;
  61194. var index = 0, endIndex = 0, i = 0;
  61195. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  61196. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  61197. // 3 channels of 4 bytes per pixel in float.
  61198. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  61199. var resultArray = new Float32Array(resultBuffer);
  61200. // read in each successive scanline
  61201. while (num_scanlines > 0) {
  61202. a = uint8array[dataIndex++];
  61203. b = uint8array[dataIndex++];
  61204. c = uint8array[dataIndex++];
  61205. d = uint8array[dataIndex++];
  61206. if (a != 2 || b != 2 || (c & 0x80)) {
  61207. // this file is not run length encoded
  61208. throw "HDR Bad header format, not RLE";
  61209. }
  61210. if (((c << 8) | d) != scanline_width) {
  61211. throw "HDR Bad header format, wrong scan line width";
  61212. }
  61213. index = 0;
  61214. // read each of the four channels for the scanline into the buffer
  61215. for (i = 0; i < 4; i++) {
  61216. endIndex = (i + 1) * scanline_width;
  61217. while (index < endIndex) {
  61218. a = uint8array[dataIndex++];
  61219. b = uint8array[dataIndex++];
  61220. if (a > 128) {
  61221. // a run of the same value
  61222. count = a - 128;
  61223. if ((count == 0) || (count > endIndex - index)) {
  61224. throw "HDR Bad Format, bad scanline data (run)";
  61225. }
  61226. while (count-- > 0) {
  61227. scanLineArray[index++] = b;
  61228. }
  61229. }
  61230. else {
  61231. // a non-run
  61232. count = a;
  61233. if ((count == 0) || (count > endIndex - index)) {
  61234. throw "HDR Bad Format, bad scanline data (non-run)";
  61235. }
  61236. scanLineArray[index++] = b;
  61237. if (--count > 0) {
  61238. for (var j = 0; j < count; j++) {
  61239. scanLineArray[index++] = uint8array[dataIndex++];
  61240. }
  61241. }
  61242. }
  61243. }
  61244. }
  61245. // now convert data from buffer into floats
  61246. for (i = 0; i < scanline_width; i++) {
  61247. a = scanLineArray[i];
  61248. b = scanLineArray[i + scanline_width];
  61249. c = scanLineArray[i + 2 * scanline_width];
  61250. d = scanLineArray[i + 3 * scanline_width];
  61251. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  61252. }
  61253. num_scanlines--;
  61254. }
  61255. return resultArray;
  61256. };
  61257. return HDRTools;
  61258. }());
  61259. Internals.HDRTools = HDRTools;
  61260. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  61261. })(BABYLON || (BABYLON = {}));
  61262. //# sourceMappingURL=babylon.hdr.js.map
  61263. var BABYLON;
  61264. (function (BABYLON) {
  61265. /**
  61266. * This represents a texture coming from an HDR input.
  61267. *
  61268. * The only supported format is currently panorama picture stored in RGBE format.
  61269. * Example of such files can be found on HDRLib: http://hdrlib.com/
  61270. */
  61271. var HDRCubeTexture = (function (_super) {
  61272. __extends(HDRCubeTexture, _super);
  61273. /**
  61274. * Instantiates an HDRTexture from the following parameters.
  61275. *
  61276. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  61277. * @param scene The scene the texture will be used in
  61278. * @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.
  61279. * @param noMipmap Forces to not generate the mipmap if true
  61280. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  61281. * @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)
  61282. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  61283. */
  61284. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  61285. if (noMipmap === void 0) { noMipmap = false; }
  61286. if (generateHarmonics === void 0) { generateHarmonics = true; }
  61287. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  61288. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  61289. if (onLoad === void 0) { onLoad = null; }
  61290. if (onError === void 0) { onError = null; }
  61291. var _this = _super.call(this, scene) || this;
  61292. _this._useInGammaSpace = false;
  61293. _this._generateHarmonics = true;
  61294. _this._isBABYLONPreprocessed = false;
  61295. _this._onLoad = null;
  61296. _this._onError = null;
  61297. /**
  61298. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  61299. */
  61300. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  61301. /**
  61302. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  61303. * This is usefull at run time to apply the good shader.
  61304. */
  61305. _this.isPMREM = false;
  61306. _this._isBlocking = true;
  61307. if (!url) {
  61308. return _this;
  61309. }
  61310. _this.name = url;
  61311. _this.url = url;
  61312. _this.hasAlpha = false;
  61313. _this.isCube = true;
  61314. _this._textureMatrix = BABYLON.Matrix.Identity();
  61315. _this._onLoad = onLoad;
  61316. _this._onError = onError;
  61317. _this.gammaSpace = false;
  61318. if (size) {
  61319. _this._isBABYLONPreprocessed = false;
  61320. _this._noMipmap = noMipmap;
  61321. _this._size = size;
  61322. _this._useInGammaSpace = useInGammaSpace;
  61323. _this._usePMREMGenerator = usePMREMGenerator &&
  61324. scene.getEngine().getCaps().textureLOD &&
  61325. _this.getScene().getEngine().getCaps().textureFloat &&
  61326. !_this._useInGammaSpace;
  61327. }
  61328. else {
  61329. _this._isBABYLONPreprocessed = true;
  61330. _this._noMipmap = false;
  61331. _this._useInGammaSpace = false;
  61332. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  61333. _this.getScene().getEngine().getCaps().textureFloat &&
  61334. !_this._useInGammaSpace;
  61335. }
  61336. _this.isPMREM = _this._usePMREMGenerator;
  61337. _this._texture = _this._getFromCache(url, _this._noMipmap);
  61338. if (!_this._texture) {
  61339. if (!scene.useDelayedTextureLoading) {
  61340. _this.loadTexture();
  61341. }
  61342. else {
  61343. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  61344. }
  61345. }
  61346. return _this;
  61347. }
  61348. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  61349. /**
  61350. * Gets wether or not the texture is blocking during loading.
  61351. */
  61352. get: function () {
  61353. return this._isBlocking;
  61354. },
  61355. /**
  61356. * Sets wether or not the texture is blocking during loading.
  61357. */
  61358. set: function (value) {
  61359. this._isBlocking = value;
  61360. },
  61361. enumerable: true,
  61362. configurable: true
  61363. });
  61364. /**
  61365. * Occurs when the file is a preprocessed .babylon.hdr file.
  61366. */
  61367. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  61368. var _this = this;
  61369. var mipLevels = 0;
  61370. var floatArrayView = null;
  61371. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  61372. var mips = new Array();
  61373. var startIndex = 30;
  61374. for (var level = 0; level < mipLevels; level++) {
  61375. mips.push([]);
  61376. // Fill each pixel of the mip level.
  61377. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  61378. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  61379. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  61380. mips[level].push(faceData);
  61381. startIndex += faceSize;
  61382. }
  61383. }
  61384. return mips;
  61385. } : null;
  61386. var callback = function (buffer) {
  61387. // Create Native Array Views
  61388. var intArrayView = new Int32Array(buffer);
  61389. floatArrayView = new Float32Array(buffer);
  61390. // Fill header.
  61391. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  61392. _this._size = intArrayView[1]; // CubeMap max mip face size.
  61393. // Update Texture Information.
  61394. _this._texture.updateSize(_this._size, _this._size);
  61395. // Fill polynomial information.
  61396. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  61397. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  61398. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  61399. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  61400. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  61401. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  61402. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  61403. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  61404. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  61405. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  61406. _this.sphericalPolynomial = sphericalPolynomial;
  61407. // Fill pixel data.
  61408. mipLevels = intArrayView[29]; // Number of mip levels.
  61409. var startIndex = 30;
  61410. var data = [];
  61411. var faceSize = Math.pow(_this._size, 2) * 3;
  61412. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  61413. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  61414. startIndex += faceSize;
  61415. }
  61416. var results = [];
  61417. var byteArray = null;
  61418. // Push each faces.
  61419. for (var k = 0; k < 6; k++) {
  61420. var dataFace = null;
  61421. // To be deprecated.
  61422. if (version === 1) {
  61423. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  61424. dataFace = data[j];
  61425. }
  61426. // If special cases.
  61427. if (!mipmapGenerator) {
  61428. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  61429. // 3 channels of 1 bytes per pixel in bytes.
  61430. var byteBuffer = new ArrayBuffer(faceSize);
  61431. byteArray = new Uint8Array(byteBuffer);
  61432. }
  61433. for (var i = 0; i < _this._size * _this._size; i++) {
  61434. // Put in gamma space if requested.
  61435. if (_this._useInGammaSpace) {
  61436. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  61437. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  61438. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  61439. }
  61440. // Convert to int texture for fallback.
  61441. if (byteArray) {
  61442. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  61443. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  61444. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  61445. // May use luminance instead if the result is not accurate.
  61446. var max = Math.max(Math.max(r, g), b);
  61447. if (max > 255) {
  61448. var scale = 255 / max;
  61449. r *= scale;
  61450. g *= scale;
  61451. b *= scale;
  61452. }
  61453. byteArray[(i * 3) + 0] = r;
  61454. byteArray[(i * 3) + 1] = g;
  61455. byteArray[(i * 3) + 2] = b;
  61456. }
  61457. }
  61458. }
  61459. // Fill the array accordingly.
  61460. if (byteArray) {
  61461. results.push(byteArray);
  61462. }
  61463. else {
  61464. results.push(dataFace);
  61465. }
  61466. }
  61467. return results;
  61468. };
  61469. this._texture = this.getScene().getEngine().createRawCubeTextureFromUrl(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  61470. };
  61471. /**
  61472. * Occurs when the file is raw .hdr file.
  61473. */
  61474. HDRCubeTexture.prototype.loadHDRTexture = function () {
  61475. var _this = this;
  61476. var callback = function (buffer) {
  61477. // Extract the raw linear data.
  61478. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  61479. // Generate harmonics if needed.
  61480. if (_this._generateHarmonics) {
  61481. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  61482. _this.sphericalPolynomial = sphericalPolynomial;
  61483. }
  61484. var results = [];
  61485. var byteArray = null;
  61486. // Push each faces.
  61487. for (var j = 0; j < 6; j++) {
  61488. // Create uintarray fallback.
  61489. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  61490. // 3 channels of 1 bytes per pixel in bytes.
  61491. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  61492. byteArray = new Uint8Array(byteBuffer);
  61493. }
  61494. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  61495. // If special cases.
  61496. if (_this._useInGammaSpace || byteArray) {
  61497. for (var i = 0; i < _this._size * _this._size; i++) {
  61498. // Put in gamma space if requested.
  61499. if (_this._useInGammaSpace) {
  61500. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  61501. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  61502. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  61503. }
  61504. // Convert to int texture for fallback.
  61505. if (byteArray) {
  61506. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  61507. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  61508. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  61509. // May use luminance instead if the result is not accurate.
  61510. var max = Math.max(Math.max(r, g), b);
  61511. if (max > 255) {
  61512. var scale = 255 / max;
  61513. r *= scale;
  61514. g *= scale;
  61515. b *= scale;
  61516. }
  61517. byteArray[(i * 3) + 0] = r;
  61518. byteArray[(i * 3) + 1] = g;
  61519. byteArray[(i * 3) + 2] = b;
  61520. }
  61521. }
  61522. }
  61523. if (byteArray) {
  61524. results.push(byteArray);
  61525. }
  61526. else {
  61527. results.push(dataFace);
  61528. }
  61529. }
  61530. return results;
  61531. };
  61532. var mipmapGenerator = null;
  61533. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  61534. // if (!this._noMipmap &&
  61535. // this._usePMREMGenerator) {
  61536. // mipmapGenerator = (data: ArrayBufferView[]) => {
  61537. // // Custom setup of the generator matching with the PBR shader values.
  61538. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  61539. // this._size,
  61540. // this._size,
  61541. // 0,
  61542. // 3,
  61543. // this.getScene().getEngine().getCaps().textureFloat,
  61544. // 2048,
  61545. // 0.25,
  61546. // false,
  61547. // true);
  61548. // return generator.filterCubeMap();
  61549. // };
  61550. // }
  61551. this._texture = this.getScene().getEngine().createRawCubeTextureFromUrl(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  61552. };
  61553. /**
  61554. * Starts the loading process of the texture.
  61555. */
  61556. HDRCubeTexture.prototype.loadTexture = function () {
  61557. if (this._isBABYLONPreprocessed) {
  61558. this.loadBabylonTexture();
  61559. }
  61560. else {
  61561. this.loadHDRTexture();
  61562. }
  61563. };
  61564. HDRCubeTexture.prototype.clone = function () {
  61565. var size = this._isBABYLONPreprocessed ? null : this._size;
  61566. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  61567. // Base texture
  61568. newTexture.level = this.level;
  61569. newTexture.wrapU = this.wrapU;
  61570. newTexture.wrapV = this.wrapV;
  61571. newTexture.coordinatesIndex = this.coordinatesIndex;
  61572. newTexture.coordinatesMode = this.coordinatesMode;
  61573. return newTexture;
  61574. };
  61575. // Methods
  61576. HDRCubeTexture.prototype.delayLoad = function () {
  61577. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  61578. return;
  61579. }
  61580. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  61581. this._texture = this._getFromCache(this.url, this._noMipmap);
  61582. if (!this._texture) {
  61583. this.loadTexture();
  61584. }
  61585. };
  61586. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  61587. return this._textureMatrix;
  61588. };
  61589. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  61590. this._textureMatrix = value;
  61591. };
  61592. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  61593. var texture = null;
  61594. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  61595. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  61596. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  61597. texture.name = parsedTexture.name;
  61598. texture.hasAlpha = parsedTexture.hasAlpha;
  61599. texture.level = parsedTexture.level;
  61600. texture.coordinatesMode = parsedTexture.coordinatesMode;
  61601. texture.isBlocking = parsedTexture.isBlocking;
  61602. }
  61603. return texture;
  61604. };
  61605. HDRCubeTexture.prototype.serialize = function () {
  61606. if (!this.name) {
  61607. return null;
  61608. }
  61609. var serializationObject = {};
  61610. serializationObject.name = this.name;
  61611. serializationObject.hasAlpha = this.hasAlpha;
  61612. serializationObject.isCube = true;
  61613. serializationObject.level = this.level;
  61614. serializationObject.size = this._size;
  61615. serializationObject.coordinatesMode = this.coordinatesMode;
  61616. serializationObject.useInGammaSpace = this._useInGammaSpace;
  61617. serializationObject.generateHarmonics = this._generateHarmonics;
  61618. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  61619. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  61620. serializationObject.customType = "BABYLON.HDRCubeTexture";
  61621. serializationObject.noMipmap = this._noMipmap;
  61622. serializationObject.isBlocking = this._isBlocking;
  61623. return serializationObject;
  61624. };
  61625. /**
  61626. * Saves as a file the data contained in the texture in a binary format.
  61627. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  61628. * as the spherical used in the lighting.
  61629. * @param url The HDR file url.
  61630. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  61631. * @param onError Method called if any error happens during download.
  61632. * @return The packed binary data.
  61633. */
  61634. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  61635. if (onError === void 0) { onError = null; }
  61636. var callback = function (buffer) {
  61637. var data = new Blob([buffer], { type: 'application/octet-stream' });
  61638. // Returns a URL you can use as a href.
  61639. var objUrl = window.URL.createObjectURL(data);
  61640. // Simulates a link to it and click to dowload.
  61641. var a = document.createElement("a");
  61642. document.body.appendChild(a);
  61643. a.style.display = "none";
  61644. a.href = objUrl;
  61645. a.download = "envmap.babylon.hdr";
  61646. a.click();
  61647. };
  61648. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  61649. };
  61650. /**
  61651. * Serializes the data contained in the texture in a binary format.
  61652. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  61653. * as the spherical used in the lighting.
  61654. * @param url The HDR file url.
  61655. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  61656. * @param onError Method called if any error happens during download.
  61657. * @return The packed binary data.
  61658. */
  61659. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  61660. if (onError === void 0) { onError = null; }
  61661. // Needs the url tho create the texture.
  61662. if (!url) {
  61663. return null;
  61664. }
  61665. // Check Power of two size.
  61666. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  61667. return null;
  61668. }
  61669. // Coming Back in 3.1.
  61670. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  61671. return null;
  61672. };
  61673. HDRCubeTexture._facesMapping = [
  61674. "right",
  61675. "left",
  61676. "up",
  61677. "down",
  61678. "front",
  61679. "back"
  61680. ];
  61681. return HDRCubeTexture;
  61682. }(BABYLON.BaseTexture));
  61683. BABYLON.HDRCubeTexture = HDRCubeTexture;
  61684. })(BABYLON || (BABYLON = {}));
  61685. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  61686. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  61687. // Huge respect for a such great lib.
  61688. // Earcut license:
  61689. // Copyright (c) 2016, Mapbox
  61690. //
  61691. // Permission to use, copy, modify, and/or distribute this software for any purpose
  61692. // with or without fee is hereby granted, provided that the above copyright notice
  61693. // and this permission notice appear in all copies.
  61694. //
  61695. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  61696. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  61697. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  61698. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  61699. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  61700. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  61701. // THIS SOFTWARE.
  61702. var Earcut;
  61703. (function (Earcut) {
  61704. /**
  61705. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  61706. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  61707. * @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).
  61708. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  61709. */
  61710. function earcut(data, holeIndices, dim) {
  61711. dim = dim || 2;
  61712. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  61713. if (!outerNode)
  61714. return triangles;
  61715. var minX, minY, maxX, maxY, x, y, size;
  61716. if (hasHoles)
  61717. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  61718. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  61719. if (data.length > 80 * dim) {
  61720. minX = maxX = data[0];
  61721. minY = maxY = data[1];
  61722. for (var i = dim; i < outerLen; i += dim) {
  61723. x = data[i];
  61724. y = data[i + 1];
  61725. if (x < minX)
  61726. minX = x;
  61727. if (y < minY)
  61728. minY = y;
  61729. if (x > maxX)
  61730. maxX = x;
  61731. if (y > maxY)
  61732. maxY = y;
  61733. }
  61734. // minX, minY and size are later used to transform coords into integers for z-order calculation
  61735. size = Math.max(maxX - minX, maxY - minY);
  61736. }
  61737. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  61738. return triangles;
  61739. }
  61740. Earcut.earcut = earcut;
  61741. var Node = (function () {
  61742. function Node(i, x, y) {
  61743. this.i = i;
  61744. this.x = x;
  61745. this.y = y;
  61746. this.prev = null;
  61747. this.next = null;
  61748. this.z = null;
  61749. this.prevZ = null;
  61750. this.nextZ = null;
  61751. this.steiner = false;
  61752. }
  61753. return Node;
  61754. }());
  61755. // create a circular doubly linked list from polygon points in the specified winding order
  61756. function linkedList(data, start, end, dim, clockwise) {
  61757. var i, last;
  61758. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  61759. for (i = start; i < end; i += dim)
  61760. last = insertNode(i, data[i], data[i + 1], last);
  61761. }
  61762. else {
  61763. for (i = end - dim; i >= start; i -= dim)
  61764. last = insertNode(i, data[i], data[i + 1], last);
  61765. }
  61766. if (last && equals(last, last.next)) {
  61767. removeNode(last);
  61768. last = last.next;
  61769. }
  61770. return last;
  61771. }
  61772. // eliminate colinear or duplicate points
  61773. function filterPoints(start, end) {
  61774. if (!start)
  61775. return start;
  61776. if (!end)
  61777. end = start;
  61778. var p = start, again;
  61779. do {
  61780. again = false;
  61781. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  61782. removeNode(p);
  61783. p = end = p.prev;
  61784. if (p === p.next)
  61785. return null;
  61786. again = true;
  61787. }
  61788. else {
  61789. p = p.next;
  61790. }
  61791. } while (again || p !== end);
  61792. return end;
  61793. }
  61794. // main ear slicing loop which triangulates a polygon (given as a linked list)
  61795. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  61796. if (!ear)
  61797. return;
  61798. // interlink polygon nodes in z-order
  61799. if (!pass && size)
  61800. indexCurve(ear, minX, minY, size);
  61801. var stop = ear, prev, next;
  61802. // iterate through ears, slicing them one by one
  61803. while (ear.prev !== ear.next) {
  61804. prev = ear.prev;
  61805. next = ear.next;
  61806. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  61807. // cut off the triangle
  61808. triangles.push(prev.i / dim);
  61809. triangles.push(ear.i / dim);
  61810. triangles.push(next.i / dim);
  61811. removeNode(ear);
  61812. // skipping the next vertice leads to less sliver triangles
  61813. ear = next.next;
  61814. stop = next.next;
  61815. continue;
  61816. }
  61817. ear = next;
  61818. // if we looped through the whole remaining polygon and can't find any more ears
  61819. if (ear === stop) {
  61820. // try filtering points and slicing again
  61821. if (!pass) {
  61822. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  61823. // if this didn't work, try curing all small self-intersections locally
  61824. }
  61825. else if (pass === 1) {
  61826. ear = cureLocalIntersections(ear, triangles, dim);
  61827. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  61828. // as a last resort, try splitting the remaining polygon into two
  61829. }
  61830. else if (pass === 2) {
  61831. splitEarcut(ear, triangles, dim, minX, minY, size);
  61832. }
  61833. break;
  61834. }
  61835. }
  61836. }
  61837. // check whether a polygon node forms a valid ear with adjacent nodes
  61838. function isEar(ear) {
  61839. var a = ear.prev, b = ear, c = ear.next;
  61840. if (area(a, b, c) >= 0)
  61841. return false; // reflex, can't be an ear
  61842. // now make sure we don't have other points inside the potential ear
  61843. var p = ear.next.next;
  61844. while (p !== ear.prev) {
  61845. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  61846. area(p.prev, p, p.next) >= 0)
  61847. return false;
  61848. p = p.next;
  61849. }
  61850. return true;
  61851. }
  61852. function isEarHashed(ear, minX, minY, size) {
  61853. var a = ear.prev, b = ear, c = ear.next;
  61854. if (area(a, b, c) >= 0)
  61855. return false; // reflex, can't be an ear
  61856. // triangle bbox; min & max are calculated like this for speed
  61857. 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);
  61858. // z-order range for the current triangle bbox;
  61859. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  61860. // first look for points inside the triangle in increasing z-order
  61861. var p = ear.nextZ;
  61862. while (p && p.z <= maxZ) {
  61863. if (p !== ear.prev &&
  61864. p !== ear.next &&
  61865. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  61866. area(p.prev, p, p.next) >= 0)
  61867. return false;
  61868. p = p.nextZ;
  61869. }
  61870. // then look for points in decreasing z-order
  61871. p = ear.prevZ;
  61872. while (p && p.z >= minZ) {
  61873. if (p !== ear.prev &&
  61874. p !== ear.next &&
  61875. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  61876. area(p.prev, p, p.next) >= 0)
  61877. return false;
  61878. p = p.prevZ;
  61879. }
  61880. return true;
  61881. }
  61882. // go through all polygon nodes and cure small local self-intersections
  61883. function cureLocalIntersections(start, triangles, dim) {
  61884. var p = start;
  61885. do {
  61886. var a = p.prev, b = p.next.next;
  61887. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  61888. triangles.push(a.i / dim);
  61889. triangles.push(p.i / dim);
  61890. triangles.push(b.i / dim);
  61891. // remove two nodes involved
  61892. removeNode(p);
  61893. removeNode(p.next);
  61894. p = start = b;
  61895. }
  61896. p = p.next;
  61897. } while (p !== start);
  61898. return p;
  61899. }
  61900. // try splitting polygon into two and triangulate them independently
  61901. function splitEarcut(start, triangles, dim, minX, minY, size) {
  61902. // look for a valid diagonal that divides the polygon into two
  61903. var a = start;
  61904. do {
  61905. var b = a.next.next;
  61906. while (b !== a.prev) {
  61907. if (a.i !== b.i && isValidDiagonal(a, b)) {
  61908. // split the polygon in two by the diagonal
  61909. var c = splitPolygon(a, b);
  61910. // filter colinear points around the cuts
  61911. a = filterPoints(a, a.next);
  61912. c = filterPoints(c, c.next);
  61913. // run earcut on each half
  61914. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  61915. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  61916. return;
  61917. }
  61918. b = b.next;
  61919. }
  61920. a = a.next;
  61921. } while (a !== start);
  61922. }
  61923. // link every hole into the outer loop, producing a single-ring polygon without holes
  61924. function eliminateHoles(data, holeIndices, outerNode, dim) {
  61925. var queue = [], i, len, start, end, list;
  61926. for (i = 0, len = holeIndices.length; i < len; i++) {
  61927. start = holeIndices[i] * dim;
  61928. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  61929. list = linkedList(data, start, end, dim, false);
  61930. if (list === list.next)
  61931. list.steiner = true;
  61932. queue.push(getLeftmost(list));
  61933. }
  61934. queue.sort(compareX);
  61935. // process holes from left to right
  61936. for (i = 0; i < queue.length; i++) {
  61937. eliminateHole(queue[i], outerNode);
  61938. outerNode = filterPoints(outerNode, outerNode.next);
  61939. }
  61940. return outerNode;
  61941. }
  61942. function compareX(a, b) {
  61943. return a.x - b.x;
  61944. }
  61945. // find a bridge between vertices that connects hole with an outer ring and and link it
  61946. function eliminateHole(hole, outerNode) {
  61947. outerNode = findHoleBridge(hole, outerNode);
  61948. if (outerNode) {
  61949. var b = splitPolygon(outerNode, hole);
  61950. filterPoints(b, b.next);
  61951. }
  61952. }
  61953. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  61954. function findHoleBridge(hole, outerNode) {
  61955. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  61956. // find a segment intersected by a ray from the hole's leftmost point to the left;
  61957. // segment's endpoint with lesser x will be potential connection point
  61958. do {
  61959. if (hy <= p.y && hy >= p.next.y) {
  61960. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  61961. if (x <= hx && x > qx) {
  61962. qx = x;
  61963. if (x === hx) {
  61964. if (hy === p.y)
  61965. return p;
  61966. if (hy === p.next.y)
  61967. return p.next;
  61968. }
  61969. m = p.x < p.next.x ? p : p.next;
  61970. }
  61971. }
  61972. p = p.next;
  61973. } while (p !== outerNode);
  61974. if (!m)
  61975. return null;
  61976. if (hx === qx)
  61977. return m.prev; // hole touches outer segment; pick lower endpoint
  61978. // look for points inside the triangle of hole point, segment intersection and endpoint;
  61979. // if there are no points found, we have a valid connection;
  61980. // otherwise choose the point of the minimum angle with the ray as connection point
  61981. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  61982. p = m.next;
  61983. while (p !== stop) {
  61984. if (hx >= p.x &&
  61985. p.x >= mx &&
  61986. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  61987. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  61988. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  61989. m = p;
  61990. tanMin = tan;
  61991. }
  61992. }
  61993. p = p.next;
  61994. }
  61995. return m;
  61996. }
  61997. // interlink polygon nodes in z-order
  61998. function indexCurve(start, minX, minY, size) {
  61999. var p = start;
  62000. do {
  62001. if (p.z === null)
  62002. p.z = zOrder(p.x, p.y, minX, minY, size);
  62003. p.prevZ = p.prev;
  62004. p.nextZ = p.next;
  62005. p = p.next;
  62006. } while (p !== start);
  62007. p.prevZ.nextZ = null;
  62008. p.prevZ = null;
  62009. sortLinked(p);
  62010. }
  62011. // Simon Tatham's linked list merge sort algorithm
  62012. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  62013. function sortLinked(list) {
  62014. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  62015. do {
  62016. p = list;
  62017. list = null;
  62018. tail = null;
  62019. numMerges = 0;
  62020. while (p) {
  62021. numMerges++;
  62022. q = p;
  62023. pSize = 0;
  62024. for (i = 0; i < inSize; i++) {
  62025. pSize++;
  62026. q = q.nextZ;
  62027. if (!q)
  62028. break;
  62029. }
  62030. qSize = inSize;
  62031. while (pSize > 0 || (qSize > 0 && q)) {
  62032. if (pSize === 0) {
  62033. e = q;
  62034. q = q.nextZ;
  62035. qSize--;
  62036. }
  62037. else if (qSize === 0 || !q) {
  62038. e = p;
  62039. p = p.nextZ;
  62040. pSize--;
  62041. }
  62042. else if (p.z <= q.z) {
  62043. e = p;
  62044. p = p.nextZ;
  62045. pSize--;
  62046. }
  62047. else {
  62048. e = q;
  62049. q = q.nextZ;
  62050. qSize--;
  62051. }
  62052. if (tail)
  62053. tail.nextZ = e;
  62054. else
  62055. list = e;
  62056. e.prevZ = tail;
  62057. tail = e;
  62058. }
  62059. p = q;
  62060. }
  62061. tail.nextZ = null;
  62062. inSize *= 2;
  62063. } while (numMerges > 1);
  62064. return list;
  62065. }
  62066. // z-order of a point given coords and size of the data bounding box
  62067. function zOrder(x, y, minX, minY, size) {
  62068. // coords are transformed into non-negative 15-bit integer range
  62069. x = 32767 * (x - minX) / size;
  62070. y = 32767 * (y - minY) / size;
  62071. x = (x | (x << 8)) & 0x00FF00FF;
  62072. x = (x | (x << 4)) & 0x0F0F0F0F;
  62073. x = (x | (x << 2)) & 0x33333333;
  62074. x = (x | (x << 1)) & 0x55555555;
  62075. y = (y | (y << 8)) & 0x00FF00FF;
  62076. y = (y | (y << 4)) & 0x0F0F0F0F;
  62077. y = (y | (y << 2)) & 0x33333333;
  62078. y = (y | (y << 1)) & 0x55555555;
  62079. return x | (y << 1);
  62080. }
  62081. // find the leftmost node of a polygon ring
  62082. function getLeftmost(start) {
  62083. var p = start, leftmost = start;
  62084. do {
  62085. if (p.x < leftmost.x)
  62086. leftmost = p;
  62087. p = p.next;
  62088. } while (p !== start);
  62089. return leftmost;
  62090. }
  62091. // check if a point lies within a convex triangle
  62092. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  62093. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  62094. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  62095. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  62096. }
  62097. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  62098. function isValidDiagonal(a, b) {
  62099. return a.next.i !== b.i &&
  62100. a.prev.i !== b.i &&
  62101. !intersectsPolygon(a, b) &&
  62102. locallyInside(a, b) &&
  62103. locallyInside(b, a) &&
  62104. middleInside(a, b);
  62105. }
  62106. // signed area of a triangle
  62107. function area(p, q, r) {
  62108. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  62109. }
  62110. // check if two points are equal
  62111. function equals(p1, p2) {
  62112. return p1.x === p2.x && p1.y === p2.y;
  62113. }
  62114. // check if two segments intersect
  62115. function intersects(p1, q1, p2, q2) {
  62116. if ((equals(p1, q1) && equals(p2, q2)) ||
  62117. (equals(p1, q2) && equals(p2, q1)))
  62118. return true;
  62119. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  62120. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  62121. }
  62122. // check if a polygon diagonal intersects any polygon segments
  62123. function intersectsPolygon(a, b) {
  62124. var p = a;
  62125. do {
  62126. if (p.i !== a.i &&
  62127. p.next.i !== a.i &&
  62128. p.i !== b.i &&
  62129. p.next.i !== b.i &&
  62130. intersects(p, p.next, a, b))
  62131. return true;
  62132. p = p.next;
  62133. } while (p !== a);
  62134. return false;
  62135. }
  62136. // check if a polygon diagonal is locally inside the polygon
  62137. function locallyInside(a, b) {
  62138. return area(a.prev, a, a.next) < 0
  62139. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  62140. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  62141. }
  62142. // check if the middle point of a polygon diagonal is inside the polygon
  62143. function middleInside(a, b) {
  62144. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  62145. do {
  62146. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  62147. inside = !inside;
  62148. p = p.next;
  62149. } while (p !== a);
  62150. return inside;
  62151. }
  62152. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  62153. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  62154. function splitPolygon(a, b) {
  62155. 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;
  62156. a.next = b;
  62157. b.prev = a;
  62158. a2.next = an;
  62159. an.prev = a2;
  62160. b2.next = a2;
  62161. a2.prev = b2;
  62162. bp.next = b2;
  62163. b2.prev = bp;
  62164. return b2;
  62165. }
  62166. // create a node and optionally link it with previous one (in a circular doubly linked list)
  62167. function insertNode(i, x, y, last) {
  62168. var p = new Node(i, x, y);
  62169. if (!last) {
  62170. p.prev = p;
  62171. p.next = p;
  62172. }
  62173. else {
  62174. p.next = last.next;
  62175. p.prev = last;
  62176. last.next.prev = p;
  62177. last.next = p;
  62178. }
  62179. return p;
  62180. }
  62181. function removeNode(p) {
  62182. p.next.prev = p.prev;
  62183. p.prev.next = p.next;
  62184. if (p.prevZ)
  62185. p.prevZ.nextZ = p.nextZ;
  62186. if (p.nextZ)
  62187. p.nextZ.prevZ = p.prevZ;
  62188. }
  62189. /**
  62190. * return a percentage difference between the polygon area and its triangulation area;
  62191. * used to verify correctness of triangulation
  62192. */
  62193. function deviation(data, holeIndices, dim, triangles) {
  62194. var hasHoles = holeIndices && holeIndices.length;
  62195. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  62196. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  62197. if (hasHoles) {
  62198. for (var i = 0, len = holeIndices.length; i < len; i++) {
  62199. var start = holeIndices[i] * dim;
  62200. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  62201. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  62202. }
  62203. }
  62204. var trianglesArea = 0;
  62205. for (i = 0; i < triangles.length; i += 3) {
  62206. var a = triangles[i] * dim;
  62207. var b = triangles[i + 1] * dim;
  62208. var c = triangles[i + 2] * dim;
  62209. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  62210. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  62211. }
  62212. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  62213. }
  62214. Earcut.deviation = deviation;
  62215. ;
  62216. function signedArea(data, start, end, dim) {
  62217. var sum = 0;
  62218. for (var i = start, j = end - dim; i < end; i += dim) {
  62219. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  62220. j = i;
  62221. }
  62222. return sum;
  62223. }
  62224. /**
  62225. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  62226. */
  62227. function flatten(data) {
  62228. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  62229. for (var i = 0; i < data.length; i++) {
  62230. for (var j = 0; j < data[i].length; j++) {
  62231. for (var d = 0; d < dim; d++)
  62232. result.vertices.push(data[i][j][d]);
  62233. }
  62234. if (i > 0) {
  62235. holeIndex += data[i - 1].length;
  62236. result.holes.push(holeIndex);
  62237. }
  62238. }
  62239. return result;
  62240. }
  62241. Earcut.flatten = flatten;
  62242. ;
  62243. })(Earcut || (Earcut = {}));
  62244. //# sourceMappingURL=babylon.earcut.js.map
  62245. /// <reference path="..\Math\babylon.math.ts" />
  62246. var BABYLON;
  62247. (function (BABYLON) {
  62248. var IndexedVector2 = (function (_super) {
  62249. __extends(IndexedVector2, _super);
  62250. function IndexedVector2(original, index) {
  62251. var _this = _super.call(this, original.x, original.y) || this;
  62252. _this.index = index;
  62253. return _this;
  62254. }
  62255. return IndexedVector2;
  62256. }(BABYLON.Vector2));
  62257. var PolygonPoints = (function () {
  62258. function PolygonPoints() {
  62259. this.elements = new Array();
  62260. }
  62261. PolygonPoints.prototype.add = function (originalPoints) {
  62262. var _this = this;
  62263. var result = new Array();
  62264. originalPoints.forEach(function (point) {
  62265. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  62266. var newPoint = new IndexedVector2(point, _this.elements.length);
  62267. result.push(newPoint);
  62268. _this.elements.push(newPoint);
  62269. }
  62270. });
  62271. return result;
  62272. };
  62273. PolygonPoints.prototype.computeBounds = function () {
  62274. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  62275. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  62276. this.elements.forEach(function (point) {
  62277. // x
  62278. if (point.x < lmin.x) {
  62279. lmin.x = point.x;
  62280. }
  62281. else if (point.x > lmax.x) {
  62282. lmax.x = point.x;
  62283. }
  62284. // y
  62285. if (point.y < lmin.y) {
  62286. lmin.y = point.y;
  62287. }
  62288. else if (point.y > lmax.y) {
  62289. lmax.y = point.y;
  62290. }
  62291. });
  62292. return {
  62293. min: lmin,
  62294. max: lmax,
  62295. width: lmax.x - lmin.x,
  62296. height: lmax.y - lmin.y
  62297. };
  62298. };
  62299. return PolygonPoints;
  62300. }());
  62301. var Polygon = (function () {
  62302. function Polygon() {
  62303. }
  62304. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  62305. return [
  62306. new BABYLON.Vector2(xmin, ymin),
  62307. new BABYLON.Vector2(xmax, ymin),
  62308. new BABYLON.Vector2(xmax, ymax),
  62309. new BABYLON.Vector2(xmin, ymax)
  62310. ];
  62311. };
  62312. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  62313. if (cx === void 0) { cx = 0; }
  62314. if (cy === void 0) { cy = 0; }
  62315. if (numberOfSides === void 0) { numberOfSides = 32; }
  62316. var result = new Array();
  62317. var angle = 0;
  62318. var increment = (Math.PI * 2) / numberOfSides;
  62319. for (var i = 0; i < numberOfSides; i++) {
  62320. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  62321. angle -= increment;
  62322. }
  62323. return result;
  62324. };
  62325. Polygon.Parse = function (input) {
  62326. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  62327. var i, result = [];
  62328. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  62329. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  62330. }
  62331. return result;
  62332. };
  62333. Polygon.StartingAt = function (x, y) {
  62334. return BABYLON.Path2.StartingAt(x, y);
  62335. };
  62336. return Polygon;
  62337. }());
  62338. BABYLON.Polygon = Polygon;
  62339. var PolygonMeshBuilder = (function () {
  62340. function PolygonMeshBuilder(name, contours, scene) {
  62341. this._points = new PolygonPoints();
  62342. this._outlinepoints = new PolygonPoints();
  62343. this._holes = new Array();
  62344. this._epoints = new Array();
  62345. this._eholes = new Array();
  62346. this._name = name;
  62347. this._scene = scene;
  62348. var points;
  62349. if (contours instanceof BABYLON.Path2) {
  62350. points = contours.getPoints();
  62351. }
  62352. else {
  62353. points = contours;
  62354. }
  62355. this._addToepoint(points);
  62356. this._points.add(points);
  62357. this._outlinepoints.add(points);
  62358. }
  62359. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  62360. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  62361. var p = points_1[_i];
  62362. this._epoints.push(p.x, p.y);
  62363. }
  62364. };
  62365. PolygonMeshBuilder.prototype.addHole = function (hole) {
  62366. this._points.add(hole);
  62367. var holepoints = new PolygonPoints();
  62368. holepoints.add(hole);
  62369. this._holes.push(holepoints);
  62370. this._eholes.push(this._epoints.length / 2);
  62371. this._addToepoint(hole);
  62372. return this;
  62373. };
  62374. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  62375. var _this = this;
  62376. if (updatable === void 0) { updatable = false; }
  62377. var result = new BABYLON.Mesh(this._name, this._scene);
  62378. var normals = new Array();
  62379. var positions = new Array();
  62380. var uvs = new Array();
  62381. var bounds = this._points.computeBounds();
  62382. this._points.elements.forEach(function (p) {
  62383. normals.push(0, 1.0, 0);
  62384. positions.push(p.x, 0, p.y);
  62385. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  62386. });
  62387. var indices = new Array();
  62388. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  62389. for (var i = 0; i < res.length; i++) {
  62390. indices.push(res[i]);
  62391. }
  62392. if (depth > 0) {
  62393. var positionscount = (positions.length / 3); //get the current pointcount
  62394. this._points.elements.forEach(function (p) {
  62395. normals.push(0, -1.0, 0);
  62396. positions.push(p.x, -depth, p.y);
  62397. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  62398. });
  62399. var totalCount = indices.length;
  62400. for (var i = 0; i < totalCount; i += 3) {
  62401. var i0 = indices[i + 0];
  62402. var i1 = indices[i + 1];
  62403. var i2 = indices[i + 2];
  62404. indices.push(i2 + positionscount);
  62405. indices.push(i1 + positionscount);
  62406. indices.push(i0 + positionscount);
  62407. }
  62408. //Add the sides
  62409. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  62410. this._holes.forEach(function (hole) {
  62411. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  62412. });
  62413. }
  62414. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  62415. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  62416. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  62417. result.setIndices(indices);
  62418. return result;
  62419. };
  62420. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  62421. var StartIndex = positions.length / 3;
  62422. var ulength = 0;
  62423. for (var i = 0; i < points.elements.length; i++) {
  62424. var p = points.elements[i];
  62425. var p1;
  62426. if ((i + 1) > points.elements.length - 1) {
  62427. p1 = points.elements[0];
  62428. }
  62429. else {
  62430. p1 = points.elements[i + 1];
  62431. }
  62432. positions.push(p.x, 0, p.y);
  62433. positions.push(p.x, -depth, p.y);
  62434. positions.push(p1.x, 0, p1.y);
  62435. positions.push(p1.x, -depth, p1.y);
  62436. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  62437. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  62438. var v3 = v2.subtract(v1);
  62439. var v4 = new BABYLON.Vector3(0, 1, 0);
  62440. var vn = BABYLON.Vector3.Cross(v3, v4);
  62441. vn = vn.normalize();
  62442. uvs.push(ulength / bounds.width, 0);
  62443. uvs.push(ulength / bounds.width, 1);
  62444. ulength += v3.length();
  62445. uvs.push((ulength / bounds.width), 0);
  62446. uvs.push((ulength / bounds.width), 1);
  62447. if (!flip) {
  62448. normals.push(-vn.x, -vn.y, -vn.z);
  62449. normals.push(-vn.x, -vn.y, -vn.z);
  62450. normals.push(-vn.x, -vn.y, -vn.z);
  62451. normals.push(-vn.x, -vn.y, -vn.z);
  62452. indices.push(StartIndex);
  62453. indices.push(StartIndex + 1);
  62454. indices.push(StartIndex + 2);
  62455. indices.push(StartIndex + 1);
  62456. indices.push(StartIndex + 3);
  62457. indices.push(StartIndex + 2);
  62458. }
  62459. else {
  62460. normals.push(vn.x, vn.y, vn.z);
  62461. normals.push(vn.x, vn.y, vn.z);
  62462. normals.push(vn.x, vn.y, vn.z);
  62463. normals.push(vn.x, vn.y, vn.z);
  62464. indices.push(StartIndex);
  62465. indices.push(StartIndex + 2);
  62466. indices.push(StartIndex + 1);
  62467. indices.push(StartIndex + 1);
  62468. indices.push(StartIndex + 2);
  62469. indices.push(StartIndex + 3);
  62470. }
  62471. StartIndex += 4;
  62472. }
  62473. ;
  62474. };
  62475. return PolygonMeshBuilder;
  62476. }());
  62477. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  62478. })(BABYLON || (BABYLON = {}));
  62479. //# sourceMappingURL=babylon.polygonMesh.js.map
  62480. var BABYLON;
  62481. (function (BABYLON) {
  62482. // Unique ID when we import meshes from Babylon to CSG
  62483. var currentCSGMeshId = 0;
  62484. // # class Vertex
  62485. // Represents a vertex of a polygon. Use your own vertex class instead of this
  62486. // one to provide additional features like texture coordinates and vertex
  62487. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  62488. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  62489. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  62490. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  62491. // is not used anywhere else.
  62492. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  62493. var Vertex = (function () {
  62494. function Vertex(pos, normal, uv) {
  62495. this.pos = pos;
  62496. this.normal = normal;
  62497. this.uv = uv;
  62498. }
  62499. Vertex.prototype.clone = function () {
  62500. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  62501. };
  62502. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  62503. // orientation of a polygon is flipped.
  62504. Vertex.prototype.flip = function () {
  62505. this.normal = this.normal.scale(-1);
  62506. };
  62507. // Create a new vertex between this vertex and `other` by linearly
  62508. // interpolating all properties using a parameter of `t`. Subclasses should
  62509. // override this to interpolate additional properties.
  62510. Vertex.prototype.interpolate = function (other, t) {
  62511. 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));
  62512. };
  62513. return Vertex;
  62514. }());
  62515. // # class Plane
  62516. // Represents a plane in 3D space.
  62517. var Plane = (function () {
  62518. function Plane(normal, w) {
  62519. this.normal = normal;
  62520. this.w = w;
  62521. }
  62522. Plane.FromPoints = function (a, b, c) {
  62523. var v0 = c.subtract(a);
  62524. var v1 = b.subtract(a);
  62525. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  62526. return null;
  62527. }
  62528. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  62529. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  62530. };
  62531. Plane.prototype.clone = function () {
  62532. return new Plane(this.normal.clone(), this.w);
  62533. };
  62534. Plane.prototype.flip = function () {
  62535. this.normal.scaleInPlace(-1);
  62536. this.w = -this.w;
  62537. };
  62538. // Split `polygon` by this plane if needed, then put the polygon or polygon
  62539. // fragments in the appropriate lists. Coplanar polygons go into either
  62540. // `coplanarFront` or `coplanarBack` depending on their orientation with
  62541. // respect to this plane. Polygons in front or in back of this plane go into
  62542. // either `front` or `back`.
  62543. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  62544. var COPLANAR = 0;
  62545. var FRONT = 1;
  62546. var BACK = 2;
  62547. var SPANNING = 3;
  62548. // Classify each point as well as the entire polygon into one of the above
  62549. // four classes.
  62550. var polygonType = 0;
  62551. var types = [];
  62552. var i;
  62553. var t;
  62554. for (i = 0; i < polygon.vertices.length; i++) {
  62555. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  62556. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  62557. polygonType |= type;
  62558. types.push(type);
  62559. }
  62560. // Put the polygon in the correct list, splitting it when necessary.
  62561. switch (polygonType) {
  62562. case COPLANAR:
  62563. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  62564. break;
  62565. case FRONT:
  62566. front.push(polygon);
  62567. break;
  62568. case BACK:
  62569. back.push(polygon);
  62570. break;
  62571. case SPANNING:
  62572. var f = [], b = [];
  62573. for (i = 0; i < polygon.vertices.length; i++) {
  62574. var j = (i + 1) % polygon.vertices.length;
  62575. var ti = types[i], tj = types[j];
  62576. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  62577. if (ti !== BACK)
  62578. f.push(vi);
  62579. if (ti !== FRONT)
  62580. b.push(ti !== BACK ? vi.clone() : vi);
  62581. if ((ti | tj) === SPANNING) {
  62582. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  62583. var v = vi.interpolate(vj, t);
  62584. f.push(v);
  62585. b.push(v.clone());
  62586. }
  62587. }
  62588. var poly;
  62589. if (f.length >= 3) {
  62590. poly = new Polygon(f, polygon.shared);
  62591. if (poly.plane)
  62592. front.push(poly);
  62593. }
  62594. if (b.length >= 3) {
  62595. poly = new Polygon(b, polygon.shared);
  62596. if (poly.plane)
  62597. back.push(poly);
  62598. }
  62599. break;
  62600. }
  62601. };
  62602. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  62603. // point is on the plane.
  62604. Plane.EPSILON = 1e-5;
  62605. return Plane;
  62606. }());
  62607. // # class Polygon
  62608. // Represents a convex polygon. The vertices used to initialize a polygon must
  62609. // be coplanar and form a convex loop.
  62610. //
  62611. // Each convex polygon has a `shared` property, which is shared between all
  62612. // polygons that are clones of each other or were split from the same polygon.
  62613. // This can be used to define per-polygon properties (such as surface color).
  62614. var Polygon = (function () {
  62615. function Polygon(vertices, shared) {
  62616. this.vertices = vertices;
  62617. this.shared = shared;
  62618. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  62619. }
  62620. Polygon.prototype.clone = function () {
  62621. var vertices = this.vertices.map(function (v) { return v.clone(); });
  62622. return new Polygon(vertices, this.shared);
  62623. };
  62624. Polygon.prototype.flip = function () {
  62625. this.vertices.reverse().map(function (v) { v.flip(); });
  62626. this.plane.flip();
  62627. };
  62628. return Polygon;
  62629. }());
  62630. // # class Node
  62631. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  62632. // by picking a polygon to split along. That polygon (and all other coplanar
  62633. // polygons) are added directly to that node and the other polygons are added to
  62634. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  62635. // no distinction between internal and leaf nodes.
  62636. var Node = (function () {
  62637. function Node(polygons) {
  62638. this.plane = null;
  62639. this.front = null;
  62640. this.back = null;
  62641. this.polygons = new Array();
  62642. if (polygons) {
  62643. this.build(polygons);
  62644. }
  62645. }
  62646. Node.prototype.clone = function () {
  62647. var node = new Node();
  62648. node.plane = this.plane && this.plane.clone();
  62649. node.front = this.front && this.front.clone();
  62650. node.back = this.back && this.back.clone();
  62651. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  62652. return node;
  62653. };
  62654. // Convert solid space to empty space and empty space to solid space.
  62655. Node.prototype.invert = function () {
  62656. for (var i = 0; i < this.polygons.length; i++) {
  62657. this.polygons[i].flip();
  62658. }
  62659. if (this.plane) {
  62660. this.plane.flip();
  62661. }
  62662. if (this.front) {
  62663. this.front.invert();
  62664. }
  62665. if (this.back) {
  62666. this.back.invert();
  62667. }
  62668. var temp = this.front;
  62669. this.front = this.back;
  62670. this.back = temp;
  62671. };
  62672. // Recursively remove all polygons in `polygons` that are inside this BSP
  62673. // tree.
  62674. Node.prototype.clipPolygons = function (polygons) {
  62675. if (!this.plane)
  62676. return polygons.slice();
  62677. var front = new Array(), back = new Array();
  62678. for (var i = 0; i < polygons.length; i++) {
  62679. this.plane.splitPolygon(polygons[i], front, back, front, back);
  62680. }
  62681. if (this.front) {
  62682. front = this.front.clipPolygons(front);
  62683. }
  62684. if (this.back) {
  62685. back = this.back.clipPolygons(back);
  62686. }
  62687. else {
  62688. back = [];
  62689. }
  62690. return front.concat(back);
  62691. };
  62692. // Remove all polygons in this BSP tree that are inside the other BSP tree
  62693. // `bsp`.
  62694. Node.prototype.clipTo = function (bsp) {
  62695. this.polygons = bsp.clipPolygons(this.polygons);
  62696. if (this.front)
  62697. this.front.clipTo(bsp);
  62698. if (this.back)
  62699. this.back.clipTo(bsp);
  62700. };
  62701. // Return a list of all polygons in this BSP tree.
  62702. Node.prototype.allPolygons = function () {
  62703. var polygons = this.polygons.slice();
  62704. if (this.front)
  62705. polygons = polygons.concat(this.front.allPolygons());
  62706. if (this.back)
  62707. polygons = polygons.concat(this.back.allPolygons());
  62708. return polygons;
  62709. };
  62710. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  62711. // new polygons are filtered down to the bottom of the tree and become new
  62712. // nodes there. Each set of polygons is partitioned using the first polygon
  62713. // (no heuristic is used to pick a good split).
  62714. Node.prototype.build = function (polygons) {
  62715. if (!polygons.length)
  62716. return;
  62717. if (!this.plane)
  62718. this.plane = polygons[0].plane.clone();
  62719. var front = new Array(), back = new Array();
  62720. for (var i = 0; i < polygons.length; i++) {
  62721. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  62722. }
  62723. if (front.length) {
  62724. if (!this.front)
  62725. this.front = new Node();
  62726. this.front.build(front);
  62727. }
  62728. if (back.length) {
  62729. if (!this.back)
  62730. this.back = new Node();
  62731. this.back.build(back);
  62732. }
  62733. };
  62734. return Node;
  62735. }());
  62736. var CSG = (function () {
  62737. function CSG() {
  62738. this.polygons = new Array();
  62739. }
  62740. // Convert BABYLON.Mesh to BABYLON.CSG
  62741. CSG.FromMesh = function (mesh) {
  62742. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  62743. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  62744. if (mesh instanceof BABYLON.Mesh) {
  62745. mesh.computeWorldMatrix(true);
  62746. matrix = mesh.getWorldMatrix();
  62747. meshPosition = mesh.position.clone();
  62748. meshRotation = mesh.rotation.clone();
  62749. if (mesh.rotationQuaternion) {
  62750. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  62751. }
  62752. meshScaling = mesh.scaling.clone();
  62753. }
  62754. else {
  62755. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  62756. }
  62757. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62758. var subMeshes = mesh.subMeshes;
  62759. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  62760. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  62761. vertices = [];
  62762. for (var j = 0; j < 3; j++) {
  62763. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  62764. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  62765. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  62766. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  62767. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  62768. vertex = new Vertex(position, normal, uv);
  62769. vertices.push(vertex);
  62770. }
  62771. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  62772. // To handle the case of degenerated triangle
  62773. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  62774. if (polygon.plane)
  62775. polygons.push(polygon);
  62776. }
  62777. }
  62778. var csg = CSG.FromPolygons(polygons);
  62779. csg.matrix = matrix;
  62780. csg.position = meshPosition;
  62781. csg.rotation = meshRotation;
  62782. csg.scaling = meshScaling;
  62783. csg.rotationQuaternion = meshRotationQuaternion;
  62784. currentCSGMeshId++;
  62785. return csg;
  62786. };
  62787. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  62788. CSG.FromPolygons = function (polygons) {
  62789. var csg = new CSG();
  62790. csg.polygons = polygons;
  62791. return csg;
  62792. };
  62793. CSG.prototype.clone = function () {
  62794. var csg = new CSG();
  62795. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  62796. csg.copyTransformAttributes(this);
  62797. return csg;
  62798. };
  62799. CSG.prototype.union = function (csg) {
  62800. var a = new Node(this.clone().polygons);
  62801. var b = new Node(csg.clone().polygons);
  62802. a.clipTo(b);
  62803. b.clipTo(a);
  62804. b.invert();
  62805. b.clipTo(a);
  62806. b.invert();
  62807. a.build(b.allPolygons());
  62808. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  62809. };
  62810. CSG.prototype.unionInPlace = function (csg) {
  62811. var a = new Node(this.polygons);
  62812. var b = new Node(csg.polygons);
  62813. a.clipTo(b);
  62814. b.clipTo(a);
  62815. b.invert();
  62816. b.clipTo(a);
  62817. b.invert();
  62818. a.build(b.allPolygons());
  62819. this.polygons = a.allPolygons();
  62820. };
  62821. CSG.prototype.subtract = function (csg) {
  62822. var a = new Node(this.clone().polygons);
  62823. var b = new Node(csg.clone().polygons);
  62824. a.invert();
  62825. a.clipTo(b);
  62826. b.clipTo(a);
  62827. b.invert();
  62828. b.clipTo(a);
  62829. b.invert();
  62830. a.build(b.allPolygons());
  62831. a.invert();
  62832. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  62833. };
  62834. CSG.prototype.subtractInPlace = function (csg) {
  62835. var a = new Node(this.polygons);
  62836. var b = new Node(csg.polygons);
  62837. a.invert();
  62838. a.clipTo(b);
  62839. b.clipTo(a);
  62840. b.invert();
  62841. b.clipTo(a);
  62842. b.invert();
  62843. a.build(b.allPolygons());
  62844. a.invert();
  62845. this.polygons = a.allPolygons();
  62846. };
  62847. CSG.prototype.intersect = function (csg) {
  62848. var a = new Node(this.clone().polygons);
  62849. var b = new Node(csg.clone().polygons);
  62850. a.invert();
  62851. b.clipTo(a);
  62852. b.invert();
  62853. a.clipTo(b);
  62854. b.clipTo(a);
  62855. a.build(b.allPolygons());
  62856. a.invert();
  62857. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  62858. };
  62859. CSG.prototype.intersectInPlace = function (csg) {
  62860. var a = new Node(this.polygons);
  62861. var b = new Node(csg.polygons);
  62862. a.invert();
  62863. b.clipTo(a);
  62864. b.invert();
  62865. a.clipTo(b);
  62866. b.clipTo(a);
  62867. a.build(b.allPolygons());
  62868. a.invert();
  62869. this.polygons = a.allPolygons();
  62870. };
  62871. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  62872. // not modified.
  62873. CSG.prototype.inverse = function () {
  62874. var csg = this.clone();
  62875. csg.inverseInPlace();
  62876. return csg;
  62877. };
  62878. CSG.prototype.inverseInPlace = function () {
  62879. this.polygons.map(function (p) { p.flip(); });
  62880. };
  62881. // This is used to keep meshes transformations so they can be restored
  62882. // when we build back a Babylon Mesh
  62883. // NB : All CSG operations are performed in world coordinates
  62884. CSG.prototype.copyTransformAttributes = function (csg) {
  62885. this.matrix = csg.matrix;
  62886. this.position = csg.position;
  62887. this.rotation = csg.rotation;
  62888. this.scaling = csg.scaling;
  62889. this.rotationQuaternion = csg.rotationQuaternion;
  62890. return this;
  62891. };
  62892. // Build Raw mesh from CSG
  62893. // Coordinates here are in world space
  62894. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  62895. var matrix = this.matrix.clone();
  62896. matrix.invert();
  62897. 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;
  62898. if (keepSubMeshes) {
  62899. // Sort Polygons, since subMeshes are indices range
  62900. polygons.sort(function (a, b) {
  62901. if (a.shared.meshId === b.shared.meshId) {
  62902. return a.shared.subMeshId - b.shared.subMeshId;
  62903. }
  62904. else {
  62905. return a.shared.meshId - b.shared.meshId;
  62906. }
  62907. });
  62908. }
  62909. for (var i = 0, il = polygons.length; i < il; i++) {
  62910. polygon = polygons[i];
  62911. // Building SubMeshes
  62912. if (!subMesh_dict[polygon.shared.meshId]) {
  62913. subMesh_dict[polygon.shared.meshId] = {};
  62914. }
  62915. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  62916. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  62917. indexStart: +Infinity,
  62918. indexEnd: -Infinity,
  62919. materialIndex: polygon.shared.materialIndex
  62920. };
  62921. }
  62922. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  62923. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  62924. polygonIndices[0] = 0;
  62925. polygonIndices[1] = j - 1;
  62926. polygonIndices[2] = j;
  62927. for (var k = 0; k < 3; k++) {
  62928. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  62929. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  62930. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  62931. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  62932. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  62933. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  62934. // Check if 2 points can be merged
  62935. if (!(typeof vertex_idx !== 'undefined' &&
  62936. normals[vertex_idx * 3] === localNormal.x &&
  62937. normals[vertex_idx * 3 + 1] === localNormal.y &&
  62938. normals[vertex_idx * 3 + 2] === localNormal.z &&
  62939. uvs[vertex_idx * 2] === uv.x &&
  62940. uvs[vertex_idx * 2 + 1] === uv.y)) {
  62941. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  62942. uvs.push(uv.x, uv.y);
  62943. normals.push(normal.x, normal.y, normal.z);
  62944. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  62945. }
  62946. indices.push(vertex_idx);
  62947. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  62948. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  62949. currentIndex++;
  62950. }
  62951. }
  62952. }
  62953. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  62954. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  62955. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  62956. mesh.setIndices(indices);
  62957. if (keepSubMeshes) {
  62958. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  62959. var materialIndexOffset = 0, materialMaxIndex;
  62960. mesh.subMeshes = new Array();
  62961. for (var m in subMesh_dict) {
  62962. materialMaxIndex = -1;
  62963. for (var sm in subMesh_dict[m]) {
  62964. subMesh_obj = subMesh_dict[m][sm];
  62965. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  62966. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  62967. }
  62968. materialIndexOffset += ++materialMaxIndex;
  62969. }
  62970. }
  62971. return mesh;
  62972. };
  62973. // Build Mesh from CSG taking material and transforms into account
  62974. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  62975. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  62976. mesh.material = material;
  62977. mesh.position.copyFrom(this.position);
  62978. mesh.rotation.copyFrom(this.rotation);
  62979. if (this.rotationQuaternion) {
  62980. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  62981. }
  62982. mesh.scaling.copyFrom(this.scaling);
  62983. mesh.computeWorldMatrix(true);
  62984. return mesh;
  62985. };
  62986. return CSG;
  62987. }());
  62988. BABYLON.CSG = CSG;
  62989. })(BABYLON || (BABYLON = {}));
  62990. //# sourceMappingURL=babylon.csg.js.map
  62991. var BABYLON;
  62992. (function (BABYLON) {
  62993. var LensFlare = (function () {
  62994. function LensFlare(size, position, color, imgUrl, system) {
  62995. this.size = size;
  62996. this.position = position;
  62997. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  62998. this.color = color || new BABYLON.Color3(1, 1, 1);
  62999. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  63000. this._system = system;
  63001. system.lensFlares.push(this);
  63002. }
  63003. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  63004. return new LensFlare(size, position, color, imgUrl, system);
  63005. };
  63006. LensFlare.prototype.dispose = function () {
  63007. if (this.texture) {
  63008. this.texture.dispose();
  63009. }
  63010. // Remove from scene
  63011. var index = this._system.lensFlares.indexOf(this);
  63012. this._system.lensFlares.splice(index, 1);
  63013. };
  63014. ;
  63015. return LensFlare;
  63016. }());
  63017. BABYLON.LensFlare = LensFlare;
  63018. })(BABYLON || (BABYLON = {}));
  63019. //# sourceMappingURL=babylon.lensFlare.js.map
  63020. var BABYLON;
  63021. (function (BABYLON) {
  63022. var LensFlareSystem = (function () {
  63023. function LensFlareSystem(name, emitter, scene) {
  63024. this.name = name;
  63025. this.lensFlares = new Array();
  63026. this.borderLimit = 300;
  63027. this.viewportBorder = 0;
  63028. this.layerMask = 0x0FFFFFFF;
  63029. this._vertexBuffers = {};
  63030. this._isEnabled = true;
  63031. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63032. this._emitter = emitter;
  63033. this.id = name;
  63034. scene.lensFlareSystems.push(this);
  63035. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  63036. var engine = scene.getEngine();
  63037. // VBO
  63038. var vertices = [];
  63039. vertices.push(1, 1);
  63040. vertices.push(-1, 1);
  63041. vertices.push(-1, -1);
  63042. vertices.push(1, -1);
  63043. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  63044. // Indices
  63045. var indices = [];
  63046. indices.push(0);
  63047. indices.push(1);
  63048. indices.push(2);
  63049. indices.push(0);
  63050. indices.push(2);
  63051. indices.push(3);
  63052. this._indexBuffer = engine.createIndexBuffer(indices);
  63053. // Effects
  63054. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  63055. }
  63056. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  63057. get: function () {
  63058. return this._isEnabled;
  63059. },
  63060. set: function (value) {
  63061. this._isEnabled = value;
  63062. },
  63063. enumerable: true,
  63064. configurable: true
  63065. });
  63066. LensFlareSystem.prototype.getScene = function () {
  63067. return this._scene;
  63068. };
  63069. LensFlareSystem.prototype.getEmitter = function () {
  63070. return this._emitter;
  63071. };
  63072. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  63073. this._emitter = newEmitter;
  63074. };
  63075. LensFlareSystem.prototype.getEmitterPosition = function () {
  63076. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  63077. };
  63078. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  63079. var position = this.getEmitterPosition();
  63080. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  63081. this._positionX = position.x;
  63082. this._positionY = position.y;
  63083. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  63084. if (this.viewportBorder > 0) {
  63085. globalViewport.x -= this.viewportBorder;
  63086. globalViewport.y -= this.viewportBorder;
  63087. globalViewport.width += this.viewportBorder * 2;
  63088. globalViewport.height += this.viewportBorder * 2;
  63089. position.x += this.viewportBorder;
  63090. position.y += this.viewportBorder;
  63091. this._positionX += this.viewportBorder;
  63092. this._positionY += this.viewportBorder;
  63093. }
  63094. if (position.z > 0) {
  63095. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  63096. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  63097. return true;
  63098. }
  63099. return true;
  63100. }
  63101. return false;
  63102. };
  63103. LensFlareSystem.prototype._isVisible = function () {
  63104. if (!this._isEnabled) {
  63105. return false;
  63106. }
  63107. var emitterPosition = this.getEmitterPosition();
  63108. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  63109. var distance = direction.length();
  63110. direction.normalize();
  63111. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  63112. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  63113. return !pickInfo.hit || pickInfo.distance > distance;
  63114. };
  63115. LensFlareSystem.prototype.render = function () {
  63116. if (!this._effect.isReady())
  63117. return false;
  63118. var engine = this._scene.getEngine();
  63119. var viewport = this._scene.activeCamera.viewport;
  63120. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  63121. // Position
  63122. if (!this.computeEffectivePosition(globalViewport)) {
  63123. return false;
  63124. }
  63125. // Visibility
  63126. if (!this._isVisible()) {
  63127. return false;
  63128. }
  63129. // Intensity
  63130. var awayX;
  63131. var awayY;
  63132. if (this._positionX < this.borderLimit + globalViewport.x) {
  63133. awayX = this.borderLimit + globalViewport.x - this._positionX;
  63134. }
  63135. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  63136. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  63137. }
  63138. else {
  63139. awayX = 0;
  63140. }
  63141. if (this._positionY < this.borderLimit + globalViewport.y) {
  63142. awayY = this.borderLimit + globalViewport.y - this._positionY;
  63143. }
  63144. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  63145. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  63146. }
  63147. else {
  63148. awayY = 0;
  63149. }
  63150. var away = (awayX > awayY) ? awayX : awayY;
  63151. away -= this.viewportBorder;
  63152. if (away > this.borderLimit) {
  63153. away = this.borderLimit;
  63154. }
  63155. var intensity = 1.0 - (away / this.borderLimit);
  63156. if (intensity < 0) {
  63157. return false;
  63158. }
  63159. if (intensity > 1.0) {
  63160. intensity = 1.0;
  63161. }
  63162. if (this.viewportBorder > 0) {
  63163. globalViewport.x += this.viewportBorder;
  63164. globalViewport.y += this.viewportBorder;
  63165. globalViewport.width -= this.viewportBorder * 2;
  63166. globalViewport.height -= this.viewportBorder * 2;
  63167. this._positionX -= this.viewportBorder;
  63168. this._positionY -= this.viewportBorder;
  63169. }
  63170. // Position
  63171. var centerX = globalViewport.x + globalViewport.width / 2;
  63172. var centerY = globalViewport.y + globalViewport.height / 2;
  63173. var distX = centerX - this._positionX;
  63174. var distY = centerY - this._positionY;
  63175. // Effects
  63176. engine.enableEffect(this._effect);
  63177. engine.setState(false);
  63178. engine.setDepthBuffer(false);
  63179. // VBOs
  63180. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63181. // Flares
  63182. for (var index = 0; index < this.lensFlares.length; index++) {
  63183. var flare = this.lensFlares[index];
  63184. engine.setAlphaMode(flare.alphaMode);
  63185. var x = centerX - (distX * flare.position);
  63186. var y = centerY - (distY * flare.position);
  63187. var cw = flare.size;
  63188. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  63189. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  63190. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  63191. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  63192. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  63193. // Texture
  63194. this._effect.setTexture("textureSampler", flare.texture);
  63195. // Color
  63196. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  63197. // Draw order
  63198. engine.draw(true, 0, 6);
  63199. }
  63200. engine.setDepthBuffer(true);
  63201. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  63202. return true;
  63203. };
  63204. LensFlareSystem.prototype.dispose = function () {
  63205. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63206. if (vertexBuffer) {
  63207. vertexBuffer.dispose();
  63208. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63209. }
  63210. if (this._indexBuffer) {
  63211. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  63212. this._indexBuffer = null;
  63213. }
  63214. while (this.lensFlares.length) {
  63215. this.lensFlares[0].dispose();
  63216. }
  63217. // Remove from scene
  63218. var index = this._scene.lensFlareSystems.indexOf(this);
  63219. this._scene.lensFlareSystems.splice(index, 1);
  63220. };
  63221. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  63222. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  63223. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  63224. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  63225. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  63226. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  63227. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  63228. var parsedFlare = parsedLensFlareSystem.flares[index];
  63229. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  63230. }
  63231. return lensFlareSystem;
  63232. };
  63233. LensFlareSystem.prototype.serialize = function () {
  63234. var serializationObject = {};
  63235. serializationObject.id = this.id;
  63236. serializationObject.name = this.name;
  63237. serializationObject.emitterId = this.getEmitter().id;
  63238. serializationObject.borderLimit = this.borderLimit;
  63239. serializationObject.flares = [];
  63240. for (var index = 0; index < this.lensFlares.length; index++) {
  63241. var flare = this.lensFlares[index];
  63242. serializationObject.flares.push({
  63243. size: flare.size,
  63244. position: flare.position,
  63245. color: flare.color.asArray(),
  63246. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  63247. });
  63248. }
  63249. return serializationObject;
  63250. };
  63251. return LensFlareSystem;
  63252. }());
  63253. BABYLON.LensFlareSystem = LensFlareSystem;
  63254. })(BABYLON || (BABYLON = {}));
  63255. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  63256. var BABYLON;
  63257. (function (BABYLON) {
  63258. /**
  63259. * This is a holder class for the physics joint created by the physics plugin.
  63260. * It holds a set of functions to control the underlying joint.
  63261. */
  63262. var PhysicsJoint = (function () {
  63263. function PhysicsJoint(type, jointData) {
  63264. this.type = type;
  63265. this.jointData = jointData;
  63266. jointData.nativeParams = jointData.nativeParams || {};
  63267. }
  63268. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  63269. get: function () {
  63270. return this._physicsJoint;
  63271. },
  63272. set: function (newJoint) {
  63273. if (this._physicsJoint) {
  63274. //remove from the wolrd
  63275. }
  63276. this._physicsJoint = newJoint;
  63277. },
  63278. enumerable: true,
  63279. configurable: true
  63280. });
  63281. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  63282. set: function (physicsPlugin) {
  63283. this._physicsPlugin = physicsPlugin;
  63284. },
  63285. enumerable: true,
  63286. configurable: true
  63287. });
  63288. /**
  63289. * Execute a function that is physics-plugin specific.
  63290. * @param {Function} func the function that will be executed.
  63291. * It accepts two parameters: the physics world and the physics joint.
  63292. */
  63293. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  63294. func(this._physicsPlugin.world, this._physicsJoint);
  63295. };
  63296. //TODO check if the native joints are the same
  63297. //Joint Types
  63298. PhysicsJoint.DistanceJoint = 0;
  63299. PhysicsJoint.HingeJoint = 1;
  63300. PhysicsJoint.BallAndSocketJoint = 2;
  63301. PhysicsJoint.WheelJoint = 3;
  63302. PhysicsJoint.SliderJoint = 4;
  63303. //OIMO
  63304. PhysicsJoint.PrismaticJoint = 5;
  63305. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  63306. PhysicsJoint.UniversalJoint = 6;
  63307. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  63308. //Cannon
  63309. //Similar to a Ball-Joint. Different in params
  63310. PhysicsJoint.PointToPointJoint = 8;
  63311. //Cannon only at the moment
  63312. PhysicsJoint.SpringJoint = 9;
  63313. PhysicsJoint.LockJoint = 10;
  63314. return PhysicsJoint;
  63315. }());
  63316. BABYLON.PhysicsJoint = PhysicsJoint;
  63317. /**
  63318. * A class representing a physics distance joint.
  63319. */
  63320. var DistanceJoint = (function (_super) {
  63321. __extends(DistanceJoint, _super);
  63322. function DistanceJoint(jointData) {
  63323. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  63324. }
  63325. /**
  63326. * Update the predefined distance.
  63327. */
  63328. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  63329. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  63330. };
  63331. return DistanceJoint;
  63332. }(PhysicsJoint));
  63333. BABYLON.DistanceJoint = DistanceJoint;
  63334. var MotorEnabledJoint = (function (_super) {
  63335. __extends(MotorEnabledJoint, _super);
  63336. function MotorEnabledJoint(type, jointData) {
  63337. return _super.call(this, type, jointData) || this;
  63338. }
  63339. /**
  63340. * Set the motor values.
  63341. * Attention, this function is plugin specific. Engines won't react 100% the same.
  63342. * @param {number} force the force to apply
  63343. * @param {number} maxForce max force for this motor.
  63344. */
  63345. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  63346. this._physicsPlugin.setMotor(this, force, maxForce);
  63347. };
  63348. /**
  63349. * Set the motor's limits.
  63350. * Attention, this function is plugin specific. Engines won't react 100% the same.
  63351. */
  63352. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  63353. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  63354. };
  63355. return MotorEnabledJoint;
  63356. }(PhysicsJoint));
  63357. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  63358. /**
  63359. * This class represents a single hinge physics joint
  63360. */
  63361. var HingeJoint = (function (_super) {
  63362. __extends(HingeJoint, _super);
  63363. function HingeJoint(jointData) {
  63364. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  63365. }
  63366. /**
  63367. * Set the motor values.
  63368. * Attention, this function is plugin specific. Engines won't react 100% the same.
  63369. * @param {number} force the force to apply
  63370. * @param {number} maxForce max force for this motor.
  63371. */
  63372. HingeJoint.prototype.setMotor = function (force, maxForce) {
  63373. this._physicsPlugin.setMotor(this, force, maxForce);
  63374. };
  63375. /**
  63376. * Set the motor's limits.
  63377. * Attention, this function is plugin specific. Engines won't react 100% the same.
  63378. */
  63379. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  63380. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  63381. };
  63382. return HingeJoint;
  63383. }(MotorEnabledJoint));
  63384. BABYLON.HingeJoint = HingeJoint;
  63385. /**
  63386. * This class represents a dual hinge physics joint (same as wheel joint)
  63387. */
  63388. var Hinge2Joint = (function (_super) {
  63389. __extends(Hinge2Joint, _super);
  63390. function Hinge2Joint(jointData) {
  63391. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  63392. }
  63393. /**
  63394. * Set the motor values.
  63395. * Attention, this function is plugin specific. Engines won't react 100% the same.
  63396. * @param {number} force the force to apply
  63397. * @param {number} maxForce max force for this motor.
  63398. * @param {motorIndex} the motor's index, 0 or 1.
  63399. */
  63400. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  63401. if (motorIndex === void 0) { motorIndex = 0; }
  63402. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  63403. };
  63404. /**
  63405. * Set the motor limits.
  63406. * Attention, this function is plugin specific. Engines won't react 100% the same.
  63407. * @param {number} upperLimit the upper limit
  63408. * @param {number} lowerLimit lower limit
  63409. * @param {motorIndex} the motor's index, 0 or 1.
  63410. */
  63411. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  63412. if (motorIndex === void 0) { motorIndex = 0; }
  63413. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  63414. };
  63415. return Hinge2Joint;
  63416. }(MotorEnabledJoint));
  63417. BABYLON.Hinge2Joint = Hinge2Joint;
  63418. })(BABYLON || (BABYLON = {}));
  63419. //# sourceMappingURL=babylon.physicsJoint.js.map
  63420. var BABYLON;
  63421. (function (BABYLON) {
  63422. var PhysicsImpostor = (function () {
  63423. function PhysicsImpostor(object, type, _options, _scene) {
  63424. if (_options === void 0) { _options = { mass: 0 }; }
  63425. var _this = this;
  63426. this.object = object;
  63427. this.type = type;
  63428. this._options = _options;
  63429. this._scene = _scene;
  63430. this._bodyUpdateRequired = false;
  63431. this._onBeforePhysicsStepCallbacks = new Array();
  63432. this._onAfterPhysicsStepCallbacks = new Array();
  63433. this._onPhysicsCollideCallbacks = [];
  63434. this._deltaPosition = BABYLON.Vector3.Zero();
  63435. this._isDisposed = false;
  63436. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  63437. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  63438. /**
  63439. * this function is executed by the physics engine.
  63440. */
  63441. this.beforeStep = function () {
  63442. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  63443. //conjugate deltaRotation
  63444. if (_this._deltaRotationConjugated) {
  63445. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  63446. }
  63447. else {
  63448. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  63449. }
  63450. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  63451. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  63452. func(_this);
  63453. });
  63454. };
  63455. /**
  63456. * this function is executed by the physics engine.
  63457. */
  63458. this.afterStep = function () {
  63459. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  63460. func(_this);
  63461. });
  63462. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  63463. _this.object.position.addInPlace(_this._deltaPosition);
  63464. if (_this._deltaRotation) {
  63465. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  63466. }
  63467. };
  63468. /**
  63469. * Legacy collision detection event support
  63470. */
  63471. this.onCollideEvent = null;
  63472. //event and body object due to cannon's event-based architecture.
  63473. this.onCollide = function (e) {
  63474. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  63475. return;
  63476. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  63477. if (otherImpostor) {
  63478. // Legacy collision detection event support
  63479. if (_this.onCollideEvent) {
  63480. _this.onCollideEvent(_this, otherImpostor);
  63481. }
  63482. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  63483. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  63484. }).forEach(function (obj) {
  63485. obj.callback(_this, otherImpostor);
  63486. });
  63487. }
  63488. };
  63489. //sanity check!
  63490. if (!this.object) {
  63491. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  63492. return;
  63493. }
  63494. //legacy support for old syntax.
  63495. if (!this._scene && object.getScene) {
  63496. this._scene = object.getScene();
  63497. }
  63498. this._physicsEngine = this._scene.getPhysicsEngine();
  63499. if (!this._physicsEngine) {
  63500. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  63501. }
  63502. else {
  63503. //set the object's quaternion, if not set
  63504. if (!this.object.rotationQuaternion) {
  63505. if (this.object.rotation) {
  63506. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  63507. }
  63508. else {
  63509. this.object.rotationQuaternion = new BABYLON.Quaternion();
  63510. }
  63511. }
  63512. //default options params
  63513. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  63514. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  63515. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  63516. this._joints = [];
  63517. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  63518. if (!this.object.parent) {
  63519. this._init();
  63520. }
  63521. else if (this.object.parent.physicsImpostor) {
  63522. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  63523. }
  63524. }
  63525. }
  63526. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  63527. get: function () {
  63528. return this._isDisposed;
  63529. },
  63530. enumerable: true,
  63531. configurable: true
  63532. });
  63533. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  63534. get: function () {
  63535. return this._physicsEngine.getPhysicsPlugin().getBodyMass(this);
  63536. },
  63537. set: function (value) {
  63538. this.setMass(value);
  63539. },
  63540. enumerable: true,
  63541. configurable: true
  63542. });
  63543. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  63544. get: function () {
  63545. return this._physicsEngine.getPhysicsPlugin().getBodyFriction(this);
  63546. },
  63547. set: function (value) {
  63548. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  63549. },
  63550. enumerable: true,
  63551. configurable: true
  63552. });
  63553. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  63554. get: function () {
  63555. return this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this);
  63556. },
  63557. set: function (value) {
  63558. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  63559. },
  63560. enumerable: true,
  63561. configurable: true
  63562. });
  63563. /**
  63564. * This function will completly initialize this impostor.
  63565. * It will create a new body - but only if this mesh has no parent.
  63566. * If it has, this impostor will not be used other than to define the impostor
  63567. * of the child mesh.
  63568. */
  63569. PhysicsImpostor.prototype._init = function () {
  63570. this._physicsEngine.removeImpostor(this);
  63571. this.physicsBody = null;
  63572. this._parent = this._parent || this._getPhysicsParent();
  63573. if (!this.parent) {
  63574. this._physicsEngine.addImpostor(this);
  63575. }
  63576. };
  63577. PhysicsImpostor.prototype._getPhysicsParent = function () {
  63578. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  63579. var parentMesh = this.object.parent;
  63580. return parentMesh.physicsImpostor;
  63581. }
  63582. return null;
  63583. };
  63584. /**
  63585. * Should a new body be generated.
  63586. */
  63587. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  63588. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  63589. };
  63590. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  63591. this.forceUpdate();
  63592. };
  63593. /**
  63594. * Force a regeneration of this or the parent's impostor's body.
  63595. * Use under cautious - This will remove all joints already implemented.
  63596. */
  63597. PhysicsImpostor.prototype.forceUpdate = function () {
  63598. this._init();
  63599. if (this.parent) {
  63600. this.parent.forceUpdate();
  63601. }
  63602. };
  63603. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  63604. /*public get mesh(): AbstractMesh {
  63605. return this._mesh;
  63606. }*/
  63607. /**
  63608. * Gets the body that holds this impostor. Either its own, or its parent.
  63609. */
  63610. get: function () {
  63611. return this._parent ? this._parent.physicsBody : this._physicsBody;
  63612. },
  63613. /**
  63614. * Set the physics body. Used mainly by the physics engine/plugin
  63615. */
  63616. set: function (physicsBody) {
  63617. if (this._physicsBody) {
  63618. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  63619. }
  63620. this._physicsBody = physicsBody;
  63621. this.resetUpdateFlags();
  63622. },
  63623. enumerable: true,
  63624. configurable: true
  63625. });
  63626. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  63627. get: function () {
  63628. return this._parent;
  63629. },
  63630. set: function (value) {
  63631. this._parent = value;
  63632. },
  63633. enumerable: true,
  63634. configurable: true
  63635. });
  63636. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  63637. this._bodyUpdateRequired = false;
  63638. };
  63639. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  63640. if (this.object.getBoundingInfo) {
  63641. var q = this.object.rotationQuaternion;
  63642. //reset rotation
  63643. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  63644. //calculate the world matrix with no rotation
  63645. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  63646. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  63647. //bring back the rotation
  63648. this.object.rotationQuaternion = q;
  63649. //calculate the world matrix with the new rotation
  63650. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  63651. return size;
  63652. }
  63653. else {
  63654. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  63655. }
  63656. };
  63657. PhysicsImpostor.prototype.getObjectCenter = function () {
  63658. if (this.object.getBoundingInfo) {
  63659. return this.object.getBoundingInfo().boundingBox.centerWorld;
  63660. }
  63661. else {
  63662. return this.object.position;
  63663. }
  63664. };
  63665. /**
  63666. * Get a specific parametes from the options parameter.
  63667. */
  63668. PhysicsImpostor.prototype.getParam = function (paramName) {
  63669. return this._options[paramName];
  63670. };
  63671. /**
  63672. * Sets a specific parameter in the options given to the physics plugin
  63673. */
  63674. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  63675. this._options[paramName] = value;
  63676. this._bodyUpdateRequired = true;
  63677. };
  63678. /**
  63679. * Specifically change the body's mass option. Won't recreate the physics body object
  63680. */
  63681. PhysicsImpostor.prototype.setMass = function (mass) {
  63682. if (this.getParam("mass") !== mass) {
  63683. this.setParam("mass", mass);
  63684. }
  63685. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  63686. };
  63687. PhysicsImpostor.prototype.getLinearVelocity = function () {
  63688. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  63689. };
  63690. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  63691. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  63692. };
  63693. PhysicsImpostor.prototype.getAngularVelocity = function () {
  63694. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  63695. };
  63696. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  63697. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  63698. };
  63699. /**
  63700. * Execute a function with the physics plugin native code.
  63701. * Provide a function the will have two variables - the world object and the physics body object.
  63702. */
  63703. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  63704. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  63705. };
  63706. /**
  63707. * Register a function that will be executed before the physics world is stepping forward.
  63708. */
  63709. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  63710. this._onBeforePhysicsStepCallbacks.push(func);
  63711. };
  63712. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  63713. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  63714. if (index > -1) {
  63715. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  63716. }
  63717. else {
  63718. BABYLON.Tools.Warn("Function to remove was not found");
  63719. }
  63720. };
  63721. /**
  63722. * Register a function that will be executed after the physics step
  63723. */
  63724. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  63725. this._onAfterPhysicsStepCallbacks.push(func);
  63726. };
  63727. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  63728. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  63729. if (index > -1) {
  63730. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  63731. }
  63732. else {
  63733. BABYLON.Tools.Warn("Function to remove was not found");
  63734. }
  63735. };
  63736. /**
  63737. * register a function that will be executed when this impostor collides against a different body.
  63738. */
  63739. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  63740. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  63741. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  63742. };
  63743. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  63744. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  63745. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  63746. if (index > -1) {
  63747. this._onPhysicsCollideCallbacks.splice(index, 1);
  63748. }
  63749. else {
  63750. BABYLON.Tools.Warn("Function to remove was not found");
  63751. }
  63752. };
  63753. /**
  63754. * Apply a force
  63755. */
  63756. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  63757. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  63758. };
  63759. /**
  63760. * Apply an impulse
  63761. */
  63762. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  63763. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  63764. };
  63765. /**
  63766. * A help function to create a joint.
  63767. */
  63768. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  63769. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  63770. this.addJoint(otherImpostor, joint);
  63771. };
  63772. /**
  63773. * Add a joint to this impostor with a different impostor.
  63774. */
  63775. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  63776. this._joints.push({
  63777. otherImpostor: otherImpostor,
  63778. joint: joint
  63779. });
  63780. this._physicsEngine.addJoint(this, otherImpostor, joint);
  63781. };
  63782. /**
  63783. * Will keep this body still, in a sleep mode.
  63784. */
  63785. PhysicsImpostor.prototype.sleep = function () {
  63786. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  63787. };
  63788. /**
  63789. * Wake the body up.
  63790. */
  63791. PhysicsImpostor.prototype.wakeUp = function () {
  63792. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  63793. };
  63794. PhysicsImpostor.prototype.clone = function (newObject) {
  63795. if (!newObject)
  63796. return null;
  63797. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  63798. };
  63799. PhysicsImpostor.prototype.dispose = function () {
  63800. var _this = this;
  63801. //no dispose if no physics engine is available.
  63802. if (!this._physicsEngine) {
  63803. return;
  63804. }
  63805. this._joints.forEach(function (j) {
  63806. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  63807. });
  63808. //dispose the physics body
  63809. this._physicsEngine.removeImpostor(this);
  63810. if (this.parent) {
  63811. this.parent.forceUpdate();
  63812. }
  63813. else {
  63814. /*this._object.getChildMeshes().forEach(function(mesh) {
  63815. if (mesh.physicsImpostor) {
  63816. if (disposeChildren) {
  63817. mesh.physicsImpostor.dispose();
  63818. mesh.physicsImpostor = null;
  63819. }
  63820. }
  63821. })*/
  63822. }
  63823. this._isDisposed = true;
  63824. };
  63825. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  63826. this._deltaPosition.copyFrom(position);
  63827. };
  63828. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  63829. if (!this._deltaRotation) {
  63830. this._deltaRotation = new BABYLON.Quaternion();
  63831. }
  63832. this._deltaRotation.copyFrom(rotation);
  63833. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  63834. };
  63835. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  63836. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  63837. };
  63838. PhysicsImpostor.prototype.getRadius = function () {
  63839. return this._physicsEngine.getPhysicsPlugin().getRadius(this);
  63840. };
  63841. /**
  63842. * Sync a bone with this impostor
  63843. * @param bone The bone to sync to the impostor.
  63844. * @param boneMesh The mesh that the bone is influencing.
  63845. * @param jointPivot The pivot of the joint / bone in local space.
  63846. * @param distToJoint Optional distance from the impostor to the joint.
  63847. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  63848. */
  63849. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  63850. var tempVec = PhysicsImpostor._tmpVecs[0];
  63851. var mesh = this.object;
  63852. if (adjustRotation) {
  63853. var tempQuat = PhysicsImpostor._tmpQuat;
  63854. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  63855. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  63856. }
  63857. else {
  63858. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  63859. }
  63860. tempVec.x = 0;
  63861. tempVec.y = 0;
  63862. tempVec.z = 0;
  63863. if (jointPivot) {
  63864. tempVec.x = jointPivot.x;
  63865. tempVec.y = jointPivot.y;
  63866. tempVec.z = jointPivot.z;
  63867. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  63868. if (distToJoint === undefined || distToJoint === null) {
  63869. distToJoint = jointPivot.length();
  63870. }
  63871. tempVec.x *= distToJoint;
  63872. tempVec.y *= distToJoint;
  63873. tempVec.z *= distToJoint;
  63874. }
  63875. if (bone.getParent()) {
  63876. tempVec.addInPlace(mesh.getAbsolutePosition());
  63877. bone.setAbsolutePosition(tempVec, boneMesh);
  63878. }
  63879. else {
  63880. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  63881. boneMesh.position.x -= tempVec.x;
  63882. boneMesh.position.y -= tempVec.y;
  63883. boneMesh.position.z -= tempVec.z;
  63884. }
  63885. };
  63886. /**
  63887. * Sync impostor to a bone
  63888. * @param bone The bone that the impostor will be synced to.
  63889. * @param boneMesh The mesh that the bone is influencing.
  63890. * @param jointPivot The pivot of the joint / bone in local space.
  63891. * @param distToJoint Optional distance from the impostor to the joint.
  63892. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  63893. * @param boneAxis Optional vector3 axis the bone is aligned with
  63894. */
  63895. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  63896. var mesh = this.object;
  63897. if (adjustRotation) {
  63898. var tempQuat = PhysicsImpostor._tmpQuat;
  63899. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  63900. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  63901. }
  63902. else {
  63903. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  63904. }
  63905. var pos = PhysicsImpostor._tmpVecs[0];
  63906. var boneDir = PhysicsImpostor._tmpVecs[1];
  63907. if (!boneAxis) {
  63908. boneAxis = PhysicsImpostor._tmpVecs[2];
  63909. boneAxis.x = 0;
  63910. boneAxis.y = 1;
  63911. boneAxis.z = 0;
  63912. }
  63913. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  63914. bone.getAbsolutePositionToRef(boneMesh, pos);
  63915. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  63916. distToJoint = jointPivot.length();
  63917. }
  63918. if (distToJoint !== undefined && distToJoint !== null) {
  63919. pos.x += boneDir.x * distToJoint;
  63920. pos.y += boneDir.y * distToJoint;
  63921. pos.z += boneDir.z * distToJoint;
  63922. }
  63923. mesh.setAbsolutePosition(pos);
  63924. };
  63925. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  63926. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  63927. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63928. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  63929. //Impostor types
  63930. PhysicsImpostor.NoImpostor = 0;
  63931. PhysicsImpostor.SphereImpostor = 1;
  63932. PhysicsImpostor.BoxImpostor = 2;
  63933. PhysicsImpostor.PlaneImpostor = 3;
  63934. PhysicsImpostor.MeshImpostor = 4;
  63935. PhysicsImpostor.CylinderImpostor = 7;
  63936. PhysicsImpostor.ParticleImpostor = 8;
  63937. PhysicsImpostor.HeightmapImpostor = 9;
  63938. return PhysicsImpostor;
  63939. }());
  63940. BABYLON.PhysicsImpostor = PhysicsImpostor;
  63941. })(BABYLON || (BABYLON = {}));
  63942. //# sourceMappingURL=babylon.physicsImpostor.js.map
  63943. var BABYLON;
  63944. (function (BABYLON) {
  63945. var PhysicsEngine = (function () {
  63946. function PhysicsEngine(gravity, _physicsPlugin) {
  63947. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  63948. this._physicsPlugin = _physicsPlugin;
  63949. //new methods and parameters
  63950. this._impostors = [];
  63951. this._joints = [];
  63952. if (!this._physicsPlugin.isSupported()) {
  63953. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  63954. + "Please make sure it is included.");
  63955. }
  63956. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  63957. this.setGravity(gravity);
  63958. this.setTimeStep();
  63959. }
  63960. PhysicsEngine.prototype.setGravity = function (gravity) {
  63961. this.gravity = gravity;
  63962. this._physicsPlugin.setGravity(this.gravity);
  63963. };
  63964. /**
  63965. * Set the time step of the physics engine.
  63966. * default is 1/60.
  63967. * To slow it down, enter 1/600 for example.
  63968. * To speed it up, 1/30
  63969. * @param {number} newTimeStep the new timestep to apply to this world.
  63970. */
  63971. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  63972. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  63973. this._physicsPlugin.setTimeStep(newTimeStep);
  63974. };
  63975. /**
  63976. * Get the time step of the physics engine.
  63977. */
  63978. PhysicsEngine.prototype.getTimeStep = function () {
  63979. return this._physicsPlugin.getTimeStep();
  63980. };
  63981. PhysicsEngine.prototype.dispose = function () {
  63982. this._impostors.forEach(function (impostor) {
  63983. impostor.dispose();
  63984. });
  63985. this._physicsPlugin.dispose();
  63986. };
  63987. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  63988. return this._physicsPlugin.name;
  63989. };
  63990. /**
  63991. * Adding a new impostor for the impostor tracking.
  63992. * This will be done by the impostor itself.
  63993. * @param {PhysicsImpostor} impostor the impostor to add
  63994. */
  63995. PhysicsEngine.prototype.addImpostor = function (impostor) {
  63996. impostor.uniqueId = this._impostors.push(impostor);
  63997. //if no parent, generate the body
  63998. if (!impostor.parent) {
  63999. this._physicsPlugin.generatePhysicsBody(impostor);
  64000. }
  64001. };
  64002. /**
  64003. * Remove an impostor from the engine.
  64004. * This impostor and its mesh will not longer be updated by the physics engine.
  64005. * @param {PhysicsImpostor} impostor the impostor to remove
  64006. */
  64007. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  64008. var index = this._impostors.indexOf(impostor);
  64009. if (index > -1) {
  64010. var removed = this._impostors.splice(index, 1);
  64011. //Is it needed?
  64012. if (removed.length) {
  64013. //this will also remove it from the world.
  64014. removed[0].physicsBody = null;
  64015. }
  64016. }
  64017. };
  64018. /**
  64019. * Add a joint to the physics engine
  64020. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  64021. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  64022. * @param {PhysicsJoint} the joint that will connect both impostors.
  64023. */
  64024. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  64025. var impostorJoint = {
  64026. mainImpostor: mainImpostor,
  64027. connectedImpostor: connectedImpostor,
  64028. joint: joint
  64029. };
  64030. joint.physicsPlugin = this._physicsPlugin;
  64031. this._joints.push(impostorJoint);
  64032. this._physicsPlugin.generateJoint(impostorJoint);
  64033. };
  64034. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  64035. var matchingJoints = this._joints.filter(function (impostorJoint) {
  64036. return (impostorJoint.connectedImpostor === connectedImpostor
  64037. && impostorJoint.joint === joint
  64038. && impostorJoint.mainImpostor === mainImpostor);
  64039. });
  64040. if (matchingJoints.length) {
  64041. this._physicsPlugin.removeJoint(matchingJoints[0]);
  64042. //TODO remove it from the list as well
  64043. }
  64044. };
  64045. /**
  64046. * Called by the scene. no need to call it.
  64047. */
  64048. PhysicsEngine.prototype._step = function (delta) {
  64049. var _this = this;
  64050. //check if any mesh has no body / requires an update
  64051. this._impostors.forEach(function (impostor) {
  64052. if (impostor.isBodyInitRequired()) {
  64053. _this._physicsPlugin.generatePhysicsBody(impostor);
  64054. }
  64055. });
  64056. if (delta > 0.1) {
  64057. delta = 0.1;
  64058. }
  64059. else if (delta <= 0) {
  64060. delta = 1.0 / 60.0;
  64061. }
  64062. this._physicsPlugin.executeStep(delta, this._impostors);
  64063. };
  64064. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  64065. return this._physicsPlugin;
  64066. };
  64067. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  64068. for (var i = 0; i < this._impostors.length; ++i) {
  64069. if (this._impostors[i].object === object) {
  64070. return this._impostors[i];
  64071. }
  64072. }
  64073. return null;
  64074. };
  64075. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  64076. for (var i = 0; i < this._impostors.length; ++i) {
  64077. if (this._impostors[i].physicsBody === body) {
  64078. return this._impostors[i];
  64079. }
  64080. }
  64081. return null;
  64082. };
  64083. // Statics
  64084. PhysicsEngine.Epsilon = 0.001;
  64085. return PhysicsEngine;
  64086. }());
  64087. BABYLON.PhysicsEngine = PhysicsEngine;
  64088. })(BABYLON || (BABYLON = {}));
  64089. //# sourceMappingURL=babylon.physicsEngine.js.map
  64090. var BABYLON;
  64091. (function (BABYLON) {
  64092. var CannonJSPlugin = (function () {
  64093. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  64094. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  64095. if (iterations === void 0) { iterations = 10; }
  64096. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  64097. this.name = "CannonJSPlugin";
  64098. this._physicsMaterials = new Array();
  64099. this._fixedTimeStep = 1 / 60;
  64100. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  64101. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : ( true ? __webpack_require__(7) : undefined);
  64102. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  64103. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  64104. this._tmpPosition = BABYLON.Vector3.Zero();
  64105. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  64106. this._tmpUnityRotation = new BABYLON.Quaternion();
  64107. if (!this.isSupported()) {
  64108. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  64109. return;
  64110. }
  64111. this.world = new this.BJSCANNON.World();
  64112. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  64113. this.world.solver.iterations = iterations;
  64114. }
  64115. CannonJSPlugin.prototype.setGravity = function (gravity) {
  64116. this.world.gravity.copy(gravity);
  64117. };
  64118. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  64119. this._fixedTimeStep = timeStep;
  64120. };
  64121. CannonJSPlugin.prototype.getTimeStep = function () {
  64122. return this._fixedTimeStep;
  64123. };
  64124. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  64125. // Delta is in seconds, should be provided in milliseconds
  64126. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  64127. };
  64128. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  64129. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  64130. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  64131. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  64132. };
  64133. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  64134. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  64135. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  64136. impostor.physicsBody.applyForce(impulse, worldPoint);
  64137. };
  64138. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  64139. //parent-child relationship. Does this impostor has a parent impostor?
  64140. if (impostor.parent) {
  64141. if (impostor.physicsBody) {
  64142. this.removePhysicsBody(impostor);
  64143. //TODO is that needed?
  64144. impostor.forceUpdate();
  64145. }
  64146. return;
  64147. }
  64148. //should a new body be created for this impostor?
  64149. if (impostor.isBodyInitRequired()) {
  64150. var shape = this._createShape(impostor);
  64151. //unregister events, if body is being changed
  64152. var oldBody = impostor.physicsBody;
  64153. if (oldBody) {
  64154. this.removePhysicsBody(impostor);
  64155. }
  64156. //create the body and material
  64157. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  64158. var bodyCreationObject = {
  64159. mass: impostor.getParam("mass"),
  64160. material: material
  64161. };
  64162. // A simple extend, in case native options were used.
  64163. var nativeOptions = impostor.getParam("nativeOptions");
  64164. for (var key in nativeOptions) {
  64165. if (nativeOptions.hasOwnProperty(key)) {
  64166. bodyCreationObject[key] = nativeOptions[key];
  64167. }
  64168. }
  64169. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  64170. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  64171. this.world.addEventListener("preStep", impostor.beforeStep);
  64172. this.world.addEventListener("postStep", impostor.afterStep);
  64173. impostor.physicsBody.addShape(shape);
  64174. this.world.add(impostor.physicsBody);
  64175. //try to keep the body moving in the right direction by taking old properties.
  64176. //Should be tested!
  64177. if (oldBody) {
  64178. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  64179. impostor.physicsBody[param].copy(oldBody[param]);
  64180. });
  64181. }
  64182. this._processChildMeshes(impostor);
  64183. }
  64184. //now update the body's transformation
  64185. this._updatePhysicsBodyTransformation(impostor);
  64186. };
  64187. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  64188. var _this = this;
  64189. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  64190. var currentRotation = mainImpostor.object.rotationQuaternion;
  64191. if (meshChildren.length) {
  64192. var processMesh = function (localPosition, mesh) {
  64193. var childImpostor = mesh.getPhysicsImpostor();
  64194. if (childImpostor) {
  64195. var parent = childImpostor.parent;
  64196. if (parent !== mainImpostor) {
  64197. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  64198. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  64199. if (childImpostor.physicsBody) {
  64200. _this.removePhysicsBody(childImpostor);
  64201. childImpostor.physicsBody = null;
  64202. }
  64203. childImpostor.parent = mainImpostor;
  64204. childImpostor.resetUpdateFlags();
  64205. 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));
  64206. //Add the mass of the children.
  64207. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  64208. }
  64209. }
  64210. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  64211. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  64212. };
  64213. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  64214. }
  64215. };
  64216. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  64217. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  64218. this.world.removeEventListener("preStep", impostor.beforeStep);
  64219. this.world.removeEventListener("postStep", impostor.afterStep);
  64220. this.world.remove(impostor.physicsBody);
  64221. };
  64222. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  64223. var mainBody = impostorJoint.mainImpostor.physicsBody;
  64224. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  64225. if (!mainBody || !connectedBody) {
  64226. return;
  64227. }
  64228. var constraint;
  64229. var jointData = impostorJoint.joint.jointData;
  64230. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  64231. var constraintData = {
  64232. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  64233. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  64234. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  64235. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  64236. maxForce: jointData.nativeParams.maxForce,
  64237. collideConnected: !!jointData.collision
  64238. };
  64239. switch (impostorJoint.joint.type) {
  64240. case BABYLON.PhysicsJoint.HingeJoint:
  64241. case BABYLON.PhysicsJoint.Hinge2Joint:
  64242. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  64243. break;
  64244. case BABYLON.PhysicsJoint.DistanceJoint:
  64245. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  64246. break;
  64247. case BABYLON.PhysicsJoint.SpringJoint:
  64248. var springData = jointData;
  64249. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  64250. restLength: springData.length,
  64251. stiffness: springData.stiffness,
  64252. damping: springData.damping,
  64253. localAnchorA: constraintData.pivotA,
  64254. localAnchorB: constraintData.pivotB
  64255. });
  64256. break;
  64257. case BABYLON.PhysicsJoint.LockJoint:
  64258. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  64259. break;
  64260. case BABYLON.PhysicsJoint.PointToPointJoint:
  64261. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  64262. default:
  64263. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  64264. break;
  64265. }
  64266. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  64267. constraint.collideConnected = !!jointData.collision;
  64268. impostorJoint.joint.physicsJoint = constraint;
  64269. //don't add spring as constraint, as it is not one.
  64270. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  64271. this.world.addConstraint(constraint);
  64272. }
  64273. else {
  64274. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  64275. constraint.applyForce();
  64276. });
  64277. }
  64278. };
  64279. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  64280. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  64281. };
  64282. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  64283. var index;
  64284. var mat;
  64285. for (index = 0; index < this._physicsMaterials.length; index++) {
  64286. mat = this._physicsMaterials[index];
  64287. if (mat.friction === friction && mat.restitution === restitution) {
  64288. return mat;
  64289. }
  64290. }
  64291. var currentMat = new this.BJSCANNON.Material(name);
  64292. currentMat.friction = friction;
  64293. currentMat.restitution = restitution;
  64294. this._physicsMaterials.push(currentMat);
  64295. return currentMat;
  64296. };
  64297. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  64298. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  64299. };
  64300. CannonJSPlugin.prototype._createShape = function (impostor) {
  64301. var object = impostor.object;
  64302. var returnValue;
  64303. var extendSize = impostor.getObjectExtendSize();
  64304. switch (impostor.type) {
  64305. case BABYLON.PhysicsImpostor.SphereImpostor:
  64306. var radiusX = extendSize.x;
  64307. var radiusY = extendSize.y;
  64308. var radiusZ = extendSize.z;
  64309. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  64310. break;
  64311. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  64312. case BABYLON.PhysicsImpostor.CylinderImpostor:
  64313. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  64314. break;
  64315. case BABYLON.PhysicsImpostor.BoxImpostor:
  64316. var box = extendSize.scale(0.5);
  64317. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  64318. break;
  64319. case BABYLON.PhysicsImpostor.PlaneImpostor:
  64320. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  64321. returnValue = new this.BJSCANNON.Plane();
  64322. break;
  64323. case BABYLON.PhysicsImpostor.MeshImpostor:
  64324. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  64325. var rawFaces = object.getIndices ? object.getIndices() : [];
  64326. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  64327. returnValue = new this.BJSCANNON.Trimesh(rawVerts, rawFaces);
  64328. break;
  64329. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  64330. returnValue = this._createHeightmap(object);
  64331. break;
  64332. case BABYLON.PhysicsImpostor.ParticleImpostor:
  64333. returnValue = new this.BJSCANNON.Particle();
  64334. break;
  64335. }
  64336. return returnValue;
  64337. };
  64338. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  64339. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64340. var matrix = new Array();
  64341. //For now pointDepth will not be used and will be automatically calculated.
  64342. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  64343. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  64344. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  64345. var elementSize = dim * 2 / arraySize;
  64346. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  64347. for (var i = 0; i < pos.length; i = i + 3) {
  64348. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  64349. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  64350. var y = pos[i + 1] + minY;
  64351. if (!matrix[x]) {
  64352. matrix[x] = [];
  64353. }
  64354. if (!matrix[x][z]) {
  64355. matrix[x][z] = y;
  64356. }
  64357. matrix[x][z] = Math.max(y, matrix[x][z]);
  64358. }
  64359. for (var x = 0; x <= arraySize; ++x) {
  64360. if (!matrix[x]) {
  64361. var loc = 1;
  64362. while (!matrix[(x + loc) % arraySize]) {
  64363. loc++;
  64364. }
  64365. matrix[x] = matrix[(x + loc) % arraySize].slice();
  64366. //console.log("missing x", x);
  64367. }
  64368. for (var z = 0; z <= arraySize; ++z) {
  64369. if (!matrix[x][z]) {
  64370. var loc = 1;
  64371. var newValue;
  64372. while (newValue === undefined) {
  64373. newValue = matrix[x][(z + loc++) % arraySize];
  64374. }
  64375. matrix[x][z] = newValue;
  64376. }
  64377. }
  64378. }
  64379. var shape = new this.BJSCANNON.Heightfield(matrix, {
  64380. elementSize: elementSize
  64381. });
  64382. //For future reference, needed for body transformation
  64383. shape.minY = minY;
  64384. return shape;
  64385. };
  64386. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  64387. var object = impostor.object;
  64388. //make sure it is updated...
  64389. object.computeWorldMatrix && object.computeWorldMatrix(true);
  64390. // The delta between the mesh position and the mesh bounding box center
  64391. var center = impostor.getObjectCenter();
  64392. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  64393. this._tmpPosition.copyFrom(center);
  64394. var quaternion = object.rotationQuaternion;
  64395. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  64396. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  64397. //-90 DEG in X, precalculated
  64398. quaternion = quaternion.multiply(this._minus90X);
  64399. //Invert! (Precalculated, 90 deg in X)
  64400. //No need to clone. this will never change.
  64401. impostor.setDeltaRotation(this._plus90X);
  64402. }
  64403. //If it is a heightfield, if should be centered.
  64404. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  64405. var mesh = object;
  64406. //calculate the correct body position:
  64407. var rotationQuaternion = mesh.rotationQuaternion;
  64408. mesh.rotationQuaternion = this._tmpUnityRotation;
  64409. mesh.computeWorldMatrix(true);
  64410. //get original center with no rotation
  64411. var c = center.clone();
  64412. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  64413. //rotation is back
  64414. mesh.rotationQuaternion = rotationQuaternion;
  64415. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  64416. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  64417. mesh.setPivotMatrix(p);
  64418. mesh.computeWorldMatrix(true);
  64419. //calculate the translation
  64420. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  64421. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  64422. //add it inverted to the delta
  64423. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  64424. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  64425. mesh.setPivotMatrix(oldPivot);
  64426. mesh.computeWorldMatrix(true);
  64427. }
  64428. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  64429. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  64430. this._tmpPosition.copyFrom(object.position);
  64431. }
  64432. impostor.setDeltaPosition(this._tmpDeltaPosition);
  64433. //Now update the impostor object
  64434. impostor.physicsBody.position.copy(this._tmpPosition);
  64435. impostor.physicsBody.quaternion.copy(quaternion);
  64436. };
  64437. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  64438. impostor.object.position.copyFrom(impostor.physicsBody.position);
  64439. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  64440. };
  64441. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  64442. impostor.physicsBody.position.copy(newPosition);
  64443. impostor.physicsBody.quaternion.copy(newRotation);
  64444. };
  64445. CannonJSPlugin.prototype.isSupported = function () {
  64446. return this.BJSCANNON !== undefined;
  64447. };
  64448. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  64449. impostor.physicsBody.velocity.copy(velocity);
  64450. };
  64451. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  64452. impostor.physicsBody.angularVelocity.copy(velocity);
  64453. };
  64454. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  64455. var v = impostor.physicsBody.velocity;
  64456. if (!v)
  64457. return null;
  64458. return new BABYLON.Vector3(v.x, v.y, v.z);
  64459. };
  64460. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  64461. var v = impostor.physicsBody.angularVelocity;
  64462. if (!v)
  64463. return null;
  64464. return new BABYLON.Vector3(v.x, v.y, v.z);
  64465. };
  64466. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  64467. impostor.physicsBody.mass = mass;
  64468. impostor.physicsBody.updateMassProperties();
  64469. };
  64470. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  64471. return impostor.physicsBody.mass;
  64472. };
  64473. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  64474. return impostor.physicsBody.material.friction;
  64475. };
  64476. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  64477. impostor.physicsBody.material.friction = friction;
  64478. };
  64479. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  64480. return impostor.physicsBody.material.restitution;
  64481. };
  64482. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  64483. impostor.physicsBody.material.restitution = restitution;
  64484. };
  64485. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  64486. impostor.physicsBody.sleep();
  64487. };
  64488. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  64489. impostor.physicsBody.wakeUp();
  64490. };
  64491. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  64492. joint.physicsJoint.distance = maxDistance;
  64493. };
  64494. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  64495. // if (!motorIndex) {
  64496. // joint.physicsJoint.enableMotor();
  64497. // }
  64498. // }
  64499. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  64500. // if (!motorIndex) {
  64501. // joint.physicsJoint.disableMotor();
  64502. // }
  64503. // }
  64504. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  64505. if (!motorIndex) {
  64506. joint.physicsJoint.enableMotor();
  64507. joint.physicsJoint.setMotorSpeed(speed);
  64508. if (maxForce) {
  64509. this.setLimit(joint, maxForce);
  64510. }
  64511. }
  64512. };
  64513. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  64514. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  64515. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  64516. };
  64517. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  64518. var body = impostor.physicsBody;
  64519. mesh.position.x = body.position.x;
  64520. mesh.position.y = body.position.y;
  64521. mesh.position.z = body.position.z;
  64522. mesh.rotationQuaternion.x = body.quaternion.x;
  64523. mesh.rotationQuaternion.y = body.quaternion.y;
  64524. mesh.rotationQuaternion.z = body.quaternion.z;
  64525. mesh.rotationQuaternion.w = body.quaternion.w;
  64526. };
  64527. CannonJSPlugin.prototype.getRadius = function (impostor) {
  64528. var shape = impostor.physicsBody.shapes[0];
  64529. return shape.boundingSphereRadius;
  64530. };
  64531. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  64532. var shape = impostor.physicsBody.shapes[0];
  64533. result.x = shape.halfExtents.x * 2;
  64534. result.y = shape.halfExtents.y * 2;
  64535. result.z = shape.halfExtents.z * 2;
  64536. };
  64537. CannonJSPlugin.prototype.dispose = function () {
  64538. };
  64539. return CannonJSPlugin;
  64540. }());
  64541. BABYLON.CannonJSPlugin = CannonJSPlugin;
  64542. })(BABYLON || (BABYLON = {}));
  64543. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  64544. var BABYLON;
  64545. (function (BABYLON) {
  64546. var OimoJSPlugin = (function () {
  64547. function OimoJSPlugin(iterations) {
  64548. this.name = "OimoJSPlugin";
  64549. this._tmpImpostorsArray = [];
  64550. this._tmpPositionVector = BABYLON.Vector3.Zero();
  64551. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : ( true ? __webpack_require__(8) : undefined);
  64552. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  64553. this.world.worldscale(1);
  64554. this.world.clear();
  64555. //making sure no stats are calculated
  64556. this.world.isNoStat = true;
  64557. }
  64558. OimoJSPlugin.prototype.setGravity = function (gravity) {
  64559. this.world.gravity.copy(gravity);
  64560. };
  64561. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  64562. this.world.timeStep = timeStep;
  64563. };
  64564. OimoJSPlugin.prototype.getTimeStep = function () {
  64565. return this.world.timeStep;
  64566. };
  64567. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  64568. var _this = this;
  64569. impostors.forEach(function (impostor) {
  64570. impostor.beforeStep();
  64571. });
  64572. this.world.step();
  64573. impostors.forEach(function (impostor) {
  64574. impostor.afterStep();
  64575. //update the ordered impostors array
  64576. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  64577. });
  64578. //check for collisions
  64579. var contact = this.world.contacts;
  64580. while (contact !== null) {
  64581. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  64582. contact = contact.next;
  64583. continue;
  64584. }
  64585. //is this body colliding with any other? get the impostor
  64586. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  64587. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  64588. if (!mainImpostor || !collidingImpostor) {
  64589. contact = contact.next;
  64590. continue;
  64591. }
  64592. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  64593. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  64594. contact = contact.next;
  64595. }
  64596. };
  64597. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  64598. var mass = impostor.physicsBody.massInfo.mass;
  64599. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  64600. };
  64601. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  64602. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  64603. this.applyImpulse(impostor, force, contactPoint);
  64604. };
  64605. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  64606. var _this = this;
  64607. //parent-child relationship. Does this impostor has a parent impostor?
  64608. if (impostor.parent) {
  64609. if (impostor.physicsBody) {
  64610. this.removePhysicsBody(impostor);
  64611. //TODO is that needed?
  64612. impostor.forceUpdate();
  64613. }
  64614. return;
  64615. }
  64616. if (impostor.isBodyInitRequired()) {
  64617. var bodyConfig = {
  64618. name: impostor.uniqueId,
  64619. //Oimo must have mass, also for static objects.
  64620. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  64621. size: [],
  64622. type: [],
  64623. pos: [],
  64624. rot: [],
  64625. move: impostor.getParam("mass") !== 0,
  64626. //Supporting older versions of Oimo
  64627. world: this.world
  64628. };
  64629. var impostors = [impostor];
  64630. var addToArray = function (parent) {
  64631. if (!parent.getChildMeshes)
  64632. return;
  64633. parent.getChildMeshes().forEach(function (m) {
  64634. if (m.physicsImpostor) {
  64635. impostors.push(m.physicsImpostor);
  64636. //m.physicsImpostor._init();
  64637. }
  64638. });
  64639. };
  64640. addToArray(impostor.object);
  64641. var checkWithEpsilon_1 = function (value) {
  64642. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  64643. };
  64644. impostors.forEach(function (i) {
  64645. //get the correct bounding box
  64646. var oldQuaternion = i.object.rotationQuaternion;
  64647. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  64648. x: impostor.object.rotationQuaternion.x,
  64649. y: impostor.object.rotationQuaternion.y,
  64650. z: impostor.object.rotationQuaternion.z,
  64651. s: impostor.object.rotationQuaternion.w
  64652. });
  64653. var extendSize = i.getObjectExtendSize();
  64654. if (i === impostor) {
  64655. var center = impostor.getObjectCenter();
  64656. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  64657. //Can also use Array.prototype.push.apply
  64658. bodyConfig.pos.push(center.x);
  64659. bodyConfig.pos.push(center.y);
  64660. bodyConfig.pos.push(center.z);
  64661. //tmp solution
  64662. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  64663. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  64664. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  64665. }
  64666. else {
  64667. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  64668. bodyConfig.pos.push(localPosition.x);
  64669. bodyConfig.pos.push(localPosition.y);
  64670. bodyConfig.pos.push(localPosition.z);
  64671. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  64672. bodyConfig.rot.push(0);
  64673. bodyConfig.rot.push(0);
  64674. bodyConfig.rot.push(0);
  64675. }
  64676. // register mesh
  64677. switch (i.type) {
  64678. case BABYLON.PhysicsImpostor.ParticleImpostor:
  64679. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  64680. case BABYLON.PhysicsImpostor.SphereImpostor:
  64681. var radiusX = extendSize.x;
  64682. var radiusY = extendSize.y;
  64683. var radiusZ = extendSize.z;
  64684. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  64685. bodyConfig.type.push('sphere');
  64686. //due to the way oimo works with compounds, add 3 times
  64687. bodyConfig.size.push(size);
  64688. bodyConfig.size.push(size);
  64689. bodyConfig.size.push(size);
  64690. break;
  64691. case BABYLON.PhysicsImpostor.CylinderImpostor:
  64692. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  64693. var sizeY = checkWithEpsilon_1(extendSize.y);
  64694. bodyConfig.type.push('cylinder');
  64695. bodyConfig.size.push(sizeX);
  64696. bodyConfig.size.push(sizeY);
  64697. //due to the way oimo works with compounds, add one more value.
  64698. bodyConfig.size.push(sizeY);
  64699. break;
  64700. case BABYLON.PhysicsImpostor.PlaneImpostor:
  64701. case BABYLON.PhysicsImpostor.BoxImpostor:
  64702. default:
  64703. var sizeX = checkWithEpsilon_1(extendSize.x);
  64704. var sizeY = checkWithEpsilon_1(extendSize.y);
  64705. var sizeZ = checkWithEpsilon_1(extendSize.z);
  64706. bodyConfig.type.push('box');
  64707. bodyConfig.size.push(sizeX);
  64708. bodyConfig.size.push(sizeY);
  64709. bodyConfig.size.push(sizeZ);
  64710. break;
  64711. }
  64712. //actually not needed, but hey...
  64713. i.object.rotationQuaternion = oldQuaternion;
  64714. });
  64715. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  64716. }
  64717. else {
  64718. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  64719. }
  64720. impostor.setDeltaPosition(this._tmpPositionVector);
  64721. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  64722. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  64723. };
  64724. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  64725. //impostor.physicsBody.dispose();
  64726. //Same as : (older oimo versions)
  64727. this.world.removeRigidBody(impostor.physicsBody);
  64728. };
  64729. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  64730. var mainBody = impostorJoint.mainImpostor.physicsBody;
  64731. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  64732. if (!mainBody || !connectedBody) {
  64733. return;
  64734. }
  64735. var jointData = impostorJoint.joint.jointData;
  64736. var options = jointData.nativeParams || {};
  64737. var type;
  64738. var nativeJointData = {
  64739. body1: mainBody,
  64740. body2: connectedBody,
  64741. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  64742. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  64743. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  64744. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  64745. min: options.min,
  64746. max: options.max,
  64747. collision: options.collision || jointData.collision,
  64748. spring: options.spring,
  64749. //supporting older version of Oimo
  64750. world: this.world
  64751. };
  64752. switch (impostorJoint.joint.type) {
  64753. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  64754. type = "jointBall";
  64755. break;
  64756. case BABYLON.PhysicsJoint.SpringJoint:
  64757. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  64758. var springData = jointData;
  64759. nativeJointData.min = springData.length || nativeJointData.min;
  64760. //Max should also be set, just make sure it is at least min
  64761. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  64762. case BABYLON.PhysicsJoint.DistanceJoint:
  64763. type = "jointDistance";
  64764. nativeJointData.max = jointData.maxDistance;
  64765. break;
  64766. case BABYLON.PhysicsJoint.PrismaticJoint:
  64767. type = "jointPrisme";
  64768. break;
  64769. case BABYLON.PhysicsJoint.SliderJoint:
  64770. type = "jointSlide";
  64771. break;
  64772. case BABYLON.PhysicsJoint.WheelJoint:
  64773. type = "jointWheel";
  64774. break;
  64775. case BABYLON.PhysicsJoint.HingeJoint:
  64776. default:
  64777. type = "jointHinge";
  64778. break;
  64779. }
  64780. nativeJointData.type = type;
  64781. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  64782. };
  64783. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  64784. //Bug in Oimo prevents us from disposing a joint in the playground
  64785. //joint.joint.physicsJoint.dispose();
  64786. //So we will bruteforce it!
  64787. try {
  64788. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  64789. }
  64790. catch (e) {
  64791. BABYLON.Tools.Warn(e);
  64792. }
  64793. };
  64794. OimoJSPlugin.prototype.isSupported = function () {
  64795. return this.BJSOIMO !== undefined;
  64796. };
  64797. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  64798. if (!impostor.physicsBody.sleeping) {
  64799. //TODO check that
  64800. if (impostor.physicsBody.shapes.next) {
  64801. var parentShape = this._getLastShape(impostor.physicsBody);
  64802. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  64803. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  64804. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  64805. }
  64806. else {
  64807. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  64808. }
  64809. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  64810. impostor.object.rotationQuaternion.normalize();
  64811. }
  64812. };
  64813. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  64814. var body = impostor.physicsBody;
  64815. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  64816. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  64817. body.syncShapes();
  64818. body.awake();
  64819. };
  64820. OimoJSPlugin.prototype._getLastShape = function (body) {
  64821. var lastShape = body.shapes;
  64822. while (lastShape.next) {
  64823. lastShape = lastShape.next;
  64824. }
  64825. return lastShape;
  64826. };
  64827. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  64828. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  64829. };
  64830. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  64831. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  64832. };
  64833. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  64834. var v = impostor.physicsBody.linearVelocity;
  64835. if (!v)
  64836. return null;
  64837. return new BABYLON.Vector3(v.x, v.y, v.z);
  64838. };
  64839. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  64840. var v = impostor.physicsBody.angularVelocity;
  64841. if (!v)
  64842. return null;
  64843. return new BABYLON.Vector3(v.x, v.y, v.z);
  64844. };
  64845. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  64846. var staticBody = mass === 0;
  64847. //this will actually set the body's density and not its mass.
  64848. //But this is how oimo treats the mass variable.
  64849. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  64850. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  64851. };
  64852. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  64853. return impostor.physicsBody.shapes.density;
  64854. };
  64855. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  64856. return impostor.physicsBody.shapes.friction;
  64857. };
  64858. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  64859. impostor.physicsBody.shapes.friction = friction;
  64860. };
  64861. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  64862. return impostor.physicsBody.shapes.restitution;
  64863. };
  64864. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  64865. impostor.physicsBody.shapes.restitution = restitution;
  64866. };
  64867. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  64868. impostor.physicsBody.sleep();
  64869. };
  64870. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  64871. impostor.physicsBody.awake();
  64872. };
  64873. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  64874. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  64875. if (minDistance !== void 0) {
  64876. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  64877. }
  64878. };
  64879. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  64880. //TODO separate rotational and transational motors.
  64881. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  64882. if (motor) {
  64883. motor.setMotor(speed, maxForce);
  64884. }
  64885. };
  64886. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  64887. //TODO separate rotational and transational motors.
  64888. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  64889. if (motor) {
  64890. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  64891. }
  64892. };
  64893. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  64894. var body = impostor.physicsBody;
  64895. mesh.position.x = body.position.x;
  64896. mesh.position.y = body.position.y;
  64897. mesh.position.z = body.position.z;
  64898. mesh.rotationQuaternion.x = body.orientation.x;
  64899. mesh.rotationQuaternion.y = body.orientation.y;
  64900. mesh.rotationQuaternion.z = body.orientation.z;
  64901. mesh.rotationQuaternion.w = body.orientation.s;
  64902. };
  64903. OimoJSPlugin.prototype.getRadius = function (impostor) {
  64904. return impostor.physicsBody.shapes.radius;
  64905. };
  64906. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  64907. var shape = impostor.physicsBody.shapes;
  64908. result.x = shape.halfWidth * 2;
  64909. result.y = shape.halfHeight * 2;
  64910. result.z = shape.halfDepth * 2;
  64911. };
  64912. OimoJSPlugin.prototype.dispose = function () {
  64913. this.world.clear();
  64914. };
  64915. return OimoJSPlugin;
  64916. }());
  64917. BABYLON.OimoJSPlugin = OimoJSPlugin;
  64918. })(BABYLON || (BABYLON = {}));
  64919. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  64920. var BABYLON;
  64921. (function (BABYLON) {
  64922. var Internals;
  64923. (function (Internals) {
  64924. /*
  64925. * Based on jsTGALoader - Javascript loader for TGA file
  64926. * By Vincent Thibault
  64927. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  64928. */
  64929. var TGATools = (function () {
  64930. function TGATools() {
  64931. }
  64932. TGATools.GetTGAHeader = function (data) {
  64933. var offset = 0;
  64934. var header = {
  64935. id_length: data[offset++],
  64936. colormap_type: data[offset++],
  64937. image_type: data[offset++],
  64938. colormap_index: data[offset++] | data[offset++] << 8,
  64939. colormap_length: data[offset++] | data[offset++] << 8,
  64940. colormap_size: data[offset++],
  64941. origin: [
  64942. data[offset++] | data[offset++] << 8,
  64943. data[offset++] | data[offset++] << 8
  64944. ],
  64945. width: data[offset++] | data[offset++] << 8,
  64946. height: data[offset++] | data[offset++] << 8,
  64947. pixel_size: data[offset++],
  64948. flags: data[offset++]
  64949. };
  64950. return header;
  64951. };
  64952. TGATools.UploadContent = function (gl, data) {
  64953. // Not enough data to contain header ?
  64954. if (data.length < 19) {
  64955. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  64956. return;
  64957. }
  64958. // Read Header
  64959. var offset = 18;
  64960. var header = TGATools.GetTGAHeader(data);
  64961. // Assume it's a valid Targa file.
  64962. if (header.id_length + offset > data.length) {
  64963. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  64964. return;
  64965. }
  64966. // Skip not needed data
  64967. offset += header.id_length;
  64968. var use_rle = false;
  64969. var use_pal = false;
  64970. var use_rgb = false;
  64971. var use_grey = false;
  64972. // Get some informations.
  64973. switch (header.image_type) {
  64974. case TGATools._TYPE_RLE_INDEXED:
  64975. use_rle = true;
  64976. case TGATools._TYPE_INDEXED:
  64977. use_pal = true;
  64978. break;
  64979. case TGATools._TYPE_RLE_RGB:
  64980. use_rle = true;
  64981. case TGATools._TYPE_RGB:
  64982. use_rgb = true;
  64983. break;
  64984. case TGATools._TYPE_RLE_GREY:
  64985. use_rle = true;
  64986. case TGATools._TYPE_GREY:
  64987. use_grey = true;
  64988. break;
  64989. }
  64990. var pixel_data;
  64991. // var numAlphaBits = header.flags & 0xf;
  64992. var pixel_size = header.pixel_size >> 3;
  64993. var pixel_total = header.width * header.height * pixel_size;
  64994. // Read palettes
  64995. var palettes;
  64996. if (use_pal) {
  64997. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  64998. }
  64999. // Read LRE
  65000. if (use_rle) {
  65001. pixel_data = new Uint8Array(pixel_total);
  65002. var c, count, i;
  65003. var localOffset = 0;
  65004. var pixels = new Uint8Array(pixel_size);
  65005. while (offset < pixel_total && localOffset < pixel_total) {
  65006. c = data[offset++];
  65007. count = (c & 0x7f) + 1;
  65008. // RLE pixels
  65009. if (c & 0x80) {
  65010. // Bind pixel tmp array
  65011. for (i = 0; i < pixel_size; ++i) {
  65012. pixels[i] = data[offset++];
  65013. }
  65014. // Copy pixel array
  65015. for (i = 0; i < count; ++i) {
  65016. pixel_data.set(pixels, localOffset + i * pixel_size);
  65017. }
  65018. localOffset += pixel_size * count;
  65019. }
  65020. else {
  65021. count *= pixel_size;
  65022. for (i = 0; i < count; ++i) {
  65023. pixel_data[localOffset + i] = data[offset++];
  65024. }
  65025. localOffset += count;
  65026. }
  65027. }
  65028. }
  65029. else {
  65030. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  65031. }
  65032. // Load to texture
  65033. var x_start, y_start, x_step, y_step, y_end, x_end;
  65034. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  65035. default:
  65036. case TGATools._ORIGIN_UL:
  65037. x_start = 0;
  65038. x_step = 1;
  65039. x_end = header.width;
  65040. y_start = 0;
  65041. y_step = 1;
  65042. y_end = header.height;
  65043. break;
  65044. case TGATools._ORIGIN_BL:
  65045. x_start = 0;
  65046. x_step = 1;
  65047. x_end = header.width;
  65048. y_start = header.height - 1;
  65049. y_step = -1;
  65050. y_end = -1;
  65051. break;
  65052. case TGATools._ORIGIN_UR:
  65053. x_start = header.width - 1;
  65054. x_step = -1;
  65055. x_end = -1;
  65056. y_start = 0;
  65057. y_step = 1;
  65058. y_end = header.height;
  65059. break;
  65060. case TGATools._ORIGIN_BR:
  65061. x_start = header.width - 1;
  65062. x_step = -1;
  65063. x_end = -1;
  65064. y_start = header.height - 1;
  65065. y_step = -1;
  65066. y_end = -1;
  65067. break;
  65068. }
  65069. // Load the specify method
  65070. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  65071. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  65072. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  65073. };
  65074. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  65075. var image = pixel_data, colormap = palettes;
  65076. var width = header.width, height = header.height;
  65077. var color, i = 0, x, y;
  65078. var imageData = new Uint8Array(width * height * 4);
  65079. for (y = y_start; y !== y_end; y += y_step) {
  65080. for (x = x_start; x !== x_end; x += x_step, i++) {
  65081. color = image[i];
  65082. imageData[(x + width * y) * 4 + 3] = 255;
  65083. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  65084. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  65085. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  65086. }
  65087. }
  65088. return imageData;
  65089. };
  65090. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  65091. var image = pixel_data;
  65092. var width = header.width, height = header.height;
  65093. var color, i = 0, x, y;
  65094. var imageData = new Uint8Array(width * height * 4);
  65095. for (y = y_start; y !== y_end; y += y_step) {
  65096. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  65097. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  65098. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  65099. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  65100. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  65101. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  65102. }
  65103. }
  65104. return imageData;
  65105. };
  65106. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  65107. var image = pixel_data;
  65108. var width = header.width, height = header.height;
  65109. var i = 0, x, y;
  65110. var imageData = new Uint8Array(width * height * 4);
  65111. for (y = y_start; y !== y_end; y += y_step) {
  65112. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  65113. imageData[(x + width * y) * 4 + 3] = 255;
  65114. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  65115. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  65116. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  65117. }
  65118. }
  65119. return imageData;
  65120. };
  65121. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  65122. var image = pixel_data;
  65123. var width = header.width, height = header.height;
  65124. var i = 0, x, y;
  65125. var imageData = new Uint8Array(width * height * 4);
  65126. for (y = y_start; y !== y_end; y += y_step) {
  65127. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  65128. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  65129. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  65130. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  65131. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  65132. }
  65133. }
  65134. return imageData;
  65135. };
  65136. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  65137. var image = pixel_data;
  65138. var width = header.width, height = header.height;
  65139. var color, i = 0, x, y;
  65140. var imageData = new Uint8Array(width * height * 4);
  65141. for (y = y_start; y !== y_end; y += y_step) {
  65142. for (x = x_start; x !== x_end; x += x_step, i++) {
  65143. color = image[i];
  65144. imageData[(x + width * y) * 4 + 0] = color;
  65145. imageData[(x + width * y) * 4 + 1] = color;
  65146. imageData[(x + width * y) * 4 + 2] = color;
  65147. imageData[(x + width * y) * 4 + 3] = 255;
  65148. }
  65149. }
  65150. return imageData;
  65151. };
  65152. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  65153. var image = pixel_data;
  65154. var width = header.width, height = header.height;
  65155. var i = 0, x, y;
  65156. var imageData = new Uint8Array(width * height * 4);
  65157. for (y = y_start; y !== y_end; y += y_step) {
  65158. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  65159. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  65160. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  65161. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  65162. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  65163. }
  65164. }
  65165. return imageData;
  65166. };
  65167. //private static _TYPE_NO_DATA = 0;
  65168. TGATools._TYPE_INDEXED = 1;
  65169. TGATools._TYPE_RGB = 2;
  65170. TGATools._TYPE_GREY = 3;
  65171. TGATools._TYPE_RLE_INDEXED = 9;
  65172. TGATools._TYPE_RLE_RGB = 10;
  65173. TGATools._TYPE_RLE_GREY = 11;
  65174. TGATools._ORIGIN_MASK = 0x30;
  65175. TGATools._ORIGIN_SHIFT = 0x04;
  65176. TGATools._ORIGIN_BL = 0x00;
  65177. TGATools._ORIGIN_BR = 0x01;
  65178. TGATools._ORIGIN_UL = 0x02;
  65179. TGATools._ORIGIN_UR = 0x03;
  65180. return TGATools;
  65181. }());
  65182. Internals.TGATools = TGATools;
  65183. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  65184. })(BABYLON || (BABYLON = {}));
  65185. //# sourceMappingURL=babylon.tga.js.map
  65186. var BABYLON;
  65187. (function (BABYLON) {
  65188. var Internals;
  65189. (function (Internals) {
  65190. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  65191. // All values and structures referenced from:
  65192. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  65193. var DDS_MAGIC = 0x20534444;
  65194. var
  65195. //DDSD_CAPS = 0x1,
  65196. //DDSD_HEIGHT = 0x2,
  65197. //DDSD_WIDTH = 0x4,
  65198. //DDSD_PITCH = 0x8,
  65199. //DDSD_PIXELFORMAT = 0x1000,
  65200. DDSD_MIPMAPCOUNT = 0x20000;
  65201. //DDSD_LINEARSIZE = 0x80000,
  65202. //DDSD_DEPTH = 0x800000;
  65203. // var DDSCAPS_COMPLEX = 0x8,
  65204. // DDSCAPS_MIPMAP = 0x400000,
  65205. // DDSCAPS_TEXTURE = 0x1000;
  65206. var DDSCAPS2_CUBEMAP = 0x200;
  65207. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  65208. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  65209. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  65210. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  65211. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  65212. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  65213. // DDSCAPS2_VOLUME = 0x200000;
  65214. var
  65215. //DDPF_ALPHAPIXELS = 0x1,
  65216. //DDPF_ALPHA = 0x2,
  65217. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  65218. //DDPF_YUV = 0x200,
  65219. DDPF_LUMINANCE = 0x20000;
  65220. function FourCCToInt32(value) {
  65221. return value.charCodeAt(0) +
  65222. (value.charCodeAt(1) << 8) +
  65223. (value.charCodeAt(2) << 16) +
  65224. (value.charCodeAt(3) << 24);
  65225. }
  65226. function Int32ToFourCC(value) {
  65227. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  65228. }
  65229. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  65230. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  65231. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  65232. var FOURCC_DX10 = FourCCToInt32("DX10");
  65233. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  65234. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  65235. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  65236. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  65237. var headerLengthInt = 31; // The header length in 32 bit ints
  65238. // Offsets into the header array
  65239. var off_magic = 0;
  65240. var off_size = 1;
  65241. var off_flags = 2;
  65242. var off_height = 3;
  65243. var off_width = 4;
  65244. var off_mipmapCount = 7;
  65245. var off_pfFlags = 20;
  65246. var off_pfFourCC = 21;
  65247. var off_RGBbpp = 22;
  65248. // var off_RMask = 23;
  65249. // var off_GMask = 24;
  65250. // var off_BMask = 25;
  65251. // var off_AMask = 26;
  65252. // var off_caps1 = 27;
  65253. var off_caps2 = 28;
  65254. // var off_caps3 = 29;
  65255. // var off_caps4 = 30;
  65256. var off_dxgiFormat = 32;
  65257. ;
  65258. var DDSTools = (function () {
  65259. function DDSTools() {
  65260. }
  65261. DDSTools.GetDDSInfo = function (arrayBuffer) {
  65262. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  65263. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  65264. var mipmapCount = 1;
  65265. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  65266. mipmapCount = Math.max(1, header[off_mipmapCount]);
  65267. }
  65268. var fourCC = header[off_pfFourCC];
  65269. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  65270. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65271. switch (fourCC) {
  65272. case FOURCC_D3DFMT_R16G16B16A16F:
  65273. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65274. break;
  65275. case FOURCC_D3DFMT_R32G32B32A32F:
  65276. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65277. break;
  65278. case FOURCC_DX10:
  65279. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  65280. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65281. break;
  65282. }
  65283. }
  65284. return {
  65285. width: header[off_width],
  65286. height: header[off_height],
  65287. mipmapCount: mipmapCount,
  65288. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  65289. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  65290. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  65291. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  65292. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  65293. dxgiFormat: dxgiFormat,
  65294. textureType: textureType
  65295. };
  65296. };
  65297. DDSTools._ToHalfFloat = function (value) {
  65298. if (!DDSTools._FloatView) {
  65299. DDSTools._FloatView = new Float32Array(1);
  65300. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  65301. }
  65302. DDSTools._FloatView[0] = value;
  65303. var x = DDSTools._Int32View[0];
  65304. var bits = (x >> 16) & 0x8000; /* Get the sign */
  65305. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  65306. var e = (x >> 23) & 0xff; /* Using int is faster here */
  65307. /* If zero, or denormal, or exponent underflows too much for a denormal
  65308. * half, return signed zero. */
  65309. if (e < 103) {
  65310. return bits;
  65311. }
  65312. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  65313. if (e > 142) {
  65314. bits |= 0x7c00;
  65315. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  65316. * not Inf, so make sure we set one mantissa bit too. */
  65317. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  65318. return bits;
  65319. }
  65320. /* If exponent underflows but not too much, return a denormal */
  65321. if (e < 113) {
  65322. m |= 0x0800;
  65323. /* Extra rounding may overflow and set mantissa to 0 and exponent
  65324. * to 1, which is OK. */
  65325. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  65326. return bits;
  65327. }
  65328. bits |= ((e - 112) << 10) | (m >> 1);
  65329. bits += m & 1;
  65330. return bits;
  65331. };
  65332. DDSTools._FromHalfFloat = function (value) {
  65333. var s = (value & 0x8000) >> 15;
  65334. var e = (value & 0x7C00) >> 10;
  65335. var f = value & 0x03FF;
  65336. if (e === 0) {
  65337. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  65338. }
  65339. else if (e == 0x1F) {
  65340. return f ? NaN : ((s ? -1 : 1) * Infinity);
  65341. }
  65342. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  65343. };
  65344. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  65345. var destArray = new Float32Array(dataLength);
  65346. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  65347. var index = 0;
  65348. for (var y = 0; y < height; y++) {
  65349. for (var x = 0; x < width; x++) {
  65350. var srcPos = (x + y * width) * 4;
  65351. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  65352. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  65353. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  65354. if (DDSTools.StoreLODInAlphaChannel) {
  65355. destArray[index + 3] = lod;
  65356. }
  65357. else {
  65358. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  65359. }
  65360. index += 4;
  65361. }
  65362. }
  65363. return destArray;
  65364. };
  65365. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  65366. if (DDSTools.StoreLODInAlphaChannel) {
  65367. var destArray = new Uint16Array(dataLength);
  65368. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  65369. var index = 0;
  65370. for (var y = 0; y < height; y++) {
  65371. for (var x = 0; x < width; x++) {
  65372. var srcPos = (x + y * width) * 4;
  65373. destArray[index] = srcData[srcPos];
  65374. destArray[index + 1] = srcData[srcPos + 1];
  65375. destArray[index + 2] = srcData[srcPos + 2];
  65376. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  65377. index += 4;
  65378. }
  65379. }
  65380. return destArray;
  65381. }
  65382. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  65383. };
  65384. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  65385. if (DDSTools.StoreLODInAlphaChannel) {
  65386. var destArray = new Float32Array(dataLength);
  65387. var srcData = new Float32Array(arrayBuffer, dataOffset);
  65388. var index = 0;
  65389. for (var y = 0; y < height; y++) {
  65390. for (var x = 0; x < width; x++) {
  65391. var srcPos = (x + y * width) * 4;
  65392. destArray[index] = srcData[srcPos];
  65393. destArray[index + 1] = srcData[srcPos + 1];
  65394. destArray[index + 2] = srcData[srcPos + 2];
  65395. destArray[index + 3] = lod;
  65396. index += 4;
  65397. }
  65398. }
  65399. return destArray;
  65400. }
  65401. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  65402. };
  65403. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  65404. var destArray = new Uint8Array(dataLength);
  65405. var srcData = new Float32Array(arrayBuffer, dataOffset);
  65406. var index = 0;
  65407. for (var y = 0; y < height; y++) {
  65408. for (var x = 0; x < width; x++) {
  65409. var srcPos = (x + y * width) * 4;
  65410. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  65411. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  65412. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  65413. if (DDSTools.StoreLODInAlphaChannel) {
  65414. destArray[index + 3] = lod;
  65415. }
  65416. else {
  65417. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  65418. }
  65419. index += 4;
  65420. }
  65421. }
  65422. return destArray;
  65423. };
  65424. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  65425. var destArray = new Uint8Array(dataLength);
  65426. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  65427. var index = 0;
  65428. for (var y = 0; y < height; y++) {
  65429. for (var x = 0; x < width; x++) {
  65430. var srcPos = (x + y * width) * 4;
  65431. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  65432. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  65433. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  65434. if (DDSTools.StoreLODInAlphaChannel) {
  65435. destArray[index + 3] = lod;
  65436. }
  65437. else {
  65438. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  65439. }
  65440. index += 4;
  65441. }
  65442. }
  65443. return destArray;
  65444. };
  65445. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  65446. var byteArray = new Uint8Array(dataLength);
  65447. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  65448. var index = 0;
  65449. for (var y = 0; y < height; y++) {
  65450. for (var x = 0; x < width; x++) {
  65451. var srcPos = (x + y * width) * 4;
  65452. byteArray[index] = srcData[srcPos + 2];
  65453. byteArray[index + 1] = srcData[srcPos + 1];
  65454. byteArray[index + 2] = srcData[srcPos];
  65455. byteArray[index + 3] = srcData[srcPos + 3];
  65456. index += 4;
  65457. }
  65458. }
  65459. return byteArray;
  65460. };
  65461. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  65462. var byteArray = new Uint8Array(dataLength);
  65463. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  65464. var index = 0;
  65465. for (var y = 0; y < height; y++) {
  65466. for (var x = 0; x < width; x++) {
  65467. var srcPos = (x + y * width) * 3;
  65468. byteArray[index] = srcData[srcPos + 2];
  65469. byteArray[index + 1] = srcData[srcPos + 1];
  65470. byteArray[index + 2] = srcData[srcPos];
  65471. index += 3;
  65472. }
  65473. }
  65474. return byteArray;
  65475. };
  65476. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  65477. var byteArray = new Uint8Array(dataLength);
  65478. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  65479. var index = 0;
  65480. for (var y = 0; y < height; y++) {
  65481. for (var x = 0; x < width; x++) {
  65482. var srcPos = (x + y * width);
  65483. byteArray[index] = srcData[srcPos];
  65484. index++;
  65485. }
  65486. }
  65487. return byteArray;
  65488. };
  65489. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  65490. if (lodIndex === void 0) { lodIndex = -1; }
  65491. var ext = engine.getCaps().s3tc;
  65492. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  65493. if (header[off_magic] != DDS_MAGIC) {
  65494. BABYLON.Tools.Error("Invalid magic number in DDS header");
  65495. return;
  65496. }
  65497. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  65498. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  65499. return;
  65500. }
  65501. if (info.isCompressed && !ext) {
  65502. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  65503. return;
  65504. }
  65505. var bpp = header[off_RGBbpp];
  65506. dataOffset = header[off_size] + 4;
  65507. var computeFormats = false;
  65508. if (info.isFourCC) {
  65509. fourCC = header[off_pfFourCC];
  65510. switch (fourCC) {
  65511. case FOURCC_DXT1:
  65512. blockBytes = 8;
  65513. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  65514. break;
  65515. case FOURCC_DXT3:
  65516. blockBytes = 16;
  65517. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  65518. break;
  65519. case FOURCC_DXT5:
  65520. blockBytes = 16;
  65521. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  65522. break;
  65523. case FOURCC_D3DFMT_R16G16B16A16F:
  65524. computeFormats = true;
  65525. break;
  65526. case FOURCC_D3DFMT_R32G32B32A32F:
  65527. computeFormats = true;
  65528. break;
  65529. case FOURCC_DX10:
  65530. // There is an additionnal header so dataOffset need to be changed
  65531. dataOffset += 5 * 4; // 5 uints
  65532. var supported = false;
  65533. switch (info.dxgiFormat) {
  65534. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  65535. computeFormats = true;
  65536. supported = true;
  65537. break;
  65538. case DXGI_FORMAT_B8G8R8X8_UNORM:
  65539. info.isRGB = true;
  65540. info.isFourCC = false;
  65541. bpp = 32;
  65542. supported = true;
  65543. break;
  65544. }
  65545. if (supported) {
  65546. break;
  65547. }
  65548. default:
  65549. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  65550. return;
  65551. }
  65552. }
  65553. if (computeFormats) {
  65554. format = engine._getWebGLTextureType(info.textureType);
  65555. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  65556. }
  65557. mipmapCount = 1;
  65558. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  65559. mipmapCount = Math.max(1, header[off_mipmapCount]);
  65560. }
  65561. for (var face = 0; face < faces; face++) {
  65562. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  65563. width = header[off_width];
  65564. height = header[off_height];
  65565. for (mip = 0; mip < mipmapCount; ++mip) {
  65566. if (lodIndex === -1 || lodIndex === mip) {
  65567. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  65568. var i = (lodIndex === -1) ? mip : 0;
  65569. if (!info.isCompressed && info.isFourCC) {
  65570. dataLength = width * height * 4;
  65571. var floatArray;
  65572. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  65573. if (bpp === 128) {
  65574. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  65575. }
  65576. else if (bpp === 64) {
  65577. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  65578. }
  65579. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65580. format = engine._getWebGLTextureType(info.textureType);
  65581. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  65582. }
  65583. else {
  65584. if (bpp === 128) {
  65585. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  65586. }
  65587. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  65588. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  65589. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65590. format = engine._getWebGLTextureType(info.textureType);
  65591. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  65592. }
  65593. else {
  65594. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  65595. }
  65596. }
  65597. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  65598. }
  65599. else if (info.isRGB) {
  65600. if (bpp === 24) {
  65601. dataLength = width * height * 3;
  65602. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  65603. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  65604. }
  65605. else {
  65606. dataLength = width * height * 4;
  65607. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  65608. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  65609. }
  65610. }
  65611. else if (info.isLuminance) {
  65612. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  65613. var unpaddedRowSize = width;
  65614. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  65615. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  65616. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  65617. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  65618. }
  65619. else {
  65620. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  65621. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  65622. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  65623. }
  65624. }
  65625. dataOffset += width * height * (bpp / 8);
  65626. width *= 0.5;
  65627. height *= 0.5;
  65628. width = Math.max(1.0, width);
  65629. height = Math.max(1.0, height);
  65630. }
  65631. }
  65632. };
  65633. DDSTools.StoreLODInAlphaChannel = false;
  65634. return DDSTools;
  65635. }());
  65636. Internals.DDSTools = DDSTools;
  65637. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  65638. })(BABYLON || (BABYLON = {}));
  65639. //# sourceMappingURL=babylon.dds.js.map
  65640. var BABYLON;
  65641. (function (BABYLON) {
  65642. var Internals;
  65643. (function (Internals) {
  65644. /**
  65645. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  65646. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  65647. */
  65648. var KhronosTextureContainer = (function () {
  65649. /**
  65650. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  65651. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  65652. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  65653. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  65654. */
  65655. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  65656. this.arrayBuffer = arrayBuffer;
  65657. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  65658. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  65659. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  65660. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  65661. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  65662. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  65663. BABYLON.Tools.Error("texture missing KTX identifier");
  65664. return;
  65665. }
  65666. // load the reset of the header in native 32 bit int
  65667. var header = new Int32Array(this.arrayBuffer, 12, 13);
  65668. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  65669. var oppositeEndianess = header[0] === 0x01020304;
  65670. // read all the header elements in order they exist in the file, without modification (sans endainness)
  65671. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  65672. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  65673. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  65674. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  65675. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  65676. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  65677. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  65678. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  65679. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  65680. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  65681. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  65682. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  65683. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  65684. if (this.glType !== 0) {
  65685. BABYLON.Tools.Error("only compressed formats currently supported");
  65686. return;
  65687. }
  65688. else {
  65689. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  65690. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  65691. }
  65692. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  65693. BABYLON.Tools.Error("only 2D textures currently supported");
  65694. return;
  65695. }
  65696. if (this.numberOfArrayElements !== 0) {
  65697. BABYLON.Tools.Error("texture arrays not currently supported");
  65698. return;
  65699. }
  65700. if (this.numberOfFaces !== facesExpected) {
  65701. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  65702. return;
  65703. }
  65704. // we now have a completely validated file, so could use existence of loadType as success
  65705. // would need to make this more elaborate & adjust checks above to support more than one load type
  65706. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  65707. }
  65708. // not as fast hardware based, but will probably never need to use
  65709. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  65710. return ((val & 0xFF) << 24)
  65711. | ((val & 0xFF00) << 8)
  65712. | ((val >> 8) & 0xFF00)
  65713. | ((val >> 24) & 0xFF);
  65714. };
  65715. /**
  65716. * It is assumed that the texture has already been created & is currently bound
  65717. */
  65718. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  65719. switch (this.loadType) {
  65720. case KhronosTextureContainer.COMPRESSED_2D:
  65721. this._upload2DCompressedLevels(gl, loadMipmaps);
  65722. break;
  65723. case KhronosTextureContainer.TEX_2D:
  65724. case KhronosTextureContainer.COMPRESSED_3D:
  65725. case KhronosTextureContainer.TEX_3D:
  65726. }
  65727. };
  65728. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  65729. // initialize width & height for level 1
  65730. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  65731. var width = this.pixelWidth;
  65732. var height = this.pixelHeight;
  65733. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  65734. for (var level = 0; level < mipmapCount; level++) {
  65735. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  65736. for (var face = 0; face < this.numberOfFaces; face++) {
  65737. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  65738. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  65739. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  65740. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  65741. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  65742. }
  65743. width = Math.max(1.0, width * 0.5);
  65744. height = Math.max(1.0, height * 0.5);
  65745. }
  65746. };
  65747. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  65748. // load types
  65749. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  65750. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  65751. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  65752. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  65753. return KhronosTextureContainer;
  65754. }());
  65755. Internals.KhronosTextureContainer = KhronosTextureContainer;
  65756. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  65757. })(BABYLON || (BABYLON = {}));
  65758. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  65759. var BABYLON;
  65760. (function (BABYLON) {
  65761. var DynamicFloatArrayElementInfo = (function () {
  65762. function DynamicFloatArrayElementInfo() {
  65763. }
  65764. return DynamicFloatArrayElementInfo;
  65765. }());
  65766. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  65767. /**
  65768. * The purpose of this class is to store float32 based elements of a given size (defined by the stride argument) in a dynamic fashion, that is, you can add/free elements. You can then access to a defragmented/packed version of the underlying Float32Array by calling the pack() method.
  65769. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  65770. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  65771. * Allocating an Element will return a instance of DynamicFloatArrayElement which contains the offset into the Float32Array of where the element starts, you are then responsible to copy your data using this offset.
  65772. * Beware, calling pack() may change the offset of some Entries because this method will defragment the Float32Array to replace empty elements by moving allocated ones at their location.
  65773. * This method will return an ArrayBufferView on the existing Float32Array that describes the used elements. Use this View to update the WebGLBuffer and NOT the "buffer" field of the class. The pack() method won't shrink/reallocate the buffer to keep it GC friendly, all the empty space will be put at the end of the buffer, the method just ensure there are no "free holes".
  65774. */
  65775. var DynamicFloatArray = (function () {
  65776. /**
  65777. * Construct an instance of the dynamic float array
  65778. * @param stride size of one element in float (i.e. not bytes!)
  65779. * @param initialElementCount the number of available entries at construction
  65780. */
  65781. function DynamicFloatArray(stride, initialElementCount) {
  65782. this.compareValueOffset = null;
  65783. this.sortingAscending = true;
  65784. this._stride = stride;
  65785. this.buffer = new Float32Array(stride * initialElementCount);
  65786. this._lastUsed = 0;
  65787. this._firstFree = 0;
  65788. this._allEntries = new Array(initialElementCount);
  65789. this._freeEntries = new Array(initialElementCount);
  65790. for (var i = 0; i < initialElementCount; i++) {
  65791. var element = new DynamicFloatArrayElementInfo();
  65792. element.offset = i * stride;
  65793. this._allEntries[i] = element;
  65794. this._freeEntries[initialElementCount - i - 1] = element;
  65795. }
  65796. }
  65797. /**
  65798. * Allocate an element in the array.
  65799. * @return the element info instance that contains the offset into the main buffer of the element's location.
  65800. * Beware, this offset may change when you call pack()
  65801. */
  65802. DynamicFloatArray.prototype.allocElement = function () {
  65803. if (this._freeEntries.length === 0) {
  65804. this._growBuffer();
  65805. }
  65806. var el = this._freeEntries.pop();
  65807. this._lastUsed = Math.max(el.offset, this._lastUsed);
  65808. if (el.offset === this._firstFree) {
  65809. if (this._freeEntries.length > 0) {
  65810. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  65811. }
  65812. else {
  65813. this._firstFree += this._stride;
  65814. }
  65815. }
  65816. return el;
  65817. };
  65818. /**
  65819. * Free the element corresponding to the given element info
  65820. * @param elInfo the element that describe the allocated element
  65821. */
  65822. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  65823. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  65824. this._freeEntries.push(elInfo);
  65825. };
  65826. /**
  65827. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  65828. * Instances of DynamicFloatArrayElement may have their 'offset' member changed as data could be copied from one location to another, so be sure to read/write your data based on the value inside this member after you called pack().
  65829. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  65830. */
  65831. DynamicFloatArray.prototype.pack = function () {
  65832. // no free slot? no need to pack
  65833. if (this._freeEntries.length === 0) {
  65834. return this.buffer;
  65835. }
  65836. // If the buffer is already packed the last used will always be lower than the first free
  65837. // The opposite may not be true, we can have a lastUsed greater than firstFree but the array still packed, because when an element is freed, lastUsed is not updated (for speed reason) so we may have a lastUsed of a freed element. But that's ok, well soon realize this case.
  65838. if (this._lastUsed < this._firstFree) {
  65839. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  65840. return elementsBuffer_1;
  65841. }
  65842. var s = this._stride;
  65843. // Make sure there's a free element at the very end, we need it to create a range where we'll move the used elements that may appear before
  65844. var lastFree = new DynamicFloatArrayElementInfo();
  65845. lastFree.offset = this.totalElementCount * s;
  65846. this._freeEntries.push(lastFree);
  65847. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  65848. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  65849. var firstFreeSlotOffset = sortedFree[0].offset;
  65850. var freeZoneSize = 1;
  65851. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  65852. var prevOffset = sortedFree[0].offset;
  65853. for (var i = 1; i < sortedFree.length; i++) {
  65854. // If the first free (which means everything before is occupied) is greater or equal the occupied zone size, it means everything is defragmented, we can quit
  65855. if (firstFreeSlotOffset >= occupiedZoneSize) {
  65856. break;
  65857. }
  65858. var curFree = sortedFree[i];
  65859. var curOffset = curFree.offset;
  65860. // Compute the distance between this offset and the previous
  65861. var distance = curOffset - prevOffset;
  65862. // If the distance is the stride size, they are adjacent, it good, move to the next
  65863. if (distance === s) {
  65864. // Free zone is one element bigger
  65865. ++freeZoneSize;
  65866. // as we're about to iterate to the next, the cur becomes the previous...
  65867. prevOffset = curOffset;
  65868. continue;
  65869. }
  65870. // Distance is bigger, which means there's x element between the previous free and this one
  65871. var usedRange = (distance / s) - 1;
  65872. // Two cases the free zone is smaller than the data to move or bigger
  65873. // Copy what can fit in the free zone
  65874. var curMoveOffset = curOffset - s;
  65875. var copyCount = Math.min(freeZoneSize, usedRange);
  65876. for (var j = 0; j < copyCount; j++) {
  65877. var freeI = firstFreeSlotOffset / s;
  65878. var curI = curMoveOffset / s;
  65879. var moveEl = sortedAll[curI];
  65880. this._moveElement(moveEl, firstFreeSlotOffset);
  65881. var replacedEl = sortedAll[freeI];
  65882. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  65883. replacedEl.offset = curMoveOffset;
  65884. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  65885. sortedAll[freeI] = moveEl;
  65886. sortedAll[curI] = replacedEl;
  65887. curMoveOffset -= s;
  65888. firstFreeSlotOffset += s;
  65889. }
  65890. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  65891. if (freeZoneSize <= usedRange) {
  65892. firstFreeSlotOffset = curMoveOffset + s;
  65893. freeZoneSize = 1 + copyCount;
  65894. }
  65895. else {
  65896. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  65897. }
  65898. // as we're about to iterate to the next, the cur becomes the previous...
  65899. prevOffset = curOffset;
  65900. }
  65901. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  65902. this._lastUsed = firstFreeSlotOffset - s;
  65903. this._firstFree = firstFreeSlotOffset;
  65904. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  65905. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  65906. this._allEntries = sortedAll;
  65907. return elementsBuffer;
  65908. };
  65909. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  65910. for (var i = 0; i < this._stride; i++) {
  65911. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  65912. }
  65913. element.offset = destOffset;
  65914. };
  65915. DynamicFloatArray.prototype._growBuffer = function () {
  65916. // Allocate the new buffer with 50% more entries, copy the content of the current one
  65917. var newElCount = Math.floor(this.totalElementCount * 1.5);
  65918. var newBuffer = new Float32Array(newElCount * this._stride);
  65919. newBuffer.set(this.buffer);
  65920. var curCount = this.totalElementCount;
  65921. var addedCount = newElCount - this.totalElementCount;
  65922. for (var i = 0; i < addedCount; i++) {
  65923. var element = new DynamicFloatArrayElementInfo();
  65924. element.offset = (curCount + i) * this.stride;
  65925. this._allEntries.push(element);
  65926. this._freeEntries[addedCount - i - 1] = element;
  65927. }
  65928. this._firstFree = curCount * this.stride;
  65929. this.buffer = newBuffer;
  65930. };
  65931. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  65932. /**
  65933. * Get the total count of entries that can fit in the current buffer
  65934. * @returns the elements count
  65935. */
  65936. get: function () {
  65937. return this._allEntries.length;
  65938. },
  65939. enumerable: true,
  65940. configurable: true
  65941. });
  65942. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  65943. /**
  65944. * Get the count of free entries that can still be allocated without resizing the buffer
  65945. * @returns the free elements count
  65946. */
  65947. get: function () {
  65948. return this._freeEntries.length;
  65949. },
  65950. enumerable: true,
  65951. configurable: true
  65952. });
  65953. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  65954. /**
  65955. * Get the count of allocated elements
  65956. * @returns the allocated elements count
  65957. */
  65958. get: function () {
  65959. return this._allEntries.length - this._freeEntries.length;
  65960. },
  65961. enumerable: true,
  65962. configurable: true
  65963. });
  65964. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  65965. /**
  65966. * Return the size of one element in float
  65967. * @returns the size in float
  65968. */
  65969. get: function () {
  65970. return this._stride;
  65971. },
  65972. enumerable: true,
  65973. configurable: true
  65974. });
  65975. DynamicFloatArray.prototype.sort = function () {
  65976. var _this = this;
  65977. if (!this.compareValueOffset) {
  65978. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  65979. }
  65980. var count = this.usedElementCount;
  65981. // Do we have to (re)create the sort table?
  65982. if (!this._sortTable || this._sortTable.length < count) {
  65983. // Small heuristic... We don't want to allocate totalElementCount right away because it may have 50 for 3 used elements, but on the other side we don't want to allocate just 3 when we just need 2, so double this value to give us some air to breath...
  65984. var newCount = Math.min(this.totalElementCount, count * 2);
  65985. this._sortTable = new Array(newCount);
  65986. }
  65987. if (!this._sortedTable || this._sortedTable.length !== count) {
  65988. this._sortedTable = new Array(count);
  65989. }
  65990. // Because, you know...
  65991. this.pack();
  65992. //let stride = this.stride;
  65993. //for (let i = 0; i < count; i++) {
  65994. // let si = this._sortTable[i];
  65995. // if (!si) {
  65996. // si = new SortInfo();
  65997. // this._sortTable[i] = si;
  65998. // }
  65999. // si.entry = this._allEntries[i];
  66000. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  66001. // si.swapedOffset = null;
  66002. // this._sortedTable[i] = si;
  66003. //}
  66004. var curOffset = 0;
  66005. var stride = this.stride;
  66006. for (var i = 0; i < count; i++, curOffset += stride) {
  66007. var si = this._sortTable[i];
  66008. if (!si) {
  66009. si = new SortInfo();
  66010. this._sortTable[i] = si;
  66011. }
  66012. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  66013. si.offset = curOffset;
  66014. si.swapedOffset = null;
  66015. this._sortedTable[i] = si;
  66016. }
  66017. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  66018. if (this.sortingAscending) {
  66019. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  66020. }
  66021. else {
  66022. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  66023. }
  66024. var swapElements = function (src, dst) {
  66025. for (var i = 0; i < stride; i++) {
  66026. var tps = _this.buffer[dst + i];
  66027. _this.buffer[dst + i] = _this.buffer[src + i];
  66028. _this.buffer[src + i] = tps;
  66029. }
  66030. };
  66031. // The fun part begin, sortedTable give us the ordered layout to obtain, to get that we have to move elements, but when we move an element:
  66032. // it replaces an existing one.I don't want to allocate a new Float32Array and do a raw copy, because it's awful (GC - wise),
  66033. // and I still want something with a good algorithm complexity.
  66034. // So here's the deal: we are going to swap elements, but we have to track the change of location of the element being replaced,
  66035. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  66036. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  66037. // When we'll look for and element, we'll check if its swapedOffset is set, if so we reiterate the operation with the one there
  66038. // until we find a SortInfo object without a swapedOffset which means we got the right location
  66039. // Yes, we may have to do multiple iterations to find the right location, but hey, it won't be huge: <3 in most cases, and it's better
  66040. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  66041. for (var i = 0; i < count; i++) {
  66042. // Get the element to move
  66043. var sourceSI = this._sortedTable[i];
  66044. var destSI = this._sortTable[i];
  66045. var sourceOff = sourceSI.offset;
  66046. // If the source changed location, find the new one
  66047. if (sourceSI.swapedOffset) {
  66048. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  66049. var curSI = sourceSI;
  66050. while (curSI.swapedOffset) {
  66051. curSI = this._sortTable[curSI.swapedOffset / stride];
  66052. }
  66053. // Finally get the right location
  66054. sourceOff = curSI.offset;
  66055. }
  66056. // Tag the element being replaced with its new location
  66057. destSI.swapedOffset = sourceOff;
  66058. // Swap elements (only if needed)
  66059. if (sourceOff !== destSI.offset) {
  66060. swapElements(sourceOff, destSI.offset);
  66061. }
  66062. // Update the offset in the corresponding DFAE
  66063. //sourceSI.entry.offset = destSI.entry.offset;
  66064. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  66065. }
  66066. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  66067. return true;
  66068. };
  66069. return DynamicFloatArray;
  66070. }());
  66071. BABYLON.DynamicFloatArray = DynamicFloatArray;
  66072. var SortInfo = (function () {
  66073. function SortInfo() {
  66074. this.compareData = this.offset = this.swapedOffset = null;
  66075. }
  66076. return SortInfo;
  66077. }());
  66078. })(BABYLON || (BABYLON = {}));
  66079. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  66080. var BABYLON;
  66081. (function (BABYLON) {
  66082. var Debug;
  66083. (function (Debug) {
  66084. /**
  66085. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  66086. */
  66087. var SkeletonViewer = (function () {
  66088. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  66089. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  66090. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  66091. this.skeleton = skeleton;
  66092. this.mesh = mesh;
  66093. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  66094. this.renderingGroupId = renderingGroupId;
  66095. this.color = BABYLON.Color3.White();
  66096. this._debugLines = new Array();
  66097. this._isEnabled = false;
  66098. this._scene = scene;
  66099. this.update();
  66100. this._renderFunction = this.update.bind(this);
  66101. }
  66102. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  66103. get: function () {
  66104. return this._isEnabled;
  66105. },
  66106. set: function (value) {
  66107. if (this._isEnabled === value) {
  66108. return;
  66109. }
  66110. this._isEnabled = value;
  66111. if (value) {
  66112. this._scene.registerBeforeRender(this._renderFunction);
  66113. }
  66114. else {
  66115. this._scene.unregisterBeforeRender(this._renderFunction);
  66116. }
  66117. },
  66118. enumerable: true,
  66119. configurable: true
  66120. });
  66121. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  66122. if (x === void 0) { x = 0; }
  66123. if (y === void 0) { y = 0; }
  66124. if (z === void 0) { z = 0; }
  66125. var tmat = BABYLON.Tmp.Matrix[0];
  66126. var parentBone = bone.getParent();
  66127. tmat.copyFrom(bone.getLocalMatrix());
  66128. if (x !== 0 || y !== 0 || z !== 0) {
  66129. var tmat2 = BABYLON.Tmp.Matrix[1];
  66130. BABYLON.Matrix.IdentityToRef(tmat2);
  66131. tmat2.m[12] = x;
  66132. tmat2.m[13] = y;
  66133. tmat2.m[14] = z;
  66134. tmat2.multiplyToRef(tmat, tmat);
  66135. }
  66136. if (parentBone) {
  66137. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  66138. }
  66139. tmat.multiplyToRef(meshMat, tmat);
  66140. position.x = tmat.m[12];
  66141. position.y = tmat.m[13];
  66142. position.z = tmat.m[14];
  66143. };
  66144. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  66145. var len = bones.length;
  66146. var meshPos = this.mesh.position;
  66147. for (var i = 0; i < len; i++) {
  66148. var bone = bones[i];
  66149. var points = this._debugLines[i];
  66150. if (!points) {
  66151. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66152. this._debugLines[i] = points;
  66153. }
  66154. this._getBonePosition(points[0], bone, meshMat);
  66155. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  66156. points[0].subtractInPlace(meshPos);
  66157. points[1].subtractInPlace(meshPos);
  66158. }
  66159. };
  66160. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  66161. var len = bones.length;
  66162. var boneNum = 0;
  66163. var meshPos = this.mesh.position;
  66164. for (var i = len - 1; i >= 0; i--) {
  66165. var childBone = bones[i];
  66166. var parentBone = childBone.getParent();
  66167. if (!parentBone) {
  66168. continue;
  66169. }
  66170. var points = this._debugLines[boneNum];
  66171. if (!points) {
  66172. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66173. this._debugLines[boneNum] = points;
  66174. }
  66175. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  66176. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  66177. points[0].subtractInPlace(meshPos);
  66178. points[1].subtractInPlace(meshPos);
  66179. boneNum++;
  66180. }
  66181. };
  66182. SkeletonViewer.prototype.update = function () {
  66183. if (this.autoUpdateBonesMatrices) {
  66184. this.skeleton.computeAbsoluteTransforms();
  66185. }
  66186. if (this.skeleton.bones[0].length === undefined) {
  66187. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  66188. }
  66189. else {
  66190. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  66191. }
  66192. if (!this._debugMesh) {
  66193. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  66194. this._debugMesh.renderingGroupId = this.renderingGroupId;
  66195. }
  66196. else {
  66197. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  66198. }
  66199. this._debugMesh.position.copyFrom(this.mesh.position);
  66200. this._debugMesh.color = this.color;
  66201. };
  66202. SkeletonViewer.prototype.dispose = function () {
  66203. if (this._debugMesh) {
  66204. this.isEnabled = false;
  66205. this._debugMesh.dispose();
  66206. this._debugMesh = null;
  66207. }
  66208. };
  66209. return SkeletonViewer;
  66210. }());
  66211. Debug.SkeletonViewer = SkeletonViewer;
  66212. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  66213. })(BABYLON || (BABYLON = {}));
  66214. //# sourceMappingURL=babylon.skeletonViewer.js.map
  66215. var BABYLON;
  66216. (function (BABYLON) {
  66217. var Debug;
  66218. (function (Debug) {
  66219. var AxesViewer = (function () {
  66220. function AxesViewer(scene, scaleLines) {
  66221. if (scaleLines === void 0) { scaleLines = 1; }
  66222. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66223. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66224. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66225. this.scaleLines = 1;
  66226. this.scaleLines = scaleLines;
  66227. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  66228. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  66229. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  66230. this._xmesh.renderingGroupId = 2;
  66231. this._ymesh.renderingGroupId = 2;
  66232. this._zmesh.renderingGroupId = 2;
  66233. this._xmesh.material.checkReadyOnlyOnce = true;
  66234. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  66235. this._ymesh.material.checkReadyOnlyOnce = true;
  66236. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  66237. this._zmesh.material.checkReadyOnlyOnce = true;
  66238. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  66239. this.scene = scene;
  66240. }
  66241. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  66242. var scaleLines = this.scaleLines;
  66243. this._xmesh.position.copyFrom(position);
  66244. this._ymesh.position.copyFrom(position);
  66245. this._zmesh.position.copyFrom(position);
  66246. var point2 = this._xline[1];
  66247. point2.x = xaxis.x * scaleLines;
  66248. point2.y = xaxis.y * scaleLines;
  66249. point2.z = xaxis.z * scaleLines;
  66250. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  66251. point2 = this._yline[1];
  66252. point2.x = yaxis.x * scaleLines;
  66253. point2.y = yaxis.y * scaleLines;
  66254. point2.z = yaxis.z * scaleLines;
  66255. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  66256. point2 = this._zline[1];
  66257. point2.x = zaxis.x * scaleLines;
  66258. point2.y = zaxis.y * scaleLines;
  66259. point2.z = zaxis.z * scaleLines;
  66260. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  66261. };
  66262. AxesViewer.prototype.dispose = function () {
  66263. if (this._xmesh) {
  66264. this._xmesh.dispose();
  66265. this._ymesh.dispose();
  66266. this._zmesh.dispose();
  66267. this._xmesh = null;
  66268. this._ymesh = null;
  66269. this._zmesh = null;
  66270. this._xline = null;
  66271. this._yline = null;
  66272. this._zline = null;
  66273. this.scene = null;
  66274. }
  66275. };
  66276. return AxesViewer;
  66277. }());
  66278. Debug.AxesViewer = AxesViewer;
  66279. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  66280. })(BABYLON || (BABYLON = {}));
  66281. //# sourceMappingURL=babylon.axesViewer.js.map
  66282. var BABYLON;
  66283. (function (BABYLON) {
  66284. var Debug;
  66285. (function (Debug) {
  66286. var BoneAxesViewer = (function (_super) {
  66287. __extends(BoneAxesViewer, _super);
  66288. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  66289. if (scaleLines === void 0) { scaleLines = 1; }
  66290. var _this = _super.call(this, scene, scaleLines) || this;
  66291. _this.pos = BABYLON.Vector3.Zero();
  66292. _this.xaxis = BABYLON.Vector3.Zero();
  66293. _this.yaxis = BABYLON.Vector3.Zero();
  66294. _this.zaxis = BABYLON.Vector3.Zero();
  66295. _this.mesh = mesh;
  66296. _this.bone = bone;
  66297. return _this;
  66298. }
  66299. BoneAxesViewer.prototype.update = function () {
  66300. var bone = this.bone;
  66301. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  66302. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  66303. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  66304. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  66305. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  66306. };
  66307. BoneAxesViewer.prototype.dispose = function () {
  66308. if (this.pos) {
  66309. this.pos = null;
  66310. this.xaxis = null;
  66311. this.yaxis = null;
  66312. this.zaxis = null;
  66313. this.mesh = null;
  66314. this.bone = null;
  66315. _super.prototype.dispose.call(this);
  66316. }
  66317. };
  66318. return BoneAxesViewer;
  66319. }(Debug.AxesViewer));
  66320. Debug.BoneAxesViewer = BoneAxesViewer;
  66321. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  66322. })(BABYLON || (BABYLON = {}));
  66323. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  66324. var BABYLON;
  66325. (function (BABYLON) {
  66326. var RayHelper = (function () {
  66327. function RayHelper(ray) {
  66328. this.ray = ray;
  66329. }
  66330. RayHelper.CreateAndShow = function (ray, scene, color) {
  66331. var helper = new RayHelper(ray);
  66332. helper.show(scene, color);
  66333. return helper;
  66334. };
  66335. RayHelper.prototype.show = function (scene, color) {
  66336. if (!this._renderFunction) {
  66337. var ray = this.ray;
  66338. this._renderFunction = this._render.bind(this);
  66339. this._scene = scene;
  66340. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  66341. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  66342. this._scene.registerBeforeRender(this._renderFunction);
  66343. }
  66344. if (color) {
  66345. this._renderLine.color.copyFrom(color);
  66346. }
  66347. };
  66348. RayHelper.prototype.hide = function () {
  66349. if (this._renderFunction) {
  66350. this._scene.unregisterBeforeRender(this._renderFunction);
  66351. this._scene = null;
  66352. this._renderFunction = null;
  66353. this._renderLine.dispose();
  66354. this._renderLine = null;
  66355. this._renderPoints = null;
  66356. }
  66357. };
  66358. RayHelper.prototype._render = function () {
  66359. var ray = this.ray;
  66360. var point = this._renderPoints[1];
  66361. var len = Math.min(ray.length, 1000000);
  66362. point.copyFrom(ray.direction);
  66363. point.scaleInPlace(len);
  66364. point.addInPlace(ray.origin);
  66365. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  66366. };
  66367. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  66368. this._attachedToMesh = mesh;
  66369. var ray = this.ray;
  66370. if (!ray.direction) {
  66371. ray.direction = BABYLON.Vector3.Zero();
  66372. }
  66373. if (!ray.origin) {
  66374. ray.origin = BABYLON.Vector3.Zero();
  66375. }
  66376. if (length) {
  66377. ray.length = length;
  66378. }
  66379. if (!meshSpaceOrigin) {
  66380. meshSpaceOrigin = BABYLON.Vector3.Zero();
  66381. }
  66382. if (!meshSpaceDirection) {
  66383. // -1 so that this will work with Mesh.lookAt
  66384. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  66385. }
  66386. if (!this._meshSpaceDirection) {
  66387. this._meshSpaceDirection = meshSpaceDirection.clone();
  66388. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  66389. }
  66390. else {
  66391. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  66392. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  66393. }
  66394. if (!this._updateToMeshFunction) {
  66395. this._updateToMeshFunction = this._updateToMesh.bind(this);
  66396. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  66397. }
  66398. this._updateToMesh();
  66399. };
  66400. RayHelper.prototype.detachFromMesh = function () {
  66401. if (this._attachedToMesh) {
  66402. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  66403. this._attachedToMesh = null;
  66404. this._updateToMeshFunction = null;
  66405. }
  66406. };
  66407. RayHelper.prototype._updateToMesh = function () {
  66408. var ray = this.ray;
  66409. if (this._attachedToMesh._isDisposed) {
  66410. this.detachFromMesh();
  66411. return;
  66412. }
  66413. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  66414. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  66415. };
  66416. RayHelper.prototype.dispose = function () {
  66417. this.hide();
  66418. this.detachFromMesh();
  66419. this.ray = null;
  66420. };
  66421. return RayHelper;
  66422. }());
  66423. BABYLON.RayHelper = RayHelper;
  66424. })(BABYLON || (BABYLON = {}));
  66425. //# sourceMappingURL=babylon.rayHelper.js.map
  66426. var BABYLON;
  66427. (function (BABYLON) {
  66428. var DebugLayer = (function () {
  66429. function DebugLayer(scene) {
  66430. this._scene = scene;
  66431. }
  66432. /** Creates the inspector window. */
  66433. DebugLayer.prototype._createInspector = function (config) {
  66434. if (config === void 0) { config = {}; }
  66435. var popup = config.popup || false;
  66436. var initialTab = config.initialTab || 0;
  66437. var parentElement = config.parentElement || null;
  66438. if (!this._inspector) {
  66439. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  66440. } // else nothing to do,; instance is already existing
  66441. };
  66442. DebugLayer.prototype.isVisible = function () {
  66443. if (!this._inspector) {
  66444. return false;
  66445. }
  66446. return true;
  66447. };
  66448. DebugLayer.prototype.hide = function () {
  66449. if (this._inspector) {
  66450. try {
  66451. this._inspector.dispose();
  66452. }
  66453. catch (e) {
  66454. // If the inspector has been removed directly from the inspector tool
  66455. }
  66456. this._inspector = null;
  66457. }
  66458. };
  66459. DebugLayer.prototype.show = function (config) {
  66460. if (config === void 0) { config = {}; }
  66461. if (typeof INSPECTOR == 'undefined') {
  66462. // Load inspector and add it to the DOM
  66463. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  66464. }
  66465. else {
  66466. // Otherwise creates the inspector
  66467. this._createInspector(config);
  66468. }
  66469. };
  66470. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  66471. return DebugLayer;
  66472. }());
  66473. BABYLON.DebugLayer = DebugLayer;
  66474. })(BABYLON || (BABYLON = {}));
  66475. //# sourceMappingURL=babylon.debugLayer.js.map
  66476. var BABYLON;
  66477. (function (BABYLON) {
  66478. var Debug;
  66479. (function (Debug) {
  66480. var PhysicsViewer = (function () {
  66481. function PhysicsViewer(scene) {
  66482. this._impostors = [];
  66483. this._meshes = [];
  66484. this._numMeshes = 0;
  66485. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66486. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  66487. }
  66488. PhysicsViewer.prototype._updateDebugMeshes = function () {
  66489. var plugin = this._physicsEnginePlugin;
  66490. for (var i = 0; i < this._numMeshes; i++) {
  66491. if (this._impostors[i].isDisposed) {
  66492. this.hideImpostor(this._impostors[i--]);
  66493. }
  66494. else {
  66495. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  66496. }
  66497. }
  66498. };
  66499. PhysicsViewer.prototype.showImpostor = function (impostor) {
  66500. for (var i = 0; i < this._numMeshes; i++) {
  66501. if (this._impostors[i] == impostor) {
  66502. return;
  66503. }
  66504. }
  66505. var debugMesh = this._getDebugMesh(impostor, this._scene);
  66506. if (debugMesh) {
  66507. this._impostors[this._numMeshes] = impostor;
  66508. this._meshes[this._numMeshes] = debugMesh;
  66509. if (this._numMeshes === 0) {
  66510. this._renderFunction = this._updateDebugMeshes.bind(this);
  66511. this._scene.registerBeforeRender(this._renderFunction);
  66512. }
  66513. this._numMeshes++;
  66514. }
  66515. };
  66516. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  66517. var removed = false;
  66518. for (var i = 0; i < this._numMeshes; i++) {
  66519. if (this._impostors[i] == impostor) {
  66520. this._scene.removeMesh(this._meshes[i]);
  66521. this._meshes[i].dispose();
  66522. this._numMeshes--;
  66523. if (this._numMeshes > 0) {
  66524. this._meshes[i] = this._meshes[this._numMeshes];
  66525. this._impostors[i] = this._impostors[this._numMeshes];
  66526. this._meshes[this._numMeshes] = null;
  66527. this._impostors[this._numMeshes] = null;
  66528. }
  66529. else {
  66530. this._meshes[0] = null;
  66531. this._impostors[0] = null;
  66532. }
  66533. removed = true;
  66534. break;
  66535. }
  66536. }
  66537. if (removed && this._numMeshes === 0) {
  66538. this._scene.unregisterBeforeRender(this._renderFunction);
  66539. }
  66540. };
  66541. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  66542. if (!this._debugMaterial) {
  66543. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  66544. this._debugMaterial.wireframe = true;
  66545. }
  66546. return this._debugMaterial;
  66547. };
  66548. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  66549. if (!this._debugBoxMesh) {
  66550. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  66551. this._debugBoxMesh.renderingGroupId = 1;
  66552. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  66553. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  66554. scene.removeMesh(this._debugBoxMesh);
  66555. }
  66556. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  66557. };
  66558. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  66559. if (!this._debugSphereMesh) {
  66560. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  66561. this._debugSphereMesh.renderingGroupId = 1;
  66562. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  66563. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  66564. scene.removeMesh(this._debugSphereMesh);
  66565. }
  66566. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  66567. };
  66568. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  66569. var mesh;
  66570. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  66571. mesh = this._getDebugBoxMesh(scene);
  66572. impostor.getBoxSizeToRef(mesh.scaling);
  66573. }
  66574. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  66575. mesh = this._getDebugSphereMesh(scene);
  66576. var radius = impostor.getRadius();
  66577. mesh.scaling.x = radius * 2;
  66578. mesh.scaling.y = radius * 2;
  66579. mesh.scaling.z = radius * 2;
  66580. }
  66581. return mesh;
  66582. };
  66583. PhysicsViewer.prototype.dispose = function () {
  66584. for (var i = 0; i < this._numMeshes; i++) {
  66585. this.hideImpostor(this._impostors[i]);
  66586. }
  66587. if (this._debugBoxMesh) {
  66588. this._debugBoxMesh.dispose();
  66589. }
  66590. if (this._debugSphereMesh) {
  66591. this._debugSphereMesh.dispose();
  66592. }
  66593. if (this._debugMaterial) {
  66594. this._debugMaterial.dispose();
  66595. }
  66596. this._impostors.length = 0;
  66597. this._scene = null;
  66598. this._physicsEnginePlugin = null;
  66599. };
  66600. return PhysicsViewer;
  66601. }());
  66602. Debug.PhysicsViewer = PhysicsViewer;
  66603. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  66604. })(BABYLON || (BABYLON = {}));
  66605. //# sourceMappingURL=babylon.physicsViewer.js.map
  66606. var BABYLON;
  66607. (function (BABYLON) {
  66608. var BoundingBoxRenderer = (function () {
  66609. function BoundingBoxRenderer(scene) {
  66610. this.frontColor = new BABYLON.Color3(1, 1, 1);
  66611. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  66612. this.showBackLines = true;
  66613. this.renderList = new BABYLON.SmartArray(32);
  66614. this._vertexBuffers = {};
  66615. this._scene = scene;
  66616. }
  66617. BoundingBoxRenderer.prototype._prepareRessources = function () {
  66618. if (this._colorShader) {
  66619. return;
  66620. }
  66621. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  66622. attributes: [BABYLON.VertexBuffer.PositionKind],
  66623. uniforms: ["world", "viewProjection", "color"]
  66624. });
  66625. var engine = this._scene.getEngine();
  66626. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  66627. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  66628. this._createIndexBuffer();
  66629. };
  66630. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  66631. var engine = this._scene.getEngine();
  66632. 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]);
  66633. };
  66634. BoundingBoxRenderer.prototype._rebuild = function () {
  66635. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  66636. this._createIndexBuffer();
  66637. };
  66638. BoundingBoxRenderer.prototype.reset = function () {
  66639. this.renderList.reset();
  66640. };
  66641. BoundingBoxRenderer.prototype.render = function () {
  66642. if (this.renderList.length === 0) {
  66643. return;
  66644. }
  66645. this._prepareRessources();
  66646. if (!this._colorShader.isReady()) {
  66647. return;
  66648. }
  66649. var engine = this._scene.getEngine();
  66650. engine.setDepthWrite(false);
  66651. this._colorShader._preBind();
  66652. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  66653. var boundingBox = this.renderList.data[boundingBoxIndex];
  66654. var min = boundingBox.minimum;
  66655. var max = boundingBox.maximum;
  66656. var diff = max.subtract(min);
  66657. var median = min.add(diff.scale(0.5));
  66658. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  66659. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  66660. .multiply(boundingBox.getWorldMatrix());
  66661. // VBOs
  66662. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  66663. if (this.showBackLines) {
  66664. // Back
  66665. engine.setDepthFunctionToGreaterOrEqual();
  66666. this._scene.resetCachedMaterial();
  66667. this._colorShader.setColor4("color", this.backColor.toColor4());
  66668. this._colorShader.bind(worldMatrix);
  66669. // Draw order
  66670. engine.draw(false, 0, 24);
  66671. }
  66672. // Front
  66673. engine.setDepthFunctionToLess();
  66674. this._scene.resetCachedMaterial();
  66675. this._colorShader.setColor4("color", this.frontColor.toColor4());
  66676. this._colorShader.bind(worldMatrix);
  66677. // Draw order
  66678. engine.draw(false, 0, 24);
  66679. }
  66680. this._colorShader.unbind();
  66681. engine.setDepthFunctionToLessOrEqual();
  66682. engine.setDepthWrite(true);
  66683. };
  66684. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  66685. this._prepareRessources();
  66686. if (!this._colorShader.isReady()) {
  66687. return;
  66688. }
  66689. var engine = this._scene.getEngine();
  66690. engine.setDepthWrite(false);
  66691. engine.setColorWrite(false);
  66692. this._colorShader._preBind();
  66693. var boundingBox = mesh._boundingInfo.boundingBox;
  66694. var min = boundingBox.minimum;
  66695. var max = boundingBox.maximum;
  66696. var diff = max.subtract(min);
  66697. var median = min.add(diff.scale(0.5));
  66698. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  66699. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  66700. .multiply(boundingBox.getWorldMatrix());
  66701. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  66702. engine.setDepthFunctionToLess();
  66703. this._scene.resetCachedMaterial();
  66704. this._colorShader.bind(worldMatrix);
  66705. engine.draw(false, 0, 24);
  66706. this._colorShader.unbind();
  66707. engine.setDepthFunctionToLessOrEqual();
  66708. engine.setDepthWrite(true);
  66709. engine.setColorWrite(true);
  66710. };
  66711. BoundingBoxRenderer.prototype.dispose = function () {
  66712. if (!this._colorShader) {
  66713. return;
  66714. }
  66715. this.renderList.dispose();
  66716. this._colorShader.dispose();
  66717. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66718. if (buffer) {
  66719. buffer.dispose();
  66720. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66721. }
  66722. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  66723. };
  66724. return BoundingBoxRenderer;
  66725. }());
  66726. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  66727. })(BABYLON || (BABYLON = {}));
  66728. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  66729. var BABYLON;
  66730. (function (BABYLON) {
  66731. var MorphTarget = (function () {
  66732. function MorphTarget(name, influence) {
  66733. if (influence === void 0) { influence = 0; }
  66734. this.name = name;
  66735. this.animations = new Array();
  66736. this.onInfluenceChanged = new BABYLON.Observable();
  66737. this.influence = influence;
  66738. }
  66739. Object.defineProperty(MorphTarget.prototype, "influence", {
  66740. get: function () {
  66741. return this._influence;
  66742. },
  66743. set: function (influence) {
  66744. if (this._influence === influence) {
  66745. return;
  66746. }
  66747. var previous = this._influence;
  66748. this._influence = influence;
  66749. if (this.onInfluenceChanged.hasObservers) {
  66750. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  66751. }
  66752. },
  66753. enumerable: true,
  66754. configurable: true
  66755. });
  66756. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  66757. get: function () {
  66758. return this._normals !== undefined;
  66759. },
  66760. enumerable: true,
  66761. configurable: true
  66762. });
  66763. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  66764. get: function () {
  66765. return this._tangents !== undefined;
  66766. },
  66767. enumerable: true,
  66768. configurable: true
  66769. });
  66770. MorphTarget.prototype.setPositions = function (data) {
  66771. this._positions = new Float32Array(data);
  66772. };
  66773. MorphTarget.prototype.getPositions = function () {
  66774. return this._positions;
  66775. };
  66776. MorphTarget.prototype.setNormals = function (data) {
  66777. this._normals = new Float32Array(data);
  66778. };
  66779. MorphTarget.prototype.getNormals = function () {
  66780. return this._normals;
  66781. };
  66782. MorphTarget.prototype.setTangents = function (data) {
  66783. this._tangents = new Float32Array(data);
  66784. };
  66785. MorphTarget.prototype.getTangents = function () {
  66786. return this._tangents;
  66787. };
  66788. /**
  66789. * Serializes the current target into a Serialization object.
  66790. * Returns the serialized object.
  66791. */
  66792. MorphTarget.prototype.serialize = function () {
  66793. var serializationObject = {};
  66794. serializationObject.name = this.name;
  66795. serializationObject.influence = this.influence;
  66796. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  66797. if (this.hasNormals) {
  66798. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  66799. }
  66800. if (this.hasTangents) {
  66801. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  66802. }
  66803. // Animations
  66804. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  66805. return serializationObject;
  66806. };
  66807. // Statics
  66808. MorphTarget.Parse = function (serializationObject) {
  66809. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  66810. result.setPositions(serializationObject.positions);
  66811. if (serializationObject.normals) {
  66812. result.setNormals(serializationObject.normals);
  66813. }
  66814. if (serializationObject.tangents) {
  66815. result.setTangents(serializationObject.tangents);
  66816. }
  66817. // Animations
  66818. if (serializationObject.animations) {
  66819. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  66820. var parsedAnimation = serializationObject.animations[animationIndex];
  66821. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  66822. }
  66823. }
  66824. return result;
  66825. };
  66826. MorphTarget.FromMesh = function (mesh, name, influence) {
  66827. if (!name) {
  66828. name = mesh.name;
  66829. }
  66830. var result = new MorphTarget(name, influence);
  66831. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  66832. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66833. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  66834. }
  66835. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  66836. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  66837. }
  66838. return result;
  66839. };
  66840. return MorphTarget;
  66841. }());
  66842. BABYLON.MorphTarget = MorphTarget;
  66843. })(BABYLON || (BABYLON = {}));
  66844. //# sourceMappingURL=babylon.morphTarget.js.map
  66845. var BABYLON;
  66846. (function (BABYLON) {
  66847. var MorphTargetManager = (function () {
  66848. function MorphTargetManager(scene) {
  66849. this._targets = new Array();
  66850. this._targetObservable = new Array();
  66851. this._activeTargets = new BABYLON.SmartArray(16);
  66852. this._supportsNormals = false;
  66853. this._supportsTangents = false;
  66854. this._vertexCount = 0;
  66855. this._uniqueId = 0;
  66856. this._tempInfluences = new Array();
  66857. if (!scene) {
  66858. scene = BABYLON.Engine.LastCreatedScene;
  66859. }
  66860. this._scene = scene;
  66861. this._scene.morphTargetManagers.push(this);
  66862. this._uniqueId = scene.getUniqueId();
  66863. }
  66864. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  66865. get: function () {
  66866. return this._uniqueId;
  66867. },
  66868. enumerable: true,
  66869. configurable: true
  66870. });
  66871. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  66872. get: function () {
  66873. return this._vertexCount;
  66874. },
  66875. enumerable: true,
  66876. configurable: true
  66877. });
  66878. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  66879. get: function () {
  66880. return this._supportsNormals;
  66881. },
  66882. enumerable: true,
  66883. configurable: true
  66884. });
  66885. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  66886. get: function () {
  66887. return this._supportsTangents;
  66888. },
  66889. enumerable: true,
  66890. configurable: true
  66891. });
  66892. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  66893. get: function () {
  66894. return this._targets.length;
  66895. },
  66896. enumerable: true,
  66897. configurable: true
  66898. });
  66899. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  66900. get: function () {
  66901. return this._activeTargets.length;
  66902. },
  66903. enumerable: true,
  66904. configurable: true
  66905. });
  66906. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  66907. get: function () {
  66908. return this._influences;
  66909. },
  66910. enumerable: true,
  66911. configurable: true
  66912. });
  66913. MorphTargetManager.prototype.getActiveTarget = function (index) {
  66914. return this._activeTargets.data[index];
  66915. };
  66916. MorphTargetManager.prototype.getTarget = function (index) {
  66917. return this._targets[index];
  66918. };
  66919. MorphTargetManager.prototype.addTarget = function (target) {
  66920. var _this = this;
  66921. if (this._vertexCount) {
  66922. if (this._vertexCount !== target.getPositions().length / 3) {
  66923. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  66924. return;
  66925. }
  66926. }
  66927. this._targets.push(target);
  66928. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  66929. _this._syncActiveTargets(needUpdate);
  66930. }));
  66931. this._syncActiveTargets(true);
  66932. };
  66933. MorphTargetManager.prototype.removeTarget = function (target) {
  66934. var index = this._targets.indexOf(target);
  66935. if (index >= 0) {
  66936. this._targets.splice(index, 1);
  66937. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  66938. this._vertexCount = 0;
  66939. this._syncActiveTargets(true);
  66940. }
  66941. };
  66942. /**
  66943. * Serializes the current manager into a Serialization object.
  66944. * Returns the serialized object.
  66945. */
  66946. MorphTargetManager.prototype.serialize = function () {
  66947. var serializationObject = {};
  66948. serializationObject.id = this.uniqueId;
  66949. serializationObject.targets = [];
  66950. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  66951. var target = _a[_i];
  66952. serializationObject.targets.push(target.serialize());
  66953. }
  66954. return serializationObject;
  66955. };
  66956. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  66957. var influenceCount = 0;
  66958. this._activeTargets.reset();
  66959. this._supportsNormals = true;
  66960. this._supportsTangents = true;
  66961. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  66962. var target = _a[_i];
  66963. if (target.influence > 0) {
  66964. this._activeTargets.push(target);
  66965. this._tempInfluences[influenceCount++] = target.influence;
  66966. this._supportsNormals = this._supportsNormals && target.hasNormals;
  66967. this._supportsTangents = this._supportsTangents && target.hasTangents;
  66968. if (this._vertexCount === 0) {
  66969. this._vertexCount = target.getPositions().length / 3;
  66970. }
  66971. }
  66972. }
  66973. if (!this._influences || this._influences.length !== influenceCount) {
  66974. this._influences = new Float32Array(influenceCount);
  66975. }
  66976. for (var index = 0; index < influenceCount; index++) {
  66977. this._influences[index] = this._tempInfluences[index];
  66978. }
  66979. if (needUpdate) {
  66980. // Flag meshes as dirty to resync with the active targets
  66981. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  66982. var mesh = _c[_b];
  66983. if (mesh.morphTargetManager === this) {
  66984. mesh._syncGeometryWithMorphTargetManager();
  66985. }
  66986. }
  66987. }
  66988. };
  66989. // Statics
  66990. MorphTargetManager.Parse = function (serializationObject, scene) {
  66991. var result = new MorphTargetManager(scene);
  66992. result._uniqueId = serializationObject.id;
  66993. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  66994. var targetData = _a[_i];
  66995. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  66996. }
  66997. return result;
  66998. };
  66999. return MorphTargetManager;
  67000. }());
  67001. BABYLON.MorphTargetManager = MorphTargetManager;
  67002. })(BABYLON || (BABYLON = {}));
  67003. //# sourceMappingURL=babylon.morphTargetManager.js.map
  67004. var BABYLON;
  67005. (function (BABYLON) {
  67006. var Octree = (function () {
  67007. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  67008. if (maxDepth === void 0) { maxDepth = 2; }
  67009. this.maxDepth = maxDepth;
  67010. this.dynamicContent = new Array();
  67011. this._maxBlockCapacity = maxBlockCapacity || 64;
  67012. this._selectionContent = new BABYLON.SmartArray(1024);
  67013. this._creationFunc = creationFunc;
  67014. }
  67015. // Methods
  67016. Octree.prototype.update = function (worldMin, worldMax, entries) {
  67017. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  67018. };
  67019. Octree.prototype.addMesh = function (entry) {
  67020. for (var index = 0; index < this.blocks.length; index++) {
  67021. var block = this.blocks[index];
  67022. block.addEntry(entry);
  67023. }
  67024. };
  67025. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  67026. this._selectionContent.reset();
  67027. for (var index = 0; index < this.blocks.length; index++) {
  67028. var block = this.blocks[index];
  67029. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  67030. }
  67031. if (allowDuplicate) {
  67032. this._selectionContent.concat(this.dynamicContent);
  67033. }
  67034. else {
  67035. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  67036. }
  67037. return this._selectionContent;
  67038. };
  67039. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  67040. this._selectionContent.reset();
  67041. for (var index = 0; index < this.blocks.length; index++) {
  67042. var block = this.blocks[index];
  67043. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  67044. }
  67045. if (allowDuplicate) {
  67046. this._selectionContent.concat(this.dynamicContent);
  67047. }
  67048. else {
  67049. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  67050. }
  67051. return this._selectionContent;
  67052. };
  67053. Octree.prototype.intersectsRay = function (ray) {
  67054. this._selectionContent.reset();
  67055. for (var index = 0; index < this.blocks.length; index++) {
  67056. var block = this.blocks[index];
  67057. block.intersectsRay(ray, this._selectionContent);
  67058. }
  67059. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  67060. return this._selectionContent;
  67061. };
  67062. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  67063. target.blocks = new Array();
  67064. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  67065. // Segmenting space
  67066. for (var x = 0; x < 2; x++) {
  67067. for (var y = 0; y < 2; y++) {
  67068. for (var z = 0; z < 2; z++) {
  67069. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  67070. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  67071. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  67072. block.addEntries(entries);
  67073. target.blocks.push(block);
  67074. }
  67075. }
  67076. }
  67077. };
  67078. Octree.CreationFuncForMeshes = function (entry, block) {
  67079. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  67080. block.entries.push(entry);
  67081. }
  67082. };
  67083. Octree.CreationFuncForSubMeshes = function (entry, block) {
  67084. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  67085. block.entries.push(entry);
  67086. }
  67087. };
  67088. return Octree;
  67089. }());
  67090. BABYLON.Octree = Octree;
  67091. })(BABYLON || (BABYLON = {}));
  67092. //# sourceMappingURL=babylon.octree.js.map
  67093. var BABYLON;
  67094. (function (BABYLON) {
  67095. var OctreeBlock = (function () {
  67096. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  67097. this.entries = new Array();
  67098. this._boundingVectors = new Array();
  67099. this._capacity = capacity;
  67100. this._depth = depth;
  67101. this._maxDepth = maxDepth;
  67102. this._creationFunc = creationFunc;
  67103. this._minPoint = minPoint;
  67104. this._maxPoint = maxPoint;
  67105. this._boundingVectors.push(minPoint.clone());
  67106. this._boundingVectors.push(maxPoint.clone());
  67107. this._boundingVectors.push(minPoint.clone());
  67108. this._boundingVectors[2].x = maxPoint.x;
  67109. this._boundingVectors.push(minPoint.clone());
  67110. this._boundingVectors[3].y = maxPoint.y;
  67111. this._boundingVectors.push(minPoint.clone());
  67112. this._boundingVectors[4].z = maxPoint.z;
  67113. this._boundingVectors.push(maxPoint.clone());
  67114. this._boundingVectors[5].z = minPoint.z;
  67115. this._boundingVectors.push(maxPoint.clone());
  67116. this._boundingVectors[6].x = minPoint.x;
  67117. this._boundingVectors.push(maxPoint.clone());
  67118. this._boundingVectors[7].y = minPoint.y;
  67119. }
  67120. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  67121. // Property
  67122. get: function () {
  67123. return this._capacity;
  67124. },
  67125. enumerable: true,
  67126. configurable: true
  67127. });
  67128. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  67129. get: function () {
  67130. return this._minPoint;
  67131. },
  67132. enumerable: true,
  67133. configurable: true
  67134. });
  67135. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  67136. get: function () {
  67137. return this._maxPoint;
  67138. },
  67139. enumerable: true,
  67140. configurable: true
  67141. });
  67142. // Methods
  67143. OctreeBlock.prototype.addEntry = function (entry) {
  67144. if (this.blocks) {
  67145. for (var index = 0; index < this.blocks.length; index++) {
  67146. var block = this.blocks[index];
  67147. block.addEntry(entry);
  67148. }
  67149. return;
  67150. }
  67151. this._creationFunc(entry, this);
  67152. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  67153. this.createInnerBlocks();
  67154. }
  67155. };
  67156. OctreeBlock.prototype.addEntries = function (entries) {
  67157. for (var index = 0; index < entries.length; index++) {
  67158. var mesh = entries[index];
  67159. this.addEntry(mesh);
  67160. }
  67161. };
  67162. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  67163. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  67164. if (this.blocks) {
  67165. for (var index = 0; index < this.blocks.length; index++) {
  67166. var block = this.blocks[index];
  67167. block.select(frustumPlanes, selection, allowDuplicate);
  67168. }
  67169. return;
  67170. }
  67171. if (allowDuplicate) {
  67172. selection.concat(this.entries);
  67173. }
  67174. else {
  67175. selection.concatWithNoDuplicate(this.entries);
  67176. }
  67177. }
  67178. };
  67179. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  67180. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  67181. if (this.blocks) {
  67182. for (var index = 0; index < this.blocks.length; index++) {
  67183. var block = this.blocks[index];
  67184. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  67185. }
  67186. return;
  67187. }
  67188. if (allowDuplicate) {
  67189. selection.concat(this.entries);
  67190. }
  67191. else {
  67192. selection.concatWithNoDuplicate(this.entries);
  67193. }
  67194. }
  67195. };
  67196. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  67197. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  67198. if (this.blocks) {
  67199. for (var index = 0; index < this.blocks.length; index++) {
  67200. var block = this.blocks[index];
  67201. block.intersectsRay(ray, selection);
  67202. }
  67203. return;
  67204. }
  67205. selection.concatWithNoDuplicate(this.entries);
  67206. }
  67207. };
  67208. OctreeBlock.prototype.createInnerBlocks = function () {
  67209. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  67210. };
  67211. return OctreeBlock;
  67212. }());
  67213. BABYLON.OctreeBlock = OctreeBlock;
  67214. })(BABYLON || (BABYLON = {}));
  67215. //# sourceMappingURL=babylon.octreeBlock.js.map
  67216. var BABYLON;
  67217. (function (BABYLON) {
  67218. var SIMDVector3 = (function () {
  67219. function SIMDVector3() {
  67220. }
  67221. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  67222. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  67223. };
  67224. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  67225. var m = transformation.m;
  67226. var m0 = SIMD.Float32x4.load(m, 0);
  67227. var m1 = SIMD.Float32x4.load(m, 4);
  67228. var m2 = SIMD.Float32x4.load(m, 8);
  67229. var m3 = SIMD.Float32x4.load(m, 12);
  67230. 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));
  67231. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  67232. result.x = SIMD.Float32x4.extractLane(r, 0);
  67233. result.y = SIMD.Float32x4.extractLane(r, 1);
  67234. result.z = SIMD.Float32x4.extractLane(r, 2);
  67235. };
  67236. return SIMDVector3;
  67237. }());
  67238. var SIMDMatrix = (function () {
  67239. function SIMDMatrix() {
  67240. }
  67241. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  67242. var tm = this.m;
  67243. var om = other.m;
  67244. var m0 = SIMD.Float32x4.load(om, 0);
  67245. var m1 = SIMD.Float32x4.load(om, 4);
  67246. var m2 = SIMD.Float32x4.load(om, 8);
  67247. var m3 = SIMD.Float32x4.load(om, 12);
  67248. for (var i = 0; i < 16; i += 4) {
  67249. 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)))));
  67250. }
  67251. return this;
  67252. };
  67253. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  67254. var src = this.m;
  67255. var dest = other.m;
  67256. // Load the 4 rows
  67257. var src0 = SIMD.Float32x4.load(src, 0);
  67258. var src1 = SIMD.Float32x4.load(src, 4);
  67259. var src2 = SIMD.Float32x4.load(src, 8);
  67260. var src3 = SIMD.Float32x4.load(src, 12);
  67261. // Transpose the source matrix. Sort of. Not a true transpose operation
  67262. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  67263. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  67264. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  67265. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  67266. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  67267. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  67268. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  67269. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  67270. // This is a true transposition, but it will lead to an incorrect result
  67271. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  67272. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  67273. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  67274. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  67275. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  67276. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  67277. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  67278. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  67279. // ----
  67280. tmp1 = SIMD.Float32x4.mul(row2, row3);
  67281. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  67282. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  67283. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  67284. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  67285. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  67286. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  67287. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  67288. // ----
  67289. tmp1 = SIMD.Float32x4.mul(row1, row2);
  67290. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  67291. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  67292. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  67293. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  67294. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  67295. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  67296. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  67297. // ----
  67298. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  67299. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  67300. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  67301. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  67302. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  67303. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  67304. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  67305. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  67306. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  67307. // ----
  67308. tmp1 = SIMD.Float32x4.mul(row0, row1);
  67309. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  67310. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  67311. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  67312. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  67313. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  67314. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  67315. // ----
  67316. tmp1 = SIMD.Float32x4.mul(row0, row3);
  67317. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  67318. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  67319. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  67320. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  67321. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  67322. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  67323. // ----
  67324. tmp1 = SIMD.Float32x4.mul(row0, row2);
  67325. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  67326. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  67327. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  67328. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  67329. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  67330. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  67331. // Compute determinant
  67332. var det = SIMD.Float32x4.mul(row0, minor0);
  67333. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  67334. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  67335. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  67336. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  67337. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  67338. // These shuffles aren't necessary if the faulty transposition is done
  67339. // up at the top of this function.
  67340. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  67341. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  67342. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  67343. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  67344. // Compute final values by multiplying with 1/det
  67345. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  67346. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  67347. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  67348. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  67349. return this;
  67350. };
  67351. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  67352. var out = result.m;
  67353. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  67354. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  67355. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  67356. // cc.kmVec3Subtract(f, pCenter, pEye);
  67357. var f = SIMD.Float32x4.sub(center, eye);
  67358. // cc.kmVec3Normalize(f, f);
  67359. var tmp = SIMD.Float32x4.mul(f, f);
  67360. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  67361. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  67362. // cc.kmVec3Assign(up, pUp);
  67363. // cc.kmVec3Normalize(up, up);
  67364. tmp = SIMD.Float32x4.mul(up, up);
  67365. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  67366. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  67367. // cc.kmVec3Cross(s, f, up);
  67368. 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)));
  67369. // cc.kmVec3Normalize(s, s);
  67370. tmp = SIMD.Float32x4.mul(s, s);
  67371. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  67372. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  67373. // cc.kmVec3Cross(u, s, f);
  67374. 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)));
  67375. // cc.kmVec3Normalize(s, s);
  67376. tmp = SIMD.Float32x4.mul(s, s);
  67377. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  67378. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  67379. var zero = SIMD.Float32x4.splat(0.0);
  67380. s = SIMD.Float32x4.neg(s);
  67381. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  67382. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  67383. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  67384. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  67385. 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);
  67386. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  67387. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  67388. 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)))));
  67389. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  67390. 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)))));
  67391. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  67392. 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)))));
  67393. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  67394. 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)))));
  67395. };
  67396. return SIMDMatrix;
  67397. }());
  67398. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  67399. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  67400. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  67401. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  67402. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  67403. var SIMDHelper = (function () {
  67404. function SIMDHelper() {
  67405. }
  67406. Object.defineProperty(SIMDHelper, "IsEnabled", {
  67407. get: function () {
  67408. return SIMDHelper._isEnabled;
  67409. },
  67410. enumerable: true,
  67411. configurable: true
  67412. });
  67413. SIMDHelper.DisableSIMD = function () {
  67414. // Replace functions
  67415. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  67416. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  67417. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  67418. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  67419. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  67420. SIMDHelper._isEnabled = false;
  67421. };
  67422. SIMDHelper.EnableSIMD = function () {
  67423. if (self.SIMD === undefined) {
  67424. return;
  67425. }
  67426. // check if polyfills needed
  67427. if (!self.Math.fround) {
  67428. self.Math.fround = (function (array) { return function (x) {
  67429. return array[0] = x, array[0];
  67430. }; })(new Float32Array(1));
  67431. }
  67432. if (!self.Math.imul) {
  67433. self.Math.imul = function (a, b) {
  67434. var ah = (a >>> 16) & 0xffff;
  67435. var al = a & 0xffff;
  67436. var bh = (b >>> 16) & 0xffff;
  67437. var bl = b & 0xffff;
  67438. // the shift by 0 fixes the sign on the high part
  67439. // the final |0 converts the unsigned value into a signed value
  67440. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  67441. };
  67442. }
  67443. // Replace functions
  67444. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  67445. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  67446. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  67447. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  67448. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  67449. SIMDHelper._isEnabled = true;
  67450. };
  67451. SIMDHelper._isEnabled = false;
  67452. return SIMDHelper;
  67453. }());
  67454. BABYLON.SIMDHelper = SIMDHelper;
  67455. })(BABYLON || (BABYLON = {}));
  67456. //# sourceMappingURL=babylon.math.SIMD.js.map
  67457. var BABYLON;
  67458. (function (BABYLON) {
  67459. var VRDistortionCorrectionPostProcess = (function (_super) {
  67460. __extends(VRDistortionCorrectionPostProcess, _super);
  67461. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  67462. var _this = _super.call(this, name, "vrDistortionCorrection", [
  67463. 'LensCenter',
  67464. 'Scale',
  67465. 'ScaleIn',
  67466. 'HmdWarpParam'
  67467. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  67468. _this._isRightEye = isRightEye;
  67469. _this._distortionFactors = vrMetrics.distortionK;
  67470. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  67471. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  67472. _this.adaptScaleToCurrentViewport = true;
  67473. _this.onSizeChangedObservable.add(function () {
  67474. _this.aspectRatio = _this.width * .5 / _this.height;
  67475. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  67476. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  67477. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  67478. });
  67479. _this.onApplyObservable.add(function (effect) {
  67480. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  67481. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  67482. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  67483. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  67484. });
  67485. return _this;
  67486. }
  67487. return VRDistortionCorrectionPostProcess;
  67488. }(BABYLON.PostProcess));
  67489. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  67490. })(BABYLON || (BABYLON = {}));
  67491. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  67492. var BABYLON;
  67493. (function (BABYLON) {
  67494. var AnaglyphPostProcess = (function (_super) {
  67495. __extends(AnaglyphPostProcess, _super);
  67496. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  67497. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  67498. _this._passedProcess = rigCameras[0]._rigPostProcess;
  67499. _this.onApplyObservable.add(function (effect) {
  67500. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  67501. });
  67502. return _this;
  67503. }
  67504. return AnaglyphPostProcess;
  67505. }(BABYLON.PostProcess));
  67506. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  67507. })(BABYLON || (BABYLON = {}));
  67508. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  67509. var BABYLON;
  67510. (function (BABYLON) {
  67511. var StereoscopicInterlacePostProcess = (function (_super) {
  67512. __extends(StereoscopicInterlacePostProcess, _super);
  67513. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  67514. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  67515. _this._passedProcess = rigCameras[0]._rigPostProcess;
  67516. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  67517. _this.onSizeChangedObservable.add(function () {
  67518. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  67519. });
  67520. _this.onApplyObservable.add(function (effect) {
  67521. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  67522. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  67523. });
  67524. return _this;
  67525. }
  67526. return StereoscopicInterlacePostProcess;
  67527. }(BABYLON.PostProcess));
  67528. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  67529. })(BABYLON || (BABYLON = {}));
  67530. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  67531. var BABYLON;
  67532. (function (BABYLON) {
  67533. var FreeCameraDeviceOrientationInput = (function () {
  67534. function FreeCameraDeviceOrientationInput() {
  67535. var _this = this;
  67536. this._screenOrientationAngle = 0;
  67537. this._screenQuaternion = new BABYLON.Quaternion();
  67538. this._alpha = 0;
  67539. this._beta = 0;
  67540. this._gamma = 0;
  67541. this._orientationChanged = function () {
  67542. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  67543. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  67544. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  67545. };
  67546. this._deviceOrientation = function (evt) {
  67547. _this._alpha = evt.alpha;
  67548. _this._beta = evt.beta;
  67549. _this._gamma = evt.gamma;
  67550. };
  67551. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  67552. this._orientationChanged();
  67553. }
  67554. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  67555. get: function () {
  67556. return this._camera;
  67557. },
  67558. set: function (camera) {
  67559. this._camera = camera;
  67560. if (this._camera != null && !this._camera.rotationQuaternion) {
  67561. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  67562. }
  67563. },
  67564. enumerable: true,
  67565. configurable: true
  67566. });
  67567. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  67568. window.addEventListener("orientationchange", this._orientationChanged);
  67569. window.addEventListener("deviceorientation", this._deviceOrientation);
  67570. //In certain cases, the attach control is called AFTER orientation was changed,
  67571. //So this is needed.
  67572. this._orientationChanged();
  67573. };
  67574. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  67575. window.removeEventListener("orientationchange", this._orientationChanged);
  67576. window.removeEventListener("deviceorientation", this._deviceOrientation);
  67577. };
  67578. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  67579. //if no device orientation provided, don't update the rotation.
  67580. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  67581. if (!this._alpha)
  67582. return;
  67583. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  67584. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  67585. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  67586. //Mirror on XY Plane
  67587. this._camera.rotationQuaternion.z *= -1;
  67588. this._camera.rotationQuaternion.w *= -1;
  67589. };
  67590. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  67591. return "FreeCameraDeviceOrientationInput";
  67592. };
  67593. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  67594. return "deviceOrientation";
  67595. };
  67596. return FreeCameraDeviceOrientationInput;
  67597. }());
  67598. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  67599. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  67600. })(BABYLON || (BABYLON = {}));
  67601. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  67602. var BABYLON;
  67603. (function (BABYLON) {
  67604. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  67605. function ArcRotateCameraVRDeviceOrientationInput() {
  67606. this.alphaCorrection = 1;
  67607. this.betaCorrection = 1;
  67608. this.gammaCorrection = 1;
  67609. this._alpha = 0;
  67610. this._beta = 0;
  67611. this._gamma = 0;
  67612. this._dirty = false;
  67613. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  67614. }
  67615. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  67616. this.camera.attachControl(element, noPreventDefault);
  67617. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  67618. };
  67619. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  67620. this._alpha = +evt.alpha | 0;
  67621. this._beta = +evt.beta | 0;
  67622. this._gamma = +evt.gamma | 0;
  67623. this._dirty = true;
  67624. };
  67625. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  67626. if (this._dirty) {
  67627. this._dirty = false;
  67628. if (this._gamma < 0) {
  67629. this._gamma = 180 + this._gamma;
  67630. }
  67631. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  67632. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  67633. }
  67634. };
  67635. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  67636. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  67637. };
  67638. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  67639. return "ArcRotateCameraVRDeviceOrientationInput";
  67640. };
  67641. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  67642. return "VRDeviceOrientation";
  67643. };
  67644. return ArcRotateCameraVRDeviceOrientationInput;
  67645. }());
  67646. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  67647. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  67648. })(BABYLON || (BABYLON = {}));
  67649. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  67650. var BABYLON;
  67651. (function (BABYLON) {
  67652. var VRCameraMetrics = (function () {
  67653. function VRCameraMetrics() {
  67654. this.compensateDistortion = true;
  67655. }
  67656. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  67657. get: function () {
  67658. return this.hResolution / (2 * this.vResolution);
  67659. },
  67660. enumerable: true,
  67661. configurable: true
  67662. });
  67663. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  67664. get: function () {
  67665. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  67666. },
  67667. enumerable: true,
  67668. configurable: true
  67669. });
  67670. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  67671. get: function () {
  67672. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  67673. var h = (4 * meters) / this.hScreenSize;
  67674. return BABYLON.Matrix.Translation(h, 0, 0);
  67675. },
  67676. enumerable: true,
  67677. configurable: true
  67678. });
  67679. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  67680. get: function () {
  67681. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  67682. var h = (4 * meters) / this.hScreenSize;
  67683. return BABYLON.Matrix.Translation(-h, 0, 0);
  67684. },
  67685. enumerable: true,
  67686. configurable: true
  67687. });
  67688. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  67689. get: function () {
  67690. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  67691. },
  67692. enumerable: true,
  67693. configurable: true
  67694. });
  67695. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  67696. get: function () {
  67697. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  67698. },
  67699. enumerable: true,
  67700. configurable: true
  67701. });
  67702. VRCameraMetrics.GetDefault = function () {
  67703. var result = new VRCameraMetrics();
  67704. result.hResolution = 1280;
  67705. result.vResolution = 800;
  67706. result.hScreenSize = 0.149759993;
  67707. result.vScreenSize = 0.0935999975;
  67708. result.vScreenCenter = 0.0467999987;
  67709. result.eyeToScreenDistance = 0.0410000011;
  67710. result.lensSeparationDistance = 0.0635000020;
  67711. result.interpupillaryDistance = 0.0640000030;
  67712. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  67713. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  67714. result.postProcessScaleFactor = 1.714605507808412;
  67715. result.lensCenterOffset = 0.151976421;
  67716. return result;
  67717. };
  67718. return VRCameraMetrics;
  67719. }());
  67720. BABYLON.VRCameraMetrics = VRCameraMetrics;
  67721. })(BABYLON || (BABYLON = {}));
  67722. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  67723. var BABYLON;
  67724. (function (BABYLON) {
  67725. var WebVRFreeCamera = (function (_super) {
  67726. __extends(WebVRFreeCamera, _super);
  67727. function WebVRFreeCamera(name, position, scene, webVROptions) {
  67728. if (webVROptions === void 0) { webVROptions = {}; }
  67729. var _this = _super.call(this, name, position, scene) || this;
  67730. _this.webVROptions = webVROptions;
  67731. _this._vrDevice = null;
  67732. _this.rawPose = null;
  67733. _this._specsVersion = "1.1";
  67734. _this._attached = false;
  67735. _this._descendants = [];
  67736. _this.devicePosition = BABYLON.Vector3.Zero();
  67737. _this.deviceScaleFactor = 1;
  67738. _this.controllers = [];
  67739. _this.onControllersAttachedObservable = new BABYLON.Observable();
  67740. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  67741. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  67742. _this.minZ = 0.1;
  67743. //legacy support - the compensation boolean was removed.
  67744. if (arguments.length === 5) {
  67745. _this.webVROptions = arguments[4];
  67746. }
  67747. // default webVR options
  67748. if (_this.webVROptions.trackPosition == undefined) {
  67749. _this.webVROptions.trackPosition = true;
  67750. }
  67751. if (_this.webVROptions.controllerMeshes == undefined) {
  67752. _this.webVROptions.controllerMeshes = true;
  67753. }
  67754. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  67755. _this.webVROptions.defaultLightingOnControllers = true;
  67756. }
  67757. _this.rotationQuaternion = new BABYLON.Quaternion();
  67758. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  67759. if (_this.webVROptions && _this.webVROptions.positionScale) {
  67760. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  67761. }
  67762. //enable VR
  67763. var engine = _this.getEngine();
  67764. _this._onVREnabled = function (success) { if (success) {
  67765. _this.initControllers();
  67766. } };
  67767. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  67768. engine.initWebVR().add(function (event) {
  67769. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  67770. return;
  67771. }
  67772. _this._vrDevice = event.vrDisplay;
  67773. //reset the rig parameters.
  67774. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  67775. if (_this._attached) {
  67776. _this.getEngine().enableVR();
  67777. }
  67778. });
  67779. if (typeof (VRFrameData) !== "undefined")
  67780. _this._frameData = new VRFrameData();
  67781. /**
  67782. * The idea behind the following lines:
  67783. * objects that have the camera as parent should actually have the rig cameras as a parent.
  67784. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  67785. * the second will not show it correctly.
  67786. *
  67787. * To solve this - each object that has the camera as parent will be added to a protected array.
  67788. * When the rig camera renders, it will take this array and set all of those to be its children.
  67789. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  67790. * Amazing!
  67791. */
  67792. scene.onBeforeCameraRenderObservable.add(function (camera) {
  67793. if (camera.parent === _this && _this.rigParenting) {
  67794. _this._descendants = _this.getDescendants(true, function (n) {
  67795. // don't take the cameras or the controllers!
  67796. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  67797. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  67798. return !isController && !isRigCamera;
  67799. });
  67800. _this._descendants.forEach(function (node) {
  67801. node.parent = camera;
  67802. });
  67803. }
  67804. });
  67805. scene.onAfterCameraRenderObservable.add(function (camera) {
  67806. if (camera.parent === _this && _this.rigParenting) {
  67807. _this._descendants.forEach(function (node) {
  67808. node.parent = _this;
  67809. });
  67810. }
  67811. });
  67812. return _this;
  67813. }
  67814. WebVRFreeCamera.prototype.dispose = function () {
  67815. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  67816. _super.prototype.dispose.call(this);
  67817. };
  67818. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  67819. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  67820. var gp = _a[_i];
  67821. if (gp.hand === name) {
  67822. return gp;
  67823. }
  67824. }
  67825. return undefined;
  67826. };
  67827. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  67828. get: function () {
  67829. if (!this._leftController) {
  67830. this._leftController = this.getControllerByName("left");
  67831. }
  67832. return this._leftController;
  67833. },
  67834. enumerable: true,
  67835. configurable: true
  67836. });
  67837. ;
  67838. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  67839. get: function () {
  67840. if (!this._rightController) {
  67841. this._rightController = this.getControllerByName("right");
  67842. }
  67843. return this._rightController;
  67844. },
  67845. enumerable: true,
  67846. configurable: true
  67847. });
  67848. ;
  67849. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  67850. if (length === void 0) { length = 100; }
  67851. if (this.leftCamera) {
  67852. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  67853. }
  67854. else {
  67855. return _super.prototype.getForwardRay.call(this, length);
  67856. }
  67857. };
  67858. WebVRFreeCamera.prototype._checkInputs = function () {
  67859. if (this._vrDevice && this._vrDevice.isPresenting) {
  67860. this._vrDevice.getFrameData(this._frameData);
  67861. this.updateFromDevice(this._frameData.pose);
  67862. }
  67863. _super.prototype._checkInputs.call(this);
  67864. };
  67865. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  67866. if (poseData && poseData.orientation) {
  67867. this.rawPose = poseData;
  67868. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  67869. if (this.getScene().useRightHandedSystem) {
  67870. this.deviceRotationQuaternion.z *= -1;
  67871. this.deviceRotationQuaternion.w *= -1;
  67872. }
  67873. if (this.webVROptions.trackPosition && this.rawPose.position) {
  67874. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  67875. if (this.getScene().useRightHandedSystem) {
  67876. this.devicePosition.z *= -1;
  67877. }
  67878. }
  67879. }
  67880. };
  67881. /**
  67882. * WebVR's attach control will start broadcasting frames to the device.
  67883. * Note that in certain browsers (chrome for example) this function must be called
  67884. * within a user-interaction callback. Example:
  67885. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  67886. *
  67887. * @param {HTMLElement} element
  67888. * @param {boolean} [noPreventDefault]
  67889. *
  67890. * @memberOf WebVRFreeCamera
  67891. */
  67892. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  67893. _super.prototype.attachControl.call(this, element, noPreventDefault);
  67894. this._attached = true;
  67895. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  67896. if (this._vrDevice) {
  67897. this.getEngine().enableVR();
  67898. }
  67899. };
  67900. WebVRFreeCamera.prototype.detachControl = function (element) {
  67901. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  67902. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  67903. _super.prototype.detachControl.call(this, element);
  67904. this._attached = false;
  67905. this.getEngine().disableVR();
  67906. };
  67907. WebVRFreeCamera.prototype.getClassName = function () {
  67908. return "WebVRFreeCamera";
  67909. };
  67910. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  67911. //uses the vrDisplay's "resetPose()".
  67912. //pitch and roll won't be affected.
  67913. this._vrDevice.resetPose();
  67914. };
  67915. WebVRFreeCamera.prototype._updateRigCameras = function () {
  67916. var camLeft = this._rigCameras[0];
  67917. var camRight = this._rigCameras[1];
  67918. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  67919. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  67920. camLeft.position.copyFrom(this.devicePosition);
  67921. camRight.position.copyFrom(this.devicePosition);
  67922. };
  67923. /**
  67924. * This function is called by the two RIG cameras.
  67925. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  67926. */
  67927. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  67928. var _this = this;
  67929. //WebVR 1.1
  67930. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  67931. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  67932. if (!this.getScene().useRightHandedSystem) {
  67933. [2, 6, 8, 9, 14].forEach(function (num) {
  67934. _this._webvrViewMatrix.m[num] *= -1;
  67935. });
  67936. }
  67937. // update the camera rotation matrix
  67938. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  67939. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  67940. // Computing target and final matrix
  67941. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  67942. var parentCamera = this._cameraRigParams["parentCamera"];
  67943. // should the view matrix be updated with scale and position offset?
  67944. if (parentCamera.deviceScaleFactor !== 1) {
  67945. this._webvrViewMatrix.invert();
  67946. // scale the position, if set
  67947. if (parentCamera.deviceScaleFactor) {
  67948. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  67949. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  67950. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  67951. }
  67952. this._webvrViewMatrix.invert();
  67953. }
  67954. return this._webvrViewMatrix;
  67955. };
  67956. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  67957. var _this = this;
  67958. var parentCamera = this.parent;
  67959. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  67960. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  67961. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  67962. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  67963. //babylon compatible matrix
  67964. if (!this.getScene().useRightHandedSystem) {
  67965. [8, 9, 10, 11].forEach(function (num) {
  67966. _this._projectionMatrix.m[num] *= -1;
  67967. });
  67968. }
  67969. return this._projectionMatrix;
  67970. };
  67971. WebVRFreeCamera.prototype.initControllers = function () {
  67972. var _this = this;
  67973. this.controllers = [];
  67974. var manager = this.getScene().gamepadManager;
  67975. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  67976. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  67977. var webVrController = gamepad;
  67978. if (webVrController.defaultModel) {
  67979. webVrController.defaultModel.setEnabled(false);
  67980. }
  67981. }
  67982. });
  67983. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  67984. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  67985. var webVrController_1 = gamepad;
  67986. if (_this.webVROptions.controllerMeshes) {
  67987. if (webVrController_1.defaultModel) {
  67988. webVrController_1.defaultModel.setEnabled(true);
  67989. }
  67990. else {
  67991. // Load the meshes
  67992. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  67993. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  67994. if (_this.webVROptions.defaultLightingOnControllers) {
  67995. if (!_this._lightOnControllers) {
  67996. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  67997. }
  67998. var activateLightOnSubMeshes_1 = function (mesh, light) {
  67999. var children = mesh.getChildren();
  68000. if (children.length !== 0) {
  68001. children.forEach(function (mesh) {
  68002. light.includedOnlyMeshes.push(mesh);
  68003. activateLightOnSubMeshes_1(mesh, light);
  68004. });
  68005. }
  68006. };
  68007. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  68008. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  68009. }
  68010. });
  68011. }
  68012. }
  68013. webVrController_1.attachToPoseControlledCamera(_this);
  68014. // since this is async - sanity check. Is the controller already stored?
  68015. if (_this.controllers.indexOf(webVrController_1) === -1) {
  68016. //add to the controllers array
  68017. _this.controllers.push(webVrController_1);
  68018. //did we find enough controllers? Great! let the developer know.
  68019. if (_this.controllers.length >= 2) {
  68020. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  68021. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  68022. // So we're overriding setting left & right manually to be sure
  68023. var firstViveWandDetected = false;
  68024. for (var i = 0; i < _this.controllers.length; i++) {
  68025. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  68026. if (!firstViveWandDetected) {
  68027. firstViveWandDetected = true;
  68028. _this.controllers[i].hand = "left";
  68029. }
  68030. else {
  68031. _this.controllers[i].hand = "right";
  68032. }
  68033. }
  68034. }
  68035. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  68036. }
  68037. }
  68038. }
  68039. });
  68040. };
  68041. return WebVRFreeCamera;
  68042. }(BABYLON.FreeCamera));
  68043. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  68044. })(BABYLON || (BABYLON = {}));
  68045. //# sourceMappingURL=babylon.webVRCamera.js.map
  68046. /// <reference path="babylon.freeCamera.ts" />
  68047. var BABYLON;
  68048. (function (BABYLON) {
  68049. // We're mainly based on the logic defined into the FreeCamera code
  68050. var DeviceOrientationCamera = (function (_super) {
  68051. __extends(DeviceOrientationCamera, _super);
  68052. function DeviceOrientationCamera(name, position, scene) {
  68053. var _this = _super.call(this, name, position, scene) || this;
  68054. _this._quaternionCache = new BABYLON.Quaternion();
  68055. _this.inputs.addDeviceOrientation();
  68056. return _this;
  68057. }
  68058. DeviceOrientationCamera.prototype.getClassName = function () {
  68059. return "DeviceOrientationCamera";
  68060. };
  68061. DeviceOrientationCamera.prototype._checkInputs = function () {
  68062. _super.prototype._checkInputs.call(this);
  68063. this._quaternionCache.copyFrom(this.rotationQuaternion);
  68064. if (this._initialQuaternion) {
  68065. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  68066. }
  68067. };
  68068. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  68069. var _this = this;
  68070. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  68071. //can only work if this camera has a rotation quaternion already.
  68072. if (!this.rotationQuaternion)
  68073. return;
  68074. if (!this._initialQuaternion) {
  68075. this._initialQuaternion = new BABYLON.Quaternion();
  68076. }
  68077. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  68078. ['x', 'y', 'z'].forEach(function (axisName) {
  68079. if (!axis[axisName]) {
  68080. _this._initialQuaternion[axisName] = 0;
  68081. }
  68082. else {
  68083. _this._initialQuaternion[axisName] *= -1;
  68084. }
  68085. });
  68086. this._initialQuaternion.normalize();
  68087. //force rotation update
  68088. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  68089. };
  68090. return DeviceOrientationCamera;
  68091. }(BABYLON.FreeCamera));
  68092. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  68093. })(BABYLON || (BABYLON = {}));
  68094. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  68095. var BABYLON;
  68096. (function (BABYLON) {
  68097. var VRDeviceOrientationFreeCamera = (function (_super) {
  68098. __extends(VRDeviceOrientationFreeCamera, _super);
  68099. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  68100. if (compensateDistortion === void 0) { compensateDistortion = true; }
  68101. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  68102. var _this = _super.call(this, name, position, scene) || this;
  68103. vrCameraMetrics.compensateDistortion = compensateDistortion;
  68104. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  68105. return _this;
  68106. }
  68107. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  68108. return "VRDeviceOrientationFreeCamera";
  68109. };
  68110. return VRDeviceOrientationFreeCamera;
  68111. }(BABYLON.DeviceOrientationCamera));
  68112. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  68113. var VRDeviceOrientationGamepadCamera = (function (_super) {
  68114. __extends(VRDeviceOrientationGamepadCamera, _super);
  68115. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  68116. if (compensateDistortion === void 0) { compensateDistortion = true; }
  68117. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  68118. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  68119. _this.inputs.addGamepad();
  68120. return _this;
  68121. }
  68122. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  68123. return "VRDeviceOrientationGamepadCamera";
  68124. };
  68125. return VRDeviceOrientationGamepadCamera;
  68126. }(VRDeviceOrientationFreeCamera));
  68127. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  68128. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  68129. __extends(VRDeviceOrientationArcRotateCamera, _super);
  68130. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  68131. if (compensateDistortion === void 0) { compensateDistortion = true; }
  68132. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  68133. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  68134. vrCameraMetrics.compensateDistortion = compensateDistortion;
  68135. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  68136. _this.inputs.addVRDeviceOrientation();
  68137. return _this;
  68138. }
  68139. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  68140. return "VRDeviceOrientationArcRotateCamera";
  68141. };
  68142. return VRDeviceOrientationArcRotateCamera;
  68143. }(BABYLON.ArcRotateCamera));
  68144. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  68145. })(BABYLON || (BABYLON = {}));
  68146. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  68147. /// <reference path="babylon.freeCamera.ts" />
  68148. /// <reference path="babylon.arcRotateCamera.ts" />
  68149. /// <reference path="babylon.gamepadCamera.ts" />
  68150. /// <reference path="babylon.universalCamera.ts" />
  68151. var BABYLON;
  68152. (function (BABYLON) {
  68153. var AnaglyphFreeCamera = (function (_super) {
  68154. __extends(AnaglyphFreeCamera, _super);
  68155. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  68156. var _this = _super.call(this, name, position, scene) || this;
  68157. _this.interaxialDistance = interaxialDistance;
  68158. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  68159. return _this;
  68160. }
  68161. AnaglyphFreeCamera.prototype.getClassName = function () {
  68162. return "AnaglyphFreeCamera";
  68163. };
  68164. return AnaglyphFreeCamera;
  68165. }(BABYLON.FreeCamera));
  68166. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  68167. var AnaglyphArcRotateCamera = (function (_super) {
  68168. __extends(AnaglyphArcRotateCamera, _super);
  68169. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  68170. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  68171. _this.interaxialDistance = interaxialDistance;
  68172. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  68173. return _this;
  68174. }
  68175. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  68176. return "AnaglyphArcRotateCamera";
  68177. };
  68178. return AnaglyphArcRotateCamera;
  68179. }(BABYLON.ArcRotateCamera));
  68180. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  68181. var AnaglyphGamepadCamera = (function (_super) {
  68182. __extends(AnaglyphGamepadCamera, _super);
  68183. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  68184. var _this = _super.call(this, name, position, scene) || this;
  68185. _this.interaxialDistance = interaxialDistance;
  68186. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  68187. return _this;
  68188. }
  68189. AnaglyphGamepadCamera.prototype.getClassName = function () {
  68190. return "AnaglyphGamepadCamera";
  68191. };
  68192. return AnaglyphGamepadCamera;
  68193. }(BABYLON.GamepadCamera));
  68194. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  68195. var AnaglyphUniversalCamera = (function (_super) {
  68196. __extends(AnaglyphUniversalCamera, _super);
  68197. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  68198. var _this = _super.call(this, name, position, scene) || this;
  68199. _this.interaxialDistance = interaxialDistance;
  68200. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  68201. return _this;
  68202. }
  68203. AnaglyphUniversalCamera.prototype.getClassName = function () {
  68204. return "AnaglyphUniversalCamera";
  68205. };
  68206. return AnaglyphUniversalCamera;
  68207. }(BABYLON.UniversalCamera));
  68208. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  68209. var StereoscopicFreeCamera = (function (_super) {
  68210. __extends(StereoscopicFreeCamera, _super);
  68211. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  68212. var _this = _super.call(this, name, position, scene) || this;
  68213. _this.interaxialDistance = interaxialDistance;
  68214. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  68215. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  68216. return _this;
  68217. }
  68218. StereoscopicFreeCamera.prototype.getClassName = function () {
  68219. return "StereoscopicFreeCamera";
  68220. };
  68221. return StereoscopicFreeCamera;
  68222. }(BABYLON.FreeCamera));
  68223. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  68224. var StereoscopicArcRotateCamera = (function (_super) {
  68225. __extends(StereoscopicArcRotateCamera, _super);
  68226. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  68227. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  68228. _this.interaxialDistance = interaxialDistance;
  68229. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  68230. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  68231. return _this;
  68232. }
  68233. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  68234. return "StereoscopicArcRotateCamera";
  68235. };
  68236. return StereoscopicArcRotateCamera;
  68237. }(BABYLON.ArcRotateCamera));
  68238. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  68239. var StereoscopicGamepadCamera = (function (_super) {
  68240. __extends(StereoscopicGamepadCamera, _super);
  68241. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  68242. var _this = _super.call(this, name, position, scene) || this;
  68243. _this.interaxialDistance = interaxialDistance;
  68244. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  68245. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  68246. return _this;
  68247. }
  68248. StereoscopicGamepadCamera.prototype.getClassName = function () {
  68249. return "StereoscopicGamepadCamera";
  68250. };
  68251. return StereoscopicGamepadCamera;
  68252. }(BABYLON.GamepadCamera));
  68253. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  68254. var StereoscopicUniversalCamera = (function (_super) {
  68255. __extends(StereoscopicUniversalCamera, _super);
  68256. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  68257. var _this = _super.call(this, name, position, scene) || this;
  68258. _this.interaxialDistance = interaxialDistance;
  68259. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  68260. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  68261. return _this;
  68262. }
  68263. StereoscopicUniversalCamera.prototype.getClassName = function () {
  68264. return "StereoscopicUniversalCamera";
  68265. };
  68266. return StereoscopicUniversalCamera;
  68267. }(BABYLON.UniversalCamera));
  68268. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  68269. })(BABYLON || (BABYLON = {}));
  68270. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  68271. var BABYLON;
  68272. (function (BABYLON) {
  68273. var VRExperienceHelper = (function () {
  68274. function VRExperienceHelper(scene, webVROptions) {
  68275. if (webVROptions === void 0) { webVROptions = {}; }
  68276. var _this = this;
  68277. this.webVROptions = webVROptions;
  68278. // Can the system support WebVR, even if a headset isn't plugged in?
  68279. this._webVRsupported = false;
  68280. // If WebVR is supported, is a headset plugged in and are we ready to present?
  68281. this._webVRready = false;
  68282. // Are we waiting for the requestPresent callback to complete?
  68283. this._webVRrequesting = false;
  68284. // Are we presenting to the headset right now?
  68285. this._webVRpresenting = false;
  68286. // Are we presenting in the fullscreen fallback?
  68287. this._fullscreenVRpresenting = false;
  68288. this._scene = scene;
  68289. if (!this._scene.activeCamera || isNaN(this._scene.activeCamera.position.x)) {
  68290. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  68291. }
  68292. else {
  68293. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  68294. if (scene.activeCamera.rotation) {
  68295. this._deviceOrientationCamera.rotation = scene.activeCamera.rotation.clone();
  68296. }
  68297. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  68298. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  68299. }
  68300. this._scene.activeCamera = this._deviceOrientationCamera;
  68301. this._position = this._scene.activeCamera.position;
  68302. this._canvas = scene.getEngine().getRenderingCanvas();
  68303. this._scene.activeCamera.attachControl(this._canvas);
  68304. this._btnVR = document.createElement("BUTTON");
  68305. this._btnVR.className = "babylonVRicon";
  68306. this._btnVR.id = "babylonVRiconbtn";
  68307. this._btnVR.title = "Click to switch to VR";
  68308. 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) }";
  68309. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  68310. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  68311. // css += ".babylonVRicon.vrdisplaysupported { }";
  68312. // css += ".babylonVRicon.vrdisplayready { }";
  68313. // css += ".babylonVRicon.vrdisplayrequesting { }";
  68314. var style = document.createElement('style');
  68315. style.appendChild(document.createTextNode(css));
  68316. document.getElementsByTagName('head')[0].appendChild(style);
  68317. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  68318. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  68319. this._btnVR.addEventListener("click", function () {
  68320. _this.enterVR();
  68321. });
  68322. window.addEventListener("resize", function () {
  68323. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  68324. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  68325. if (_this._fullscreenVRpresenting && _this._webVRready) {
  68326. _this.exitVR();
  68327. }
  68328. });
  68329. document.addEventListener("fullscreenchange", function () { _this._onFullscreenChange(); }, false);
  68330. document.addEventListener("mozfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  68331. document.addEventListener("webkitfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  68332. document.addEventListener("msfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  68333. document.body.appendChild(this._btnVR);
  68334. // Exiting VR mode using 'ESC' key on desktop
  68335. this._onKeyDown = function (event) {
  68336. if (event.keyCode === 27 && _this.isInVRMode()) {
  68337. _this.exitVR();
  68338. }
  68339. };
  68340. document.addEventListener("keydown", this._onKeyDown);
  68341. // Exiting VR mode double tapping the touch screen
  68342. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  68343. if (_this.isInVRMode()) {
  68344. _this.exitVR();
  68345. if (_this._fullscreenVRpresenting) {
  68346. _this._scene.getEngine().switchFullscreen(true);
  68347. }
  68348. }
  68349. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  68350. // Listen for WebVR display changes
  68351. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  68352. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  68353. this._onVRRequestPresentStart = function () {
  68354. _this._webVRrequesting = true;
  68355. _this.updateButtonVisibility();
  68356. };
  68357. this._onVRRequestPresentComplete = function (success) {
  68358. _this._webVRrequesting = false;
  68359. _this.updateButtonVisibility();
  68360. };
  68361. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  68362. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  68363. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  68364. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  68365. // Create the cameras
  68366. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  68367. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  68368. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  68369. this.updateButtonVisibility();
  68370. }
  68371. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  68372. if (this.onControllerMeshLoaded) {
  68373. this.onControllerMeshLoaded(webVRController);
  68374. }
  68375. };
  68376. VRExperienceHelper.prototype._onFullscreenChange = function () {
  68377. if (document.fullscreen !== undefined) {
  68378. this._fullscreenVRpresenting = document.fullscreen;
  68379. }
  68380. else if (document.mozFullScreen !== undefined) {
  68381. this._fullscreenVRpresenting = document.mozFullScreen;
  68382. }
  68383. else if (document.webkitIsFullScreen !== undefined) {
  68384. this._fullscreenVRpresenting = document.webkitIsFullScreen;
  68385. }
  68386. else if (document.msIsFullScreen !== undefined) {
  68387. this._fullscreenVRpresenting = document.msIsFullScreen;
  68388. }
  68389. if (!this._fullscreenVRpresenting) {
  68390. this.exitVR();
  68391. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  68392. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  68393. }
  68394. };
  68395. VRExperienceHelper.prototype.isInVRMode = function () {
  68396. return this._webVRpresenting || this._fullscreenVRpresenting;
  68397. };
  68398. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  68399. var vrDisplay = this._scene.getEngine().getVRDevice();
  68400. if (vrDisplay) {
  68401. var wasPresenting = this._webVRpresenting;
  68402. // A VR display is connected
  68403. this._webVRpresenting = vrDisplay.isPresenting;
  68404. if (wasPresenting && !this._webVRpresenting)
  68405. this.exitVR();
  68406. }
  68407. else {
  68408. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  68409. }
  68410. this.updateButtonVisibility();
  68411. };
  68412. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  68413. this._webVRsupported = eventArgs.vrSupported;
  68414. this._webVRready = !!eventArgs.vrDisplay;
  68415. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  68416. this.updateButtonVisibility();
  68417. };
  68418. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  68419. if (!this._btnVR) {
  68420. return;
  68421. }
  68422. this._btnVR.className = "babylonVRicon";
  68423. if (this.isInVRMode()) {
  68424. this._btnVR.className += " vrdisplaypresenting";
  68425. }
  68426. else {
  68427. if (this._webVRready)
  68428. this._btnVR.className += " vrdisplayready";
  68429. if (this._webVRsupported)
  68430. this._btnVR.className += " vrdisplaysupported";
  68431. if (this._webVRrequesting)
  68432. this._btnVR.className += " vrdisplayrequesting";
  68433. }
  68434. };
  68435. /**
  68436. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  68437. * Otherwise, will use the fullscreen API.
  68438. */
  68439. VRExperienceHelper.prototype.enterVR = function () {
  68440. if (this.onEnteringVR) {
  68441. this.onEnteringVR();
  68442. }
  68443. if (this._webVRrequesting)
  68444. return;
  68445. // If WebVR is supported and a headset is connected
  68446. if (this._webVRready) {
  68447. if (!this._webVRpresenting) {
  68448. this._webVRCamera.position = this._position;
  68449. this._scene.activeCamera = this._webVRCamera;
  68450. }
  68451. }
  68452. else {
  68453. this._vrDeviceOrientationCamera.position = this._position;
  68454. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  68455. this._scene.getEngine().switchFullscreen(true);
  68456. this.updateButtonVisibility();
  68457. }
  68458. this._scene.activeCamera.attachControl(this._canvas);
  68459. };
  68460. /**
  68461. * Attempt to exit VR, or fullscreen.
  68462. */
  68463. VRExperienceHelper.prototype.exitVR = function () {
  68464. if (this.onExitingVR) {
  68465. this.onExitingVR();
  68466. }
  68467. if (this._webVRpresenting) {
  68468. this._scene.getEngine().disableVR();
  68469. }
  68470. if (this._scene.activeCamera) {
  68471. this._position = this._scene.activeCamera.position;
  68472. }
  68473. this._deviceOrientationCamera.position = this._position;
  68474. this._scene.activeCamera = this._deviceOrientationCamera;
  68475. this._scene.activeCamera.attachControl(this._canvas);
  68476. this.updateButtonVisibility();
  68477. };
  68478. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  68479. get: function () {
  68480. return this._position;
  68481. },
  68482. set: function (value) {
  68483. this._position = value;
  68484. this._scene.activeCamera.position = value;
  68485. },
  68486. enumerable: true,
  68487. configurable: true
  68488. });
  68489. VRExperienceHelper.prototype.dispose = function () {
  68490. if (this.isInVRMode()) {
  68491. this.exitVR();
  68492. }
  68493. this._deviceOrientationCamera.dispose();
  68494. if (this._webVRCamera) {
  68495. this._webVRCamera.dispose();
  68496. }
  68497. if (this._vrDeviceOrientationCamera) {
  68498. this._vrDeviceOrientationCamera.dispose();
  68499. }
  68500. document.body.removeChild(this._btnVR);
  68501. document.removeEventListener("keydown", this._onKeyDown);
  68502. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  68503. };
  68504. VRExperienceHelper.prototype.getClassName = function () {
  68505. return "VRExperienceHelper";
  68506. };
  68507. return VRExperienceHelper;
  68508. }());
  68509. BABYLON.VRExperienceHelper = VRExperienceHelper;
  68510. })(BABYLON || (BABYLON = {}));
  68511. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  68512. // Mainly based on these 2 articles :
  68513. // 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
  68514. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  68515. var BABYLON;
  68516. (function (BABYLON) {
  68517. var JoystickAxis;
  68518. (function (JoystickAxis) {
  68519. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  68520. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  68521. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  68522. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  68523. var VirtualJoystick = (function () {
  68524. function VirtualJoystick(leftJoystick) {
  68525. var _this = this;
  68526. if (leftJoystick) {
  68527. this._leftJoystick = true;
  68528. }
  68529. else {
  68530. this._leftJoystick = false;
  68531. }
  68532. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  68533. VirtualJoystick._globalJoystickIndex++;
  68534. // By default left & right arrow keys are moving the X
  68535. // and up & down keys are moving the Y
  68536. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  68537. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  68538. this.reverseLeftRight = false;
  68539. this.reverseUpDown = false;
  68540. // collections of pointers
  68541. this._touches = new BABYLON.StringDictionary();
  68542. this.deltaPosition = BABYLON.Vector3.Zero();
  68543. this._joystickSensibility = 25;
  68544. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  68545. this._rotationSpeed = 25;
  68546. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  68547. this._rotateOnAxisRelativeToMesh = false;
  68548. this._onResize = function (evt) {
  68549. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  68550. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  68551. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  68552. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  68553. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  68554. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  68555. };
  68556. // injecting a canvas element on top of the canvas 3D game
  68557. if (!VirtualJoystick.vjCanvas) {
  68558. window.addEventListener("resize", this._onResize, false);
  68559. VirtualJoystick.vjCanvas = document.createElement("canvas");
  68560. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  68561. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  68562. VirtualJoystick.vjCanvas.width = window.innerWidth;
  68563. VirtualJoystick.vjCanvas.height = window.innerHeight;
  68564. VirtualJoystick.vjCanvas.style.width = "100%";
  68565. VirtualJoystick.vjCanvas.style.height = "100%";
  68566. VirtualJoystick.vjCanvas.style.position = "absolute";
  68567. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  68568. VirtualJoystick.vjCanvas.style.top = "0px";
  68569. VirtualJoystick.vjCanvas.style.left = "0px";
  68570. VirtualJoystick.vjCanvas.style.zIndex = "5";
  68571. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  68572. // Support for jQuery PEP polyfill
  68573. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  68574. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  68575. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  68576. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  68577. document.body.appendChild(VirtualJoystick.vjCanvas);
  68578. }
  68579. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  68580. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  68581. this.pressed = false;
  68582. // default joystick color
  68583. this._joystickColor = "cyan";
  68584. this._joystickPointerID = -1;
  68585. // current joystick position
  68586. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  68587. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  68588. // origin joystick position
  68589. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  68590. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  68591. this._onPointerDownHandlerRef = function (evt) {
  68592. _this._onPointerDown(evt);
  68593. };
  68594. this._onPointerMoveHandlerRef = function (evt) {
  68595. _this._onPointerMove(evt);
  68596. };
  68597. this._onPointerOutHandlerRef = function (evt) {
  68598. _this._onPointerUp(evt);
  68599. };
  68600. this._onPointerUpHandlerRef = function (evt) {
  68601. _this._onPointerUp(evt);
  68602. };
  68603. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  68604. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  68605. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  68606. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  68607. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  68608. evt.preventDefault(); // Disables system menu
  68609. }, false);
  68610. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  68611. }
  68612. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  68613. this._joystickSensibility = newJoystickSensibility;
  68614. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  68615. };
  68616. VirtualJoystick.prototype._onPointerDown = function (e) {
  68617. var positionOnScreenCondition;
  68618. e.preventDefault();
  68619. if (this._leftJoystick === true) {
  68620. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  68621. }
  68622. else {
  68623. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  68624. }
  68625. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  68626. // First contact will be dedicated to the virtual joystick
  68627. this._joystickPointerID = e.pointerId;
  68628. this._joystickPointerStartPos.x = e.clientX;
  68629. this._joystickPointerStartPos.y = e.clientY;
  68630. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  68631. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  68632. this._deltaJoystickVector.x = 0;
  68633. this._deltaJoystickVector.y = 0;
  68634. this.pressed = true;
  68635. this._touches.add(e.pointerId.toString(), e);
  68636. }
  68637. else {
  68638. // You can only trigger the action buttons with a joystick declared
  68639. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  68640. this._action();
  68641. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  68642. }
  68643. }
  68644. };
  68645. VirtualJoystick.prototype._onPointerMove = function (e) {
  68646. // If the current pointer is the one associated to the joystick (first touch contact)
  68647. if (this._joystickPointerID == e.pointerId) {
  68648. this._joystickPointerPos.x = e.clientX;
  68649. this._joystickPointerPos.y = e.clientY;
  68650. this._deltaJoystickVector = this._joystickPointerPos.clone();
  68651. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  68652. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  68653. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  68654. switch (this._axisTargetedByLeftAndRight) {
  68655. case JoystickAxis.X:
  68656. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  68657. break;
  68658. case JoystickAxis.Y:
  68659. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  68660. break;
  68661. case JoystickAxis.Z:
  68662. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  68663. break;
  68664. }
  68665. var directionUpDown = this.reverseUpDown ? 1 : -1;
  68666. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  68667. switch (this._axisTargetedByUpAndDown) {
  68668. case JoystickAxis.X:
  68669. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  68670. break;
  68671. case JoystickAxis.Y:
  68672. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  68673. break;
  68674. case JoystickAxis.Z:
  68675. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  68676. break;
  68677. }
  68678. }
  68679. else {
  68680. var data = this._touches.get(e.pointerId.toString());
  68681. if (data) {
  68682. data.x = e.clientX;
  68683. data.y = e.clientY;
  68684. }
  68685. }
  68686. };
  68687. VirtualJoystick.prototype._onPointerUp = function (e) {
  68688. if (this._joystickPointerID == e.pointerId) {
  68689. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  68690. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  68691. this._joystickPointerID = -1;
  68692. this.pressed = false;
  68693. }
  68694. else {
  68695. var touch = this._touches.get(e.pointerId.toString());
  68696. if (touch) {
  68697. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  68698. }
  68699. }
  68700. this._deltaJoystickVector.x = 0;
  68701. this._deltaJoystickVector.y = 0;
  68702. this._touches.remove(e.pointerId.toString());
  68703. };
  68704. /**
  68705. * Change the color of the virtual joystick
  68706. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  68707. */
  68708. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  68709. this._joystickColor = newColor;
  68710. };
  68711. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  68712. this._action = action;
  68713. };
  68714. // Define which axis you'd like to control for left & right
  68715. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  68716. switch (axis) {
  68717. case JoystickAxis.X:
  68718. case JoystickAxis.Y:
  68719. case JoystickAxis.Z:
  68720. this._axisTargetedByLeftAndRight = axis;
  68721. break;
  68722. default:
  68723. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  68724. break;
  68725. }
  68726. };
  68727. // Define which axis you'd like to control for up & down
  68728. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  68729. switch (axis) {
  68730. case JoystickAxis.X:
  68731. case JoystickAxis.Y:
  68732. case JoystickAxis.Z:
  68733. this._axisTargetedByUpAndDown = axis;
  68734. break;
  68735. default:
  68736. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  68737. break;
  68738. }
  68739. };
  68740. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  68741. var _this = this;
  68742. if (this.pressed) {
  68743. this._touches.forEach(function (key, touch) {
  68744. if (touch.pointerId === _this._joystickPointerID) {
  68745. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  68746. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  68747. VirtualJoystick.vjCanvasContext.beginPath();
  68748. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  68749. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  68750. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  68751. VirtualJoystick.vjCanvasContext.stroke();
  68752. VirtualJoystick.vjCanvasContext.closePath();
  68753. VirtualJoystick.vjCanvasContext.beginPath();
  68754. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  68755. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  68756. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  68757. VirtualJoystick.vjCanvasContext.stroke();
  68758. VirtualJoystick.vjCanvasContext.closePath();
  68759. VirtualJoystick.vjCanvasContext.beginPath();
  68760. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  68761. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  68762. VirtualJoystick.vjCanvasContext.stroke();
  68763. VirtualJoystick.vjCanvasContext.closePath();
  68764. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  68765. }
  68766. else {
  68767. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  68768. VirtualJoystick.vjCanvasContext.beginPath();
  68769. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  68770. VirtualJoystick.vjCanvasContext.beginPath();
  68771. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  68772. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  68773. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  68774. VirtualJoystick.vjCanvasContext.stroke();
  68775. VirtualJoystick.vjCanvasContext.closePath();
  68776. touch.prevX = touch.x;
  68777. touch.prevY = touch.y;
  68778. }
  68779. ;
  68780. });
  68781. }
  68782. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  68783. };
  68784. VirtualJoystick.prototype.releaseCanvas = function () {
  68785. if (VirtualJoystick.vjCanvas) {
  68786. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  68787. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  68788. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  68789. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  68790. window.removeEventListener("resize", this._onResize);
  68791. document.body.removeChild(VirtualJoystick.vjCanvas);
  68792. VirtualJoystick.vjCanvas = null;
  68793. }
  68794. };
  68795. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  68796. VirtualJoystick._globalJoystickIndex = 0;
  68797. return VirtualJoystick;
  68798. }());
  68799. BABYLON.VirtualJoystick = VirtualJoystick;
  68800. })(BABYLON || (BABYLON = {}));
  68801. //# sourceMappingURL=babylon.virtualJoystick.js.map
  68802. var BABYLON;
  68803. (function (BABYLON) {
  68804. // We're mainly based on the logic defined into the FreeCamera code
  68805. var VirtualJoysticksCamera = (function (_super) {
  68806. __extends(VirtualJoysticksCamera, _super);
  68807. function VirtualJoysticksCamera(name, position, scene) {
  68808. var _this = _super.call(this, name, position, scene) || this;
  68809. _this.inputs.addVirtualJoystick();
  68810. return _this;
  68811. }
  68812. VirtualJoysticksCamera.prototype.getClassName = function () {
  68813. return "VirtualJoysticksCamera";
  68814. };
  68815. return VirtualJoysticksCamera;
  68816. }(BABYLON.FreeCamera));
  68817. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  68818. })(BABYLON || (BABYLON = {}));
  68819. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  68820. var BABYLON;
  68821. (function (BABYLON) {
  68822. var FreeCameraVirtualJoystickInput = (function () {
  68823. function FreeCameraVirtualJoystickInput() {
  68824. }
  68825. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  68826. return this._leftjoystick;
  68827. };
  68828. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  68829. return this._rightjoystick;
  68830. };
  68831. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  68832. if (this._leftjoystick) {
  68833. var camera = this.camera;
  68834. var speed = camera._computeLocalCameraSpeed() * 50;
  68835. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  68836. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  68837. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  68838. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  68839. if (!this._leftjoystick.pressed) {
  68840. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  68841. }
  68842. if (!this._rightjoystick.pressed) {
  68843. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  68844. }
  68845. }
  68846. };
  68847. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  68848. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  68849. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  68850. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  68851. this._leftjoystick.setJoystickSensibility(0.15);
  68852. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  68853. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  68854. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  68855. this._rightjoystick.reverseUpDown = true;
  68856. this._rightjoystick.setJoystickSensibility(0.05);
  68857. this._rightjoystick.setJoystickColor("yellow");
  68858. };
  68859. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  68860. this._leftjoystick.releaseCanvas();
  68861. this._rightjoystick.releaseCanvas();
  68862. };
  68863. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  68864. return "FreeCameraVirtualJoystickInput";
  68865. };
  68866. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  68867. return "virtualJoystick";
  68868. };
  68869. return FreeCameraVirtualJoystickInput;
  68870. }());
  68871. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  68872. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  68873. })(BABYLON || (BABYLON = {}));
  68874. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  68875. var BABYLON;
  68876. (function (BABYLON) {
  68877. var SimplificationSettings = (function () {
  68878. function SimplificationSettings(quality, distance, optimizeMesh) {
  68879. this.quality = quality;
  68880. this.distance = distance;
  68881. this.optimizeMesh = optimizeMesh;
  68882. }
  68883. return SimplificationSettings;
  68884. }());
  68885. BABYLON.SimplificationSettings = SimplificationSettings;
  68886. var SimplificationQueue = (function () {
  68887. function SimplificationQueue() {
  68888. this.running = false;
  68889. this._simplificationArray = [];
  68890. }
  68891. SimplificationQueue.prototype.addTask = function (task) {
  68892. this._simplificationArray.push(task);
  68893. };
  68894. SimplificationQueue.prototype.executeNext = function () {
  68895. var task = this._simplificationArray.pop();
  68896. if (task) {
  68897. this.running = true;
  68898. this.runSimplification(task);
  68899. }
  68900. else {
  68901. this.running = false;
  68902. }
  68903. };
  68904. SimplificationQueue.prototype.runSimplification = function (task) {
  68905. var _this = this;
  68906. if (task.parallelProcessing) {
  68907. //parallel simplifier
  68908. task.settings.forEach(function (setting) {
  68909. var simplifier = _this.getSimplifier(task);
  68910. simplifier.simplify(setting, function (newMesh) {
  68911. task.mesh.addLODLevel(setting.distance, newMesh);
  68912. newMesh.isVisible = true;
  68913. //check if it is the last
  68914. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  68915. //all done, run the success callback.
  68916. task.successCallback();
  68917. }
  68918. _this.executeNext();
  68919. });
  68920. });
  68921. }
  68922. else {
  68923. //single simplifier.
  68924. var simplifier = this.getSimplifier(task);
  68925. var runDecimation = function (setting, callback) {
  68926. simplifier.simplify(setting, function (newMesh) {
  68927. task.mesh.addLODLevel(setting.distance, newMesh);
  68928. newMesh.isVisible = true;
  68929. //run the next quality level
  68930. callback();
  68931. });
  68932. };
  68933. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  68934. runDecimation(task.settings[loop.index], function () {
  68935. loop.executeNext();
  68936. });
  68937. }, function () {
  68938. //execution ended, run the success callback.
  68939. if (task.successCallback) {
  68940. task.successCallback();
  68941. }
  68942. _this.executeNext();
  68943. });
  68944. }
  68945. };
  68946. SimplificationQueue.prototype.getSimplifier = function (task) {
  68947. switch (task.simplificationType) {
  68948. case SimplificationType.QUADRATIC:
  68949. default:
  68950. return new QuadraticErrorSimplification(task.mesh);
  68951. }
  68952. };
  68953. return SimplificationQueue;
  68954. }());
  68955. BABYLON.SimplificationQueue = SimplificationQueue;
  68956. /**
  68957. * The implemented types of simplification.
  68958. * At the moment only Quadratic Error Decimation is implemented.
  68959. */
  68960. var SimplificationType;
  68961. (function (SimplificationType) {
  68962. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  68963. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  68964. var DecimationTriangle = (function () {
  68965. function DecimationTriangle(vertices) {
  68966. this.vertices = vertices;
  68967. this.error = new Array(4);
  68968. this.deleted = false;
  68969. this.isDirty = false;
  68970. this.deletePending = false;
  68971. this.borderFactor = 0;
  68972. }
  68973. return DecimationTriangle;
  68974. }());
  68975. BABYLON.DecimationTriangle = DecimationTriangle;
  68976. var DecimationVertex = (function () {
  68977. function DecimationVertex(position, id) {
  68978. this.position = position;
  68979. this.id = id;
  68980. this.isBorder = true;
  68981. this.q = new QuadraticMatrix();
  68982. this.triangleCount = 0;
  68983. this.triangleStart = 0;
  68984. this.originalOffsets = [];
  68985. }
  68986. DecimationVertex.prototype.updatePosition = function (newPosition) {
  68987. this.position.copyFrom(newPosition);
  68988. };
  68989. return DecimationVertex;
  68990. }());
  68991. BABYLON.DecimationVertex = DecimationVertex;
  68992. var QuadraticMatrix = (function () {
  68993. function QuadraticMatrix(data) {
  68994. this.data = new Array(10);
  68995. for (var i = 0; i < 10; ++i) {
  68996. if (data && data[i]) {
  68997. this.data[i] = data[i];
  68998. }
  68999. else {
  69000. this.data[i] = 0;
  69001. }
  69002. }
  69003. }
  69004. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  69005. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  69006. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  69007. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  69008. return det;
  69009. };
  69010. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  69011. for (var i = 0; i < 10; ++i) {
  69012. this.data[i] += matrix.data[i];
  69013. }
  69014. };
  69015. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  69016. for (var i = 0; i < 10; ++i) {
  69017. this.data[i] += data[i];
  69018. }
  69019. };
  69020. QuadraticMatrix.prototype.add = function (matrix) {
  69021. var m = new QuadraticMatrix();
  69022. for (var i = 0; i < 10; ++i) {
  69023. m.data[i] = this.data[i] + matrix.data[i];
  69024. }
  69025. return m;
  69026. };
  69027. QuadraticMatrix.FromData = function (a, b, c, d) {
  69028. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  69029. };
  69030. //returning an array to avoid garbage collection
  69031. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  69032. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  69033. };
  69034. return QuadraticMatrix;
  69035. }());
  69036. BABYLON.QuadraticMatrix = QuadraticMatrix;
  69037. var Reference = (function () {
  69038. function Reference(vertexId, triangleId) {
  69039. this.vertexId = vertexId;
  69040. this.triangleId = triangleId;
  69041. }
  69042. return Reference;
  69043. }());
  69044. BABYLON.Reference = Reference;
  69045. /**
  69046. * An implementation of the Quadratic Error simplification algorithm.
  69047. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  69048. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  69049. * @author RaananW
  69050. */
  69051. var QuadraticErrorSimplification = (function () {
  69052. function QuadraticErrorSimplification(_mesh) {
  69053. this._mesh = _mesh;
  69054. this.initialized = false;
  69055. this.syncIterations = 5000;
  69056. this.aggressiveness = 7;
  69057. this.decimationIterations = 100;
  69058. this.boundingBoxEpsilon = BABYLON.Epsilon;
  69059. }
  69060. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  69061. var _this = this;
  69062. this.initDecimatedMesh();
  69063. //iterating through the submeshes array, one after the other.
  69064. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  69065. _this.initWithMesh(loop.index, function () {
  69066. _this.runDecimation(settings, loop.index, function () {
  69067. loop.executeNext();
  69068. });
  69069. }, settings.optimizeMesh);
  69070. }, function () {
  69071. setTimeout(function () {
  69072. successCallback(_this._reconstructedMesh);
  69073. }, 0);
  69074. });
  69075. };
  69076. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  69077. var _this = this;
  69078. var targetCount = ~~(this.triangles.length * settings.quality);
  69079. var deletedTriangles = 0;
  69080. var triangleCount = this.triangles.length;
  69081. var iterationFunction = function (iteration, callback) {
  69082. setTimeout(function () {
  69083. if (iteration % 5 === 0) {
  69084. _this.updateMesh(iteration === 0);
  69085. }
  69086. for (var i = 0; i < _this.triangles.length; ++i) {
  69087. _this.triangles[i].isDirty = false;
  69088. }
  69089. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  69090. var trianglesIterator = function (i) {
  69091. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  69092. var t = _this.triangles[tIdx];
  69093. if (!t)
  69094. return;
  69095. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  69096. return;
  69097. }
  69098. for (var j = 0; j < 3; ++j) {
  69099. if (t.error[j] < threshold) {
  69100. var deleted0 = [];
  69101. var deleted1 = [];
  69102. var v0 = t.vertices[j];
  69103. var v1 = t.vertices[(j + 1) % 3];
  69104. if (v0.isBorder || v1.isBorder)
  69105. continue;
  69106. var p = BABYLON.Vector3.Zero();
  69107. var n = BABYLON.Vector3.Zero();
  69108. var uv = BABYLON.Vector2.Zero();
  69109. var color = new BABYLON.Color4(0, 0, 0, 1);
  69110. _this.calculateError(v0, v1, p, n, uv, color);
  69111. var delTr = new Array();
  69112. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  69113. continue;
  69114. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  69115. continue;
  69116. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  69117. continue;
  69118. var uniqueArray = new Array();
  69119. delTr.forEach(function (deletedT) {
  69120. if (uniqueArray.indexOf(deletedT) === -1) {
  69121. deletedT.deletePending = true;
  69122. uniqueArray.push(deletedT);
  69123. }
  69124. });
  69125. if (uniqueArray.length % 2 !== 0) {
  69126. continue;
  69127. }
  69128. v0.q = v1.q.add(v0.q);
  69129. v0.updatePosition(p);
  69130. var tStart = _this.references.length;
  69131. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  69132. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  69133. var tCount = _this.references.length - tStart;
  69134. if (tCount <= v0.triangleCount) {
  69135. if (tCount) {
  69136. for (var c = 0; c < tCount; c++) {
  69137. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  69138. }
  69139. }
  69140. }
  69141. else {
  69142. v0.triangleStart = tStart;
  69143. }
  69144. v0.triangleCount = tCount;
  69145. break;
  69146. }
  69147. }
  69148. };
  69149. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  69150. }, 0);
  69151. };
  69152. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  69153. if (triangleCount - deletedTriangles <= targetCount)
  69154. loop.breakLoop();
  69155. else {
  69156. iterationFunction(loop.index, function () {
  69157. loop.executeNext();
  69158. });
  69159. }
  69160. }, function () {
  69161. setTimeout(function () {
  69162. //reconstruct this part of the mesh
  69163. _this.reconstructMesh(submeshIndex);
  69164. successCallback();
  69165. }, 0);
  69166. });
  69167. };
  69168. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  69169. var _this = this;
  69170. this.vertices = [];
  69171. this.triangles = [];
  69172. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  69173. var indices = this._mesh.getIndices();
  69174. var submesh = this._mesh.subMeshes[submeshIndex];
  69175. var findInVertices = function (positionToSearch) {
  69176. if (optimizeMesh) {
  69177. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  69178. if (_this.vertices[ii].position.equals(positionToSearch)) {
  69179. return _this.vertices[ii];
  69180. }
  69181. }
  69182. }
  69183. return null;
  69184. };
  69185. var vertexReferences = [];
  69186. var vertexInit = function (i) {
  69187. var offset = i + submesh.verticesStart;
  69188. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  69189. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  69190. vertex.originalOffsets.push(offset);
  69191. if (vertex.id === _this.vertices.length) {
  69192. _this.vertices.push(vertex);
  69193. }
  69194. vertexReferences.push(vertex.id);
  69195. };
  69196. //var totalVertices = mesh.getTotalVertices();
  69197. var totalVertices = submesh.verticesCount;
  69198. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  69199. var indicesInit = function (i) {
  69200. var offset = (submesh.indexStart / 3) + i;
  69201. var pos = (offset * 3);
  69202. var i0 = indices[pos + 0];
  69203. var i1 = indices[pos + 1];
  69204. var i2 = indices[pos + 2];
  69205. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  69206. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  69207. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  69208. var triangle = new DecimationTriangle([v0, v1, v2]);
  69209. triangle.originalOffset = pos;
  69210. _this.triangles.push(triangle);
  69211. };
  69212. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  69213. _this.init(callback);
  69214. });
  69215. });
  69216. };
  69217. QuadraticErrorSimplification.prototype.init = function (callback) {
  69218. var _this = this;
  69219. var triangleInit1 = function (i) {
  69220. var t = _this.triangles[i];
  69221. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  69222. for (var j = 0; j < 3; j++) {
  69223. 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))));
  69224. }
  69225. };
  69226. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  69227. var triangleInit2 = function (i) {
  69228. var t = _this.triangles[i];
  69229. for (var j = 0; j < 3; ++j) {
  69230. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  69231. }
  69232. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  69233. };
  69234. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  69235. _this.initialized = true;
  69236. callback();
  69237. });
  69238. });
  69239. };
  69240. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  69241. var newTriangles = [];
  69242. var i;
  69243. for (i = 0; i < this.vertices.length; ++i) {
  69244. this.vertices[i].triangleCount = 0;
  69245. }
  69246. var t;
  69247. var j;
  69248. for (i = 0; i < this.triangles.length; ++i) {
  69249. if (!this.triangles[i].deleted) {
  69250. t = this.triangles[i];
  69251. for (j = 0; j < 3; ++j) {
  69252. t.vertices[j].triangleCount = 1;
  69253. }
  69254. newTriangles.push(t);
  69255. }
  69256. }
  69257. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  69258. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  69259. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  69260. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  69261. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  69262. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  69263. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  69264. var vertexCount = 0;
  69265. for (i = 0; i < this.vertices.length; ++i) {
  69266. var vertex = this.vertices[i];
  69267. vertex.id = vertexCount;
  69268. if (vertex.triangleCount) {
  69269. vertex.originalOffsets.forEach(function (originalOffset) {
  69270. newPositionData.push(vertex.position.x);
  69271. newPositionData.push(vertex.position.y);
  69272. newPositionData.push(vertex.position.z);
  69273. newNormalData.push(normalData[originalOffset * 3]);
  69274. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  69275. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  69276. if (uvs && uvs.length) {
  69277. newUVsData.push(uvs[(originalOffset * 2)]);
  69278. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  69279. }
  69280. else if (colorsData && colorsData.length) {
  69281. newColorsData.push(colorsData[(originalOffset * 4)]);
  69282. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  69283. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  69284. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  69285. }
  69286. ++vertexCount;
  69287. });
  69288. }
  69289. }
  69290. var startingIndex = this._reconstructedMesh.getTotalIndices();
  69291. var startingVertex = this._reconstructedMesh.getTotalVertices();
  69292. var submeshesArray = this._reconstructedMesh.subMeshes;
  69293. this._reconstructedMesh.subMeshes = [];
  69294. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  69295. var originalIndices = this._mesh.getIndices();
  69296. for (i = 0; i < newTriangles.length; ++i) {
  69297. t = newTriangles[i]; //now get the new referencing point for each vertex
  69298. [0, 1, 2].forEach(function (idx) {
  69299. var id = originalIndices[t.originalOffset + idx];
  69300. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  69301. if (offset < 0)
  69302. offset = 0;
  69303. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  69304. });
  69305. }
  69306. //overwriting the old vertex buffers and indices.
  69307. this._reconstructedMesh.setIndices(newIndicesArray);
  69308. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  69309. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  69310. if (newUVsData.length > 0)
  69311. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  69312. if (newColorsData.length > 0)
  69313. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  69314. //create submesh
  69315. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  69316. if (submeshIndex > 0) {
  69317. this._reconstructedMesh.subMeshes = [];
  69318. submeshesArray.forEach(function (submesh) {
  69319. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  69320. });
  69321. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  69322. }
  69323. };
  69324. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  69325. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  69326. this._reconstructedMesh.material = this._mesh.material;
  69327. this._reconstructedMesh.parent = this._mesh.parent;
  69328. this._reconstructedMesh.isVisible = false;
  69329. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  69330. };
  69331. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  69332. for (var i = 0; i < vertex1.triangleCount; ++i) {
  69333. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  69334. if (t.deleted)
  69335. continue;
  69336. var s = this.references[vertex1.triangleStart + i].vertexId;
  69337. var v1 = t.vertices[(s + 1) % 3];
  69338. var v2 = t.vertices[(s + 2) % 3];
  69339. if ((v1 === vertex2 || v2 === vertex2)) {
  69340. deletedArray[i] = true;
  69341. delTr.push(t);
  69342. continue;
  69343. }
  69344. var d1 = v1.position.subtract(point);
  69345. d1 = d1.normalize();
  69346. var d2 = v2.position.subtract(point);
  69347. d2 = d2.normalize();
  69348. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  69349. return true;
  69350. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  69351. deletedArray[i] = false;
  69352. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  69353. return true;
  69354. }
  69355. return false;
  69356. };
  69357. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  69358. var newDeleted = deletedTriangles;
  69359. for (var i = 0; i < vertex.triangleCount; ++i) {
  69360. var ref = this.references[vertex.triangleStart + i];
  69361. var t = this.triangles[ref.triangleId];
  69362. if (t.deleted)
  69363. continue;
  69364. if (deletedArray[i] && t.deletePending) {
  69365. t.deleted = true;
  69366. newDeleted++;
  69367. continue;
  69368. }
  69369. t.vertices[ref.vertexId] = origVertex;
  69370. t.isDirty = true;
  69371. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  69372. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  69373. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  69374. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  69375. this.references.push(ref);
  69376. }
  69377. return newDeleted;
  69378. };
  69379. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  69380. for (var i = 0; i < this.vertices.length; ++i) {
  69381. var vCount = [];
  69382. var vId = [];
  69383. var v = this.vertices[i];
  69384. var j;
  69385. for (j = 0; j < v.triangleCount; ++j) {
  69386. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  69387. for (var ii = 0; ii < 3; ii++) {
  69388. var ofs = 0;
  69389. var vv = triangle.vertices[ii];
  69390. while (ofs < vCount.length) {
  69391. if (vId[ofs] === vv.id)
  69392. break;
  69393. ++ofs;
  69394. }
  69395. if (ofs === vCount.length) {
  69396. vCount.push(1);
  69397. vId.push(vv.id);
  69398. }
  69399. else {
  69400. vCount[ofs]++;
  69401. }
  69402. }
  69403. }
  69404. for (j = 0; j < vCount.length; ++j) {
  69405. if (vCount[j] === 1) {
  69406. this.vertices[vId[j]].isBorder = true;
  69407. }
  69408. else {
  69409. this.vertices[vId[j]].isBorder = false;
  69410. }
  69411. }
  69412. }
  69413. };
  69414. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  69415. if (identifyBorders === void 0) { identifyBorders = false; }
  69416. var i;
  69417. if (!identifyBorders) {
  69418. var newTrianglesVector = [];
  69419. for (i = 0; i < this.triangles.length; ++i) {
  69420. if (!this.triangles[i].deleted) {
  69421. newTrianglesVector.push(this.triangles[i]);
  69422. }
  69423. }
  69424. this.triangles = newTrianglesVector;
  69425. }
  69426. for (i = 0; i < this.vertices.length; ++i) {
  69427. this.vertices[i].triangleCount = 0;
  69428. this.vertices[i].triangleStart = 0;
  69429. }
  69430. var t;
  69431. var j;
  69432. var v;
  69433. for (i = 0; i < this.triangles.length; ++i) {
  69434. t = this.triangles[i];
  69435. for (j = 0; j < 3; ++j) {
  69436. v = t.vertices[j];
  69437. v.triangleCount++;
  69438. }
  69439. }
  69440. var tStart = 0;
  69441. for (i = 0; i < this.vertices.length; ++i) {
  69442. this.vertices[i].triangleStart = tStart;
  69443. tStart += this.vertices[i].triangleCount;
  69444. this.vertices[i].triangleCount = 0;
  69445. }
  69446. var newReferences = new Array(this.triangles.length * 3);
  69447. for (i = 0; i < this.triangles.length; ++i) {
  69448. t = this.triangles[i];
  69449. for (j = 0; j < 3; ++j) {
  69450. v = t.vertices[j];
  69451. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  69452. v.triangleCount++;
  69453. }
  69454. }
  69455. this.references = newReferences;
  69456. if (identifyBorders) {
  69457. this.identifyBorder();
  69458. }
  69459. };
  69460. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  69461. var x = point.x;
  69462. var y = point.y;
  69463. var z = point.z;
  69464. 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
  69465. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  69466. };
  69467. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  69468. var q = vertex1.q.add(vertex2.q);
  69469. var border = vertex1.isBorder && vertex2.isBorder;
  69470. var error = 0;
  69471. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  69472. if (qDet !== 0 && !border) {
  69473. if (!pointResult) {
  69474. pointResult = BABYLON.Vector3.Zero();
  69475. }
  69476. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  69477. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  69478. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  69479. error = this.vertexError(q, pointResult);
  69480. }
  69481. else {
  69482. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  69483. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  69484. var error1 = this.vertexError(q, vertex1.position);
  69485. var error2 = this.vertexError(q, vertex2.position);
  69486. var error3 = this.vertexError(q, p3);
  69487. error = Math.min(error1, error2, error3);
  69488. if (error === error1) {
  69489. if (pointResult) {
  69490. pointResult.copyFrom(vertex1.position);
  69491. }
  69492. }
  69493. else if (error === error2) {
  69494. if (pointResult) {
  69495. pointResult.copyFrom(vertex2.position);
  69496. }
  69497. }
  69498. else {
  69499. if (pointResult) {
  69500. pointResult.copyFrom(p3);
  69501. }
  69502. }
  69503. }
  69504. return error;
  69505. };
  69506. return QuadraticErrorSimplification;
  69507. }());
  69508. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  69509. })(BABYLON || (BABYLON = {}));
  69510. //# sourceMappingURL=babylon.meshSimplification.js.map
  69511. var BABYLON;
  69512. (function (BABYLON) {
  69513. var Internals;
  69514. (function (Internals) {
  69515. var MeshLODLevel = (function () {
  69516. function MeshLODLevel(distance, mesh) {
  69517. this.distance = distance;
  69518. this.mesh = mesh;
  69519. }
  69520. return MeshLODLevel;
  69521. }());
  69522. Internals.MeshLODLevel = MeshLODLevel;
  69523. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  69524. })(BABYLON || (BABYLON = {}));
  69525. //# sourceMappingURL=babylon.meshLODLevel.js.map
  69526. var BABYLON;
  69527. (function (BABYLON) {
  69528. // Standard optimizations
  69529. var SceneOptimization = (function () {
  69530. function SceneOptimization(priority) {
  69531. if (priority === void 0) { priority = 0; }
  69532. this.priority = priority;
  69533. this.apply = function (scene) {
  69534. return true; // Return true if everything that can be done was applied
  69535. };
  69536. }
  69537. return SceneOptimization;
  69538. }());
  69539. BABYLON.SceneOptimization = SceneOptimization;
  69540. var TextureOptimization = (function (_super) {
  69541. __extends(TextureOptimization, _super);
  69542. function TextureOptimization(priority, maximumSize) {
  69543. if (priority === void 0) { priority = 0; }
  69544. if (maximumSize === void 0) { maximumSize = 1024; }
  69545. var _this = _super.call(this, priority) || this;
  69546. _this.priority = priority;
  69547. _this.maximumSize = maximumSize;
  69548. _this.apply = function (scene) {
  69549. var allDone = true;
  69550. for (var index = 0; index < scene.textures.length; index++) {
  69551. var texture = scene.textures[index];
  69552. if (!texture.canRescale || texture.getContext) {
  69553. continue;
  69554. }
  69555. var currentSize = texture.getSize();
  69556. var maxDimension = Math.max(currentSize.width, currentSize.height);
  69557. if (maxDimension > _this.maximumSize) {
  69558. texture.scale(0.5);
  69559. allDone = false;
  69560. }
  69561. }
  69562. return allDone;
  69563. };
  69564. return _this;
  69565. }
  69566. return TextureOptimization;
  69567. }(SceneOptimization));
  69568. BABYLON.TextureOptimization = TextureOptimization;
  69569. var HardwareScalingOptimization = (function (_super) {
  69570. __extends(HardwareScalingOptimization, _super);
  69571. function HardwareScalingOptimization(priority, maximumScale) {
  69572. if (priority === void 0) { priority = 0; }
  69573. if (maximumScale === void 0) { maximumScale = 2; }
  69574. var _this = _super.call(this, priority) || this;
  69575. _this.priority = priority;
  69576. _this.maximumScale = maximumScale;
  69577. _this._currentScale = 1;
  69578. _this.apply = function (scene) {
  69579. _this._currentScale++;
  69580. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  69581. return _this._currentScale >= _this.maximumScale;
  69582. };
  69583. return _this;
  69584. }
  69585. return HardwareScalingOptimization;
  69586. }(SceneOptimization));
  69587. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  69588. var ShadowsOptimization = (function (_super) {
  69589. __extends(ShadowsOptimization, _super);
  69590. function ShadowsOptimization() {
  69591. var _this = _super !== null && _super.apply(this, arguments) || this;
  69592. _this.apply = function (scene) {
  69593. scene.shadowsEnabled = false;
  69594. return true;
  69595. };
  69596. return _this;
  69597. }
  69598. return ShadowsOptimization;
  69599. }(SceneOptimization));
  69600. BABYLON.ShadowsOptimization = ShadowsOptimization;
  69601. var PostProcessesOptimization = (function (_super) {
  69602. __extends(PostProcessesOptimization, _super);
  69603. function PostProcessesOptimization() {
  69604. var _this = _super !== null && _super.apply(this, arguments) || this;
  69605. _this.apply = function (scene) {
  69606. scene.postProcessesEnabled = false;
  69607. return true;
  69608. };
  69609. return _this;
  69610. }
  69611. return PostProcessesOptimization;
  69612. }(SceneOptimization));
  69613. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  69614. var LensFlaresOptimization = (function (_super) {
  69615. __extends(LensFlaresOptimization, _super);
  69616. function LensFlaresOptimization() {
  69617. var _this = _super !== null && _super.apply(this, arguments) || this;
  69618. _this.apply = function (scene) {
  69619. scene.lensFlaresEnabled = false;
  69620. return true;
  69621. };
  69622. return _this;
  69623. }
  69624. return LensFlaresOptimization;
  69625. }(SceneOptimization));
  69626. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  69627. var ParticlesOptimization = (function (_super) {
  69628. __extends(ParticlesOptimization, _super);
  69629. function ParticlesOptimization() {
  69630. var _this = _super !== null && _super.apply(this, arguments) || this;
  69631. _this.apply = function (scene) {
  69632. scene.particlesEnabled = false;
  69633. return true;
  69634. };
  69635. return _this;
  69636. }
  69637. return ParticlesOptimization;
  69638. }(SceneOptimization));
  69639. BABYLON.ParticlesOptimization = ParticlesOptimization;
  69640. var RenderTargetsOptimization = (function (_super) {
  69641. __extends(RenderTargetsOptimization, _super);
  69642. function RenderTargetsOptimization() {
  69643. var _this = _super !== null && _super.apply(this, arguments) || this;
  69644. _this.apply = function (scene) {
  69645. scene.renderTargetsEnabled = false;
  69646. return true;
  69647. };
  69648. return _this;
  69649. }
  69650. return RenderTargetsOptimization;
  69651. }(SceneOptimization));
  69652. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  69653. var MergeMeshesOptimization = (function (_super) {
  69654. __extends(MergeMeshesOptimization, _super);
  69655. function MergeMeshesOptimization() {
  69656. var _this = _super !== null && _super.apply(this, arguments) || this;
  69657. _this._canBeMerged = function (abstractMesh) {
  69658. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  69659. return false;
  69660. }
  69661. var mesh = abstractMesh;
  69662. if (!mesh.isVisible || !mesh.isEnabled()) {
  69663. return false;
  69664. }
  69665. if (mesh.instances.length > 0) {
  69666. return false;
  69667. }
  69668. if (mesh.skeleton || mesh.hasLODLevels) {
  69669. return false;
  69670. }
  69671. if (mesh.parent) {
  69672. return false;
  69673. }
  69674. return true;
  69675. };
  69676. _this.apply = function (scene, updateSelectionTree) {
  69677. var globalPool = scene.meshes.slice(0);
  69678. var globalLength = globalPool.length;
  69679. for (var index = 0; index < globalLength; index++) {
  69680. var currentPool = new Array();
  69681. var current = globalPool[index];
  69682. // Checks
  69683. if (!_this._canBeMerged(current)) {
  69684. continue;
  69685. }
  69686. currentPool.push(current);
  69687. // Find compatible meshes
  69688. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  69689. var otherMesh = globalPool[subIndex];
  69690. if (!_this._canBeMerged(otherMesh)) {
  69691. continue;
  69692. }
  69693. if (otherMesh.material !== current.material) {
  69694. continue;
  69695. }
  69696. if (otherMesh.checkCollisions !== current.checkCollisions) {
  69697. continue;
  69698. }
  69699. currentPool.push(otherMesh);
  69700. globalLength--;
  69701. globalPool.splice(subIndex, 1);
  69702. subIndex--;
  69703. }
  69704. if (currentPool.length < 2) {
  69705. continue;
  69706. }
  69707. // Merge meshes
  69708. BABYLON.Mesh.MergeMeshes(currentPool);
  69709. }
  69710. if (updateSelectionTree != undefined) {
  69711. if (updateSelectionTree) {
  69712. scene.createOrUpdateSelectionOctree();
  69713. }
  69714. }
  69715. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  69716. scene.createOrUpdateSelectionOctree();
  69717. }
  69718. return true;
  69719. };
  69720. return _this;
  69721. }
  69722. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  69723. get: function () {
  69724. return MergeMeshesOptimization._UpdateSelectionTree;
  69725. },
  69726. set: function (value) {
  69727. MergeMeshesOptimization._UpdateSelectionTree = value;
  69728. },
  69729. enumerable: true,
  69730. configurable: true
  69731. });
  69732. MergeMeshesOptimization._UpdateSelectionTree = false;
  69733. return MergeMeshesOptimization;
  69734. }(SceneOptimization));
  69735. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  69736. // Options
  69737. var SceneOptimizerOptions = (function () {
  69738. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  69739. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  69740. if (trackerDuration === void 0) { trackerDuration = 2000; }
  69741. this.targetFrameRate = targetFrameRate;
  69742. this.trackerDuration = trackerDuration;
  69743. this.optimizations = new Array();
  69744. }
  69745. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  69746. var result = new SceneOptimizerOptions(targetFrameRate);
  69747. var priority = 0;
  69748. result.optimizations.push(new MergeMeshesOptimization(priority));
  69749. result.optimizations.push(new ShadowsOptimization(priority));
  69750. result.optimizations.push(new LensFlaresOptimization(priority));
  69751. // Next priority
  69752. priority++;
  69753. result.optimizations.push(new PostProcessesOptimization(priority));
  69754. result.optimizations.push(new ParticlesOptimization(priority));
  69755. // Next priority
  69756. priority++;
  69757. result.optimizations.push(new TextureOptimization(priority, 1024));
  69758. return result;
  69759. };
  69760. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  69761. var result = new SceneOptimizerOptions(targetFrameRate);
  69762. var priority = 0;
  69763. result.optimizations.push(new MergeMeshesOptimization(priority));
  69764. result.optimizations.push(new ShadowsOptimization(priority));
  69765. result.optimizations.push(new LensFlaresOptimization(priority));
  69766. // Next priority
  69767. priority++;
  69768. result.optimizations.push(new PostProcessesOptimization(priority));
  69769. result.optimizations.push(new ParticlesOptimization(priority));
  69770. // Next priority
  69771. priority++;
  69772. result.optimizations.push(new TextureOptimization(priority, 512));
  69773. // Next priority
  69774. priority++;
  69775. result.optimizations.push(new RenderTargetsOptimization(priority));
  69776. // Next priority
  69777. priority++;
  69778. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  69779. return result;
  69780. };
  69781. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  69782. var result = new SceneOptimizerOptions(targetFrameRate);
  69783. var priority = 0;
  69784. result.optimizations.push(new MergeMeshesOptimization(priority));
  69785. result.optimizations.push(new ShadowsOptimization(priority));
  69786. result.optimizations.push(new LensFlaresOptimization(priority));
  69787. // Next priority
  69788. priority++;
  69789. result.optimizations.push(new PostProcessesOptimization(priority));
  69790. result.optimizations.push(new ParticlesOptimization(priority));
  69791. // Next priority
  69792. priority++;
  69793. result.optimizations.push(new TextureOptimization(priority, 256));
  69794. // Next priority
  69795. priority++;
  69796. result.optimizations.push(new RenderTargetsOptimization(priority));
  69797. // Next priority
  69798. priority++;
  69799. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  69800. return result;
  69801. };
  69802. return SceneOptimizerOptions;
  69803. }());
  69804. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  69805. // Scene optimizer tool
  69806. var SceneOptimizer = (function () {
  69807. function SceneOptimizer() {
  69808. }
  69809. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  69810. // TODO: add an epsilon
  69811. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  69812. if (onSuccess) {
  69813. onSuccess();
  69814. }
  69815. return;
  69816. }
  69817. // Apply current level of optimizations
  69818. var allDone = true;
  69819. var noOptimizationApplied = true;
  69820. for (var index = 0; index < options.optimizations.length; index++) {
  69821. var optimization = options.optimizations[index];
  69822. if (optimization.priority === currentPriorityLevel) {
  69823. noOptimizationApplied = false;
  69824. allDone = allDone && optimization.apply(scene);
  69825. }
  69826. }
  69827. // If no optimization was applied, this is a failure :(
  69828. if (noOptimizationApplied) {
  69829. if (onFailure) {
  69830. onFailure();
  69831. }
  69832. return;
  69833. }
  69834. // If all optimizations were done, move to next level
  69835. if (allDone) {
  69836. currentPriorityLevel++;
  69837. }
  69838. // Let's the system running for a specific amount of time before checking FPS
  69839. scene.executeWhenReady(function () {
  69840. setTimeout(function () {
  69841. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  69842. }, options.trackerDuration);
  69843. });
  69844. };
  69845. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  69846. if (!options) {
  69847. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  69848. }
  69849. // Let's the system running for a specific amount of time before checking FPS
  69850. scene.executeWhenReady(function () {
  69851. setTimeout(function () {
  69852. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  69853. }, options.trackerDuration);
  69854. });
  69855. };
  69856. return SceneOptimizer;
  69857. }());
  69858. BABYLON.SceneOptimizer = SceneOptimizer;
  69859. })(BABYLON || (BABYLON = {}));
  69860. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  69861. var BABYLON;
  69862. (function (BABYLON) {
  69863. var OutlineRenderer = (function () {
  69864. function OutlineRenderer(scene) {
  69865. this.zOffset = 1;
  69866. this._scene = scene;
  69867. }
  69868. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  69869. var _this = this;
  69870. if (useOverlay === void 0) { useOverlay = false; }
  69871. var scene = this._scene;
  69872. var engine = this._scene.getEngine();
  69873. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  69874. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  69875. return;
  69876. }
  69877. var mesh = subMesh.getRenderingMesh();
  69878. var material = subMesh.getMaterial();
  69879. engine.enableEffect(this._effect);
  69880. // Logarithmic depth
  69881. if (material.useLogarithmicDepth) {
  69882. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  69883. }
  69884. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  69885. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  69886. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  69887. // Bones
  69888. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69889. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69890. }
  69891. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  69892. // Alpha test
  69893. if (material && material.needAlphaTesting()) {
  69894. var alphaTexture = material.getAlphaTestTexture();
  69895. if (alphaTexture) {
  69896. this._effect.setTexture("diffuseSampler", alphaTexture);
  69897. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69898. }
  69899. }
  69900. engine.setZOffset(-this.zOffset);
  69901. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  69902. engine.setZOffset(0);
  69903. };
  69904. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  69905. var defines = [];
  69906. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  69907. var mesh = subMesh.getMesh();
  69908. var material = subMesh.getMaterial();
  69909. if (material) {
  69910. // Alpha test
  69911. if (material.needAlphaTesting()) {
  69912. defines.push("#define ALPHATEST");
  69913. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69914. attribs.push(BABYLON.VertexBuffer.UVKind);
  69915. defines.push("#define UV1");
  69916. }
  69917. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69918. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69919. defines.push("#define UV2");
  69920. }
  69921. }
  69922. //Logarithmic depth
  69923. if (material.useLogarithmicDepth) {
  69924. defines.push("#define LOGARITHMICDEPTH");
  69925. }
  69926. }
  69927. // Bones
  69928. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69929. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69930. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69931. if (mesh.numBoneInfluencers > 4) {
  69932. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69933. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69934. }
  69935. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69936. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  69937. }
  69938. else {
  69939. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69940. }
  69941. // Instances
  69942. if (useInstances) {
  69943. defines.push("#define INSTANCES");
  69944. attribs.push("world0");
  69945. attribs.push("world1");
  69946. attribs.push("world2");
  69947. attribs.push("world3");
  69948. }
  69949. // Get correct effect
  69950. var join = defines.join("\n");
  69951. if (this._cachedDefines !== join) {
  69952. this._cachedDefines = join;
  69953. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  69954. }
  69955. return this._effect.isReady();
  69956. };
  69957. return OutlineRenderer;
  69958. }());
  69959. BABYLON.OutlineRenderer = OutlineRenderer;
  69960. })(BABYLON || (BABYLON = {}));
  69961. //# sourceMappingURL=babylon.outlineRenderer.js.map
  69962. var BABYLON;
  69963. (function (BABYLON) {
  69964. var FaceAdjacencies = (function () {
  69965. function FaceAdjacencies() {
  69966. this.edges = new Array();
  69967. this.edgesConnectedCount = 0;
  69968. }
  69969. return FaceAdjacencies;
  69970. }());
  69971. var EdgesRenderer = (function () {
  69972. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  69973. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  69974. if (epsilon === void 0) { epsilon = 0.95; }
  69975. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  69976. this.edgesWidthScalerForOrthographic = 1000.0;
  69977. this.edgesWidthScalerForPerspective = 50.0;
  69978. this._linesPositions = new Array();
  69979. this._linesNormals = new Array();
  69980. this._linesIndices = new Array();
  69981. this._buffers = {};
  69982. this._checkVerticesInsteadOfIndices = false;
  69983. this._source = source;
  69984. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  69985. this._epsilon = epsilon;
  69986. this._prepareRessources();
  69987. this._generateEdgesLines();
  69988. }
  69989. EdgesRenderer.prototype._prepareRessources = function () {
  69990. if (this._lineShader) {
  69991. return;
  69992. }
  69993. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  69994. attributes: ["position", "normal"],
  69995. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  69996. });
  69997. this._lineShader.disableDepthWrite = true;
  69998. this._lineShader.backFaceCulling = false;
  69999. };
  70000. EdgesRenderer.prototype._rebuild = function () {
  70001. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  70002. if (buffer) {
  70003. buffer._rebuild();
  70004. }
  70005. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  70006. if (buffer) {
  70007. buffer._rebuild();
  70008. }
  70009. var scene = this._source.getScene();
  70010. var engine = scene.getEngine();
  70011. this._ib = engine.createIndexBuffer(this._linesIndices);
  70012. };
  70013. EdgesRenderer.prototype.dispose = function () {
  70014. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  70015. if (buffer) {
  70016. buffer.dispose();
  70017. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  70018. }
  70019. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  70020. if (buffer) {
  70021. buffer.dispose();
  70022. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  70023. }
  70024. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  70025. this._lineShader.dispose();
  70026. };
  70027. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  70028. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  70029. return 0;
  70030. }
  70031. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  70032. return 1;
  70033. }
  70034. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  70035. return 2;
  70036. }
  70037. return -1;
  70038. };
  70039. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  70040. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  70041. return 0;
  70042. }
  70043. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  70044. return 1;
  70045. }
  70046. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  70047. return 2;
  70048. }
  70049. return -1;
  70050. };
  70051. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  70052. var needToCreateLine;
  70053. if (edge === undefined) {
  70054. needToCreateLine = true;
  70055. }
  70056. else {
  70057. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  70058. needToCreateLine = dotProduct < this._epsilon;
  70059. }
  70060. if (needToCreateLine) {
  70061. var offset = this._linesPositions.length / 3;
  70062. var normal = p0.subtract(p1);
  70063. normal.normalize();
  70064. // Positions
  70065. this._linesPositions.push(p0.x);
  70066. this._linesPositions.push(p0.y);
  70067. this._linesPositions.push(p0.z);
  70068. this._linesPositions.push(p0.x);
  70069. this._linesPositions.push(p0.y);
  70070. this._linesPositions.push(p0.z);
  70071. this._linesPositions.push(p1.x);
  70072. this._linesPositions.push(p1.y);
  70073. this._linesPositions.push(p1.z);
  70074. this._linesPositions.push(p1.x);
  70075. this._linesPositions.push(p1.y);
  70076. this._linesPositions.push(p1.z);
  70077. // Normals
  70078. this._linesNormals.push(p1.x);
  70079. this._linesNormals.push(p1.y);
  70080. this._linesNormals.push(p1.z);
  70081. this._linesNormals.push(-1);
  70082. this._linesNormals.push(p1.x);
  70083. this._linesNormals.push(p1.y);
  70084. this._linesNormals.push(p1.z);
  70085. this._linesNormals.push(1);
  70086. this._linesNormals.push(p0.x);
  70087. this._linesNormals.push(p0.y);
  70088. this._linesNormals.push(p0.z);
  70089. this._linesNormals.push(-1);
  70090. this._linesNormals.push(p0.x);
  70091. this._linesNormals.push(p0.y);
  70092. this._linesNormals.push(p0.z);
  70093. this._linesNormals.push(1);
  70094. // Indices
  70095. this._linesIndices.push(offset);
  70096. this._linesIndices.push(offset + 1);
  70097. this._linesIndices.push(offset + 2);
  70098. this._linesIndices.push(offset);
  70099. this._linesIndices.push(offset + 2);
  70100. this._linesIndices.push(offset + 3);
  70101. }
  70102. };
  70103. EdgesRenderer.prototype._generateEdgesLines = function () {
  70104. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  70105. var indices = this._source.getIndices();
  70106. // First let's find adjacencies
  70107. var adjacencies = new Array();
  70108. var faceNormals = new Array();
  70109. var index;
  70110. var faceAdjacencies;
  70111. // Prepare faces
  70112. for (index = 0; index < indices.length; index += 3) {
  70113. faceAdjacencies = new FaceAdjacencies();
  70114. var p0Index = indices[index];
  70115. var p1Index = indices[index + 1];
  70116. var p2Index = indices[index + 2];
  70117. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  70118. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  70119. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  70120. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  70121. faceNormal.normalize();
  70122. faceNormals.push(faceNormal);
  70123. adjacencies.push(faceAdjacencies);
  70124. }
  70125. // Scan
  70126. for (index = 0; index < adjacencies.length; index++) {
  70127. faceAdjacencies = adjacencies[index];
  70128. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  70129. var otherFaceAdjacencies = adjacencies[otherIndex];
  70130. if (faceAdjacencies.edgesConnectedCount === 3) {
  70131. break;
  70132. }
  70133. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  70134. continue;
  70135. }
  70136. var otherP0 = indices[otherIndex * 3];
  70137. var otherP1 = indices[otherIndex * 3 + 1];
  70138. var otherP2 = indices[otherIndex * 3 + 2];
  70139. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  70140. var otherEdgeIndex;
  70141. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  70142. continue;
  70143. }
  70144. switch (edgeIndex) {
  70145. case 0:
  70146. if (this._checkVerticesInsteadOfIndices) {
  70147. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  70148. }
  70149. else {
  70150. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  70151. }
  70152. break;
  70153. case 1:
  70154. if (this._checkVerticesInsteadOfIndices) {
  70155. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  70156. }
  70157. else {
  70158. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  70159. }
  70160. break;
  70161. case 2:
  70162. if (this._checkVerticesInsteadOfIndices) {
  70163. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  70164. }
  70165. else {
  70166. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  70167. }
  70168. break;
  70169. }
  70170. if (otherEdgeIndex === -1) {
  70171. continue;
  70172. }
  70173. faceAdjacencies.edges[edgeIndex] = otherIndex;
  70174. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  70175. faceAdjacencies.edgesConnectedCount++;
  70176. otherFaceAdjacencies.edgesConnectedCount++;
  70177. if (faceAdjacencies.edgesConnectedCount === 3) {
  70178. break;
  70179. }
  70180. }
  70181. }
  70182. }
  70183. // Create lines
  70184. for (index = 0; index < adjacencies.length; index++) {
  70185. // 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
  70186. var current = adjacencies[index];
  70187. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  70188. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  70189. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  70190. }
  70191. // Merge into a single mesh
  70192. var engine = this._source.getScene().getEngine();
  70193. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  70194. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  70195. this._ib = engine.createIndexBuffer(this._linesIndices);
  70196. this._indicesCount = this._linesIndices.length;
  70197. };
  70198. EdgesRenderer.prototype.render = function () {
  70199. if (!this._lineShader.isReady()) {
  70200. return;
  70201. }
  70202. var scene = this._source.getScene();
  70203. var engine = scene.getEngine();
  70204. this._lineShader._preBind();
  70205. // VBOs
  70206. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  70207. scene.resetCachedMaterial();
  70208. this._lineShader.setColor4("color", this._source.edgesColor);
  70209. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  70210. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  70211. }
  70212. else {
  70213. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  70214. }
  70215. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  70216. this._lineShader.bind(this._source.getWorldMatrix());
  70217. // Draw order
  70218. engine.draw(true, 0, this._indicesCount);
  70219. this._lineShader.unbind();
  70220. engine.setDepthWrite(true);
  70221. };
  70222. return EdgesRenderer;
  70223. }());
  70224. BABYLON.EdgesRenderer = EdgesRenderer;
  70225. })(BABYLON || (BABYLON = {}));
  70226. //# sourceMappingURL=babylon.edgesRenderer.js.map
  70227. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  70228. /// <reference path="..\Math\babylon.math.ts" />
  70229. var BABYLON;
  70230. (function (BABYLON) {
  70231. /**
  70232. * Special Glow Blur post process only blurring the alpha channel
  70233. * It enforces keeping the most luminous color in the color channel.
  70234. */
  70235. var GlowBlurPostProcess = (function (_super) {
  70236. __extends(GlowBlurPostProcess, _super);
  70237. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  70238. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70239. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  70240. _this.direction = direction;
  70241. _this.kernel = kernel;
  70242. _this.onApplyObservable.add(function (effect) {
  70243. effect.setFloat2("screenSize", _this.width, _this.height);
  70244. effect.setVector2("direction", _this.direction);
  70245. effect.setFloat("blurWidth", _this.kernel);
  70246. });
  70247. return _this;
  70248. }
  70249. return GlowBlurPostProcess;
  70250. }(BABYLON.PostProcess));
  70251. /**
  70252. * The highlight layer Helps adding a glow effect around a mesh.
  70253. *
  70254. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  70255. * glowy meshes to your scene.
  70256. *
  70257. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  70258. */
  70259. var HighlightLayer = (function () {
  70260. /**
  70261. * Instantiates a new highlight Layer and references it to the scene..
  70262. * @param name The name of the layer
  70263. * @param scene The scene to use the layer in
  70264. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  70265. */
  70266. function HighlightLayer(name, scene, options) {
  70267. this.name = name;
  70268. this._vertexBuffers = {};
  70269. this._mainTextureDesiredSize = { width: 0, height: 0 };
  70270. this._meshes = {};
  70271. this._maxSize = 0;
  70272. this._shouldRender = false;
  70273. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  70274. this._excludedMeshes = {};
  70275. /**
  70276. * Specifies whether or not the inner glow is ACTIVE in the layer.
  70277. */
  70278. this.innerGlow = true;
  70279. /**
  70280. * Specifies whether or not the outer glow is ACTIVE in the layer.
  70281. */
  70282. this.outerGlow = true;
  70283. /**
  70284. * Specifies wether the highlight layer is enabled or not.
  70285. */
  70286. this.isEnabled = true;
  70287. /**
  70288. * An event triggered when the highlight layer has been disposed.
  70289. * @type {BABYLON.Observable}
  70290. */
  70291. this.onDisposeObservable = new BABYLON.Observable();
  70292. /**
  70293. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  70294. * @type {BABYLON.Observable}
  70295. */
  70296. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  70297. /**
  70298. * An event triggered when the highlight layer is being blurred.
  70299. * @type {BABYLON.Observable}
  70300. */
  70301. this.onBeforeBlurObservable = new BABYLON.Observable();
  70302. /**
  70303. * An event triggered when the highlight layer has been blurred.
  70304. * @type {BABYLON.Observable}
  70305. */
  70306. this.onAfterBlurObservable = new BABYLON.Observable();
  70307. /**
  70308. * An event triggered when the glowing blurred texture is being merged in the scene.
  70309. * @type {BABYLON.Observable}
  70310. */
  70311. this.onBeforeComposeObservable = new BABYLON.Observable();
  70312. /**
  70313. * An event triggered when the glowing blurred texture has been merged in the scene.
  70314. * @type {BABYLON.Observable}
  70315. */
  70316. this.onAfterComposeObservable = new BABYLON.Observable();
  70317. /**
  70318. * An event triggered when the highlight layer changes its size.
  70319. * @type {BABYLON.Observable}
  70320. */
  70321. this.onSizeChangedObservable = new BABYLON.Observable();
  70322. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70323. var engine = scene.getEngine();
  70324. this._engine = engine;
  70325. this._maxSize = this._engine.getCaps().maxTextureSize;
  70326. this._scene.highlightLayers.push(this);
  70327. // Warn on stencil.
  70328. if (!this._engine.isStencilEnable) {
  70329. 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 }");
  70330. }
  70331. // Adapt options
  70332. this._options = options || {
  70333. mainTextureRatio: 0.5,
  70334. blurTextureSizeRatio: 0.5,
  70335. blurHorizontalSize: 1.0,
  70336. blurVerticalSize: 1.0,
  70337. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  70338. };
  70339. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  70340. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  70341. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  70342. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  70343. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  70344. // VBO
  70345. var vertices = [];
  70346. vertices.push(1, 1);
  70347. vertices.push(-1, 1);
  70348. vertices.push(-1, -1);
  70349. vertices.push(1, -1);
  70350. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70351. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  70352. this._createIndexBuffer();
  70353. // Effect
  70354. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  70355. // Render target
  70356. this.setMainTextureSize();
  70357. // Create Textures and post processes
  70358. this.createTextureAndPostProcesses();
  70359. }
  70360. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  70361. /**
  70362. * Gets the horizontal size of the blur.
  70363. */
  70364. get: function () {
  70365. return this._horizontalBlurPostprocess.kernel;
  70366. },
  70367. /**
  70368. * Specifies the horizontal size of the blur.
  70369. */
  70370. set: function (value) {
  70371. this._horizontalBlurPostprocess.kernel = value;
  70372. },
  70373. enumerable: true,
  70374. configurable: true
  70375. });
  70376. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  70377. /**
  70378. * Gets the vertical size of the blur.
  70379. */
  70380. get: function () {
  70381. return this._verticalBlurPostprocess.kernel;
  70382. },
  70383. /**
  70384. * Specifies the vertical size of the blur.
  70385. */
  70386. set: function (value) {
  70387. this._verticalBlurPostprocess.kernel = value;
  70388. },
  70389. enumerable: true,
  70390. configurable: true
  70391. });
  70392. Object.defineProperty(HighlightLayer.prototype, "camera", {
  70393. /**
  70394. * Gets the camera attached to the layer.
  70395. */
  70396. get: function () {
  70397. return this._options.camera;
  70398. },
  70399. enumerable: true,
  70400. configurable: true
  70401. });
  70402. HighlightLayer.prototype._createIndexBuffer = function () {
  70403. var engine = this._scene.getEngine();
  70404. // Indices
  70405. var indices = [];
  70406. indices.push(0);
  70407. indices.push(1);
  70408. indices.push(2);
  70409. indices.push(0);
  70410. indices.push(2);
  70411. indices.push(3);
  70412. this._indexBuffer = engine.createIndexBuffer(indices);
  70413. };
  70414. HighlightLayer.prototype._rebuild = function () {
  70415. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  70416. this._createIndexBuffer();
  70417. };
  70418. /**
  70419. * Creates the render target textures and post processes used in the highlight layer.
  70420. */
  70421. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  70422. var _this = this;
  70423. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  70424. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  70425. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  70426. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  70427. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  70428. width: this._mainTextureDesiredSize.width,
  70429. height: this._mainTextureDesiredSize.height
  70430. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70431. this._mainTexture.activeCamera = this._options.camera;
  70432. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70433. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70434. this._mainTexture.anisotropicFilteringLevel = 1;
  70435. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70436. this._mainTexture.renderParticles = false;
  70437. this._mainTexture.renderList = null;
  70438. this._mainTexture.ignoreCameraViewport = true;
  70439. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  70440. width: blurTextureWidth,
  70441. height: blurTextureHeight
  70442. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70443. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70444. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70445. this._blurTexture.anisotropicFilteringLevel = 16;
  70446. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  70447. this._blurTexture.renderParticles = false;
  70448. this._blurTexture.ignoreCameraViewport = true;
  70449. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  70450. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  70451. effect.setTexture("textureSampler", _this._mainTexture);
  70452. });
  70453. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  70454. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  70455. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  70456. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  70457. });
  70458. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  70459. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  70460. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  70461. });
  70462. }
  70463. else {
  70464. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  70465. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  70466. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  70467. });
  70468. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  70469. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  70470. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  70471. });
  70472. }
  70473. this._mainTexture.onAfterUnbindObservable.add(function () {
  70474. _this.onBeforeBlurObservable.notifyObservers(_this);
  70475. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture(), true);
  70476. _this.onAfterBlurObservable.notifyObservers(_this);
  70477. });
  70478. // Custom render function
  70479. var renderSubMesh = function (subMesh) {
  70480. var mesh = subMesh.getRenderingMesh();
  70481. var scene = _this._scene;
  70482. var engine = scene.getEngine();
  70483. // Culling
  70484. engine.setState(subMesh.getMaterial().backFaceCulling);
  70485. // Managing instances
  70486. var batch = mesh._getInstancesRenderList(subMesh._id);
  70487. if (batch.mustReturn) {
  70488. return;
  70489. }
  70490. // Excluded Mesh
  70491. if (_this._excludedMeshes[mesh.uniqueId]) {
  70492. return;
  70493. }
  70494. ;
  70495. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  70496. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  70497. var material = subMesh.getMaterial();
  70498. var emissiveTexture = null;
  70499. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  70500. emissiveTexture = material.emissiveTexture;
  70501. }
  70502. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  70503. engine.enableEffect(_this._glowMapGenerationEffect);
  70504. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  70505. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  70506. if (highlightLayerMesh) {
  70507. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  70508. }
  70509. else {
  70510. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  70511. }
  70512. // Alpha test
  70513. if (material && material.needAlphaTesting()) {
  70514. var alphaTexture = material.getAlphaTestTexture();
  70515. if (alphaTexture) {
  70516. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  70517. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70518. }
  70519. }
  70520. // Glow emissive only
  70521. if (emissiveTexture) {
  70522. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  70523. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  70524. }
  70525. // Bones
  70526. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70527. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70528. }
  70529. // Draw
  70530. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  70531. }
  70532. else {
  70533. // Need to reset refresh rate of the shadowMap
  70534. _this._mainTexture.resetRefreshCounter();
  70535. }
  70536. };
  70537. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70538. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  70539. var index;
  70540. var engine = _this._scene.getEngine();
  70541. if (depthOnlySubMeshes.length) {
  70542. engine.setColorWrite(false);
  70543. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70544. renderSubMesh(depthOnlySubMeshes.data[index]);
  70545. }
  70546. engine.setColorWrite(true);
  70547. }
  70548. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70549. renderSubMesh(opaqueSubMeshes.data[index]);
  70550. }
  70551. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70552. renderSubMesh(alphaTestSubMeshes.data[index]);
  70553. }
  70554. for (index = 0; index < transparentSubMeshes.length; index++) {
  70555. renderSubMesh(transparentSubMeshes.data[index]);
  70556. }
  70557. };
  70558. this._mainTexture.onClearObservable.add(function (engine) {
  70559. engine.clear(HighlightLayer.neutralColor, true, true, true);
  70560. });
  70561. };
  70562. /**
  70563. * Checks for the readiness of the element composing the layer.
  70564. * @param subMesh the mesh to check for
  70565. * @param useInstances specify wether or not to use instances to render the mesh
  70566. * @param emissiveTexture the associated emissive texture used to generate the glow
  70567. * @return true if ready otherwise, false
  70568. */
  70569. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  70570. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  70571. return false;
  70572. }
  70573. var defines = [];
  70574. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70575. var mesh = subMesh.getMesh();
  70576. var material = subMesh.getMaterial();
  70577. var uv1 = false;
  70578. var uv2 = false;
  70579. // Alpha test
  70580. if (material && material.needAlphaTesting()) {
  70581. var alphaTexture = material.getAlphaTestTexture();
  70582. if (alphaTexture) {
  70583. defines.push("#define ALPHATEST");
  70584. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  70585. alphaTexture.coordinatesIndex === 1) {
  70586. defines.push("#define DIFFUSEUV2");
  70587. uv2 = true;
  70588. }
  70589. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70590. defines.push("#define DIFFUSEUV1");
  70591. uv1 = true;
  70592. }
  70593. }
  70594. }
  70595. // Emissive
  70596. if (emissiveTexture) {
  70597. defines.push("#define EMISSIVE");
  70598. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  70599. emissiveTexture.coordinatesIndex === 1) {
  70600. defines.push("#define EMISSIVEUV2");
  70601. uv2 = true;
  70602. }
  70603. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70604. defines.push("#define EMISSIVEUV1");
  70605. uv1 = true;
  70606. }
  70607. }
  70608. if (uv1) {
  70609. attribs.push(BABYLON.VertexBuffer.UVKind);
  70610. defines.push("#define UV1");
  70611. }
  70612. if (uv2) {
  70613. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70614. defines.push("#define UV2");
  70615. }
  70616. // Bones
  70617. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70618. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70619. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70620. if (mesh.numBoneInfluencers > 4) {
  70621. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70622. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70623. }
  70624. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70625. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  70626. }
  70627. else {
  70628. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70629. }
  70630. // Instances
  70631. if (useInstances) {
  70632. defines.push("#define INSTANCES");
  70633. attribs.push("world0");
  70634. attribs.push("world1");
  70635. attribs.push("world2");
  70636. attribs.push("world3");
  70637. }
  70638. // Get correct effect
  70639. var join = defines.join("\n");
  70640. if (this._cachedDefines !== join) {
  70641. this._cachedDefines = join;
  70642. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  70643. }
  70644. return this._glowMapGenerationEffect.isReady();
  70645. };
  70646. /**
  70647. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  70648. */
  70649. HighlightLayer.prototype.render = function () {
  70650. var currentEffect = this._glowMapMergeEffect;
  70651. // Check
  70652. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  70653. return;
  70654. var engine = this._scene.getEngine();
  70655. this.onBeforeComposeObservable.notifyObservers(this);
  70656. // Render
  70657. engine.enableEffect(currentEffect);
  70658. engine.setState(false);
  70659. // Cache
  70660. var previousStencilBuffer = engine.getStencilBuffer();
  70661. var previousStencilFunction = engine.getStencilFunction();
  70662. var previousStencilMask = engine.getStencilMask();
  70663. var previousStencilOperationPass = engine.getStencilOperationPass();
  70664. var previousStencilOperationFail = engine.getStencilOperationFail();
  70665. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  70666. var previousAlphaMode = engine.getAlphaMode();
  70667. // Texture
  70668. currentEffect.setTexture("textureSampler", this._blurTexture);
  70669. // VBOs
  70670. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  70671. // Stencil operations
  70672. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  70673. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  70674. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  70675. // Draw order
  70676. engine.setAlphaMode(this._options.alphaBlendingMode);
  70677. engine.setStencilMask(0x00);
  70678. engine.setStencilBuffer(true);
  70679. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  70680. if (this.outerGlow) {
  70681. currentEffect.setFloat("offset", 0);
  70682. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  70683. engine.draw(true, 0, 6);
  70684. }
  70685. if (this.innerGlow) {
  70686. currentEffect.setFloat("offset", 1);
  70687. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  70688. engine.draw(true, 0, 6);
  70689. }
  70690. // Restore Cache
  70691. engine.setStencilFunction(previousStencilFunction);
  70692. engine.setStencilMask(previousStencilMask);
  70693. engine.setAlphaMode(previousAlphaMode);
  70694. engine.setStencilBuffer(previousStencilBuffer);
  70695. engine.setStencilOperationPass(previousStencilOperationPass);
  70696. engine.setStencilOperationFail(previousStencilOperationFail);
  70697. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  70698. engine._stencilState.reset();
  70699. this.onAfterComposeObservable.notifyObservers(this);
  70700. // Handle size changes.
  70701. var size = this._mainTexture.getSize();
  70702. this.setMainTextureSize();
  70703. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  70704. // Recreate RTT and post processes on size change.
  70705. this.onSizeChangedObservable.notifyObservers(this);
  70706. this.disposeTextureAndPostProcesses();
  70707. this.createTextureAndPostProcesses();
  70708. }
  70709. };
  70710. /**
  70711. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  70712. * @param mesh The mesh to exclude from the highlight layer
  70713. */
  70714. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  70715. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  70716. if (!meshExcluded) {
  70717. this._excludedMeshes[mesh.uniqueId] = {
  70718. mesh: mesh,
  70719. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  70720. mesh.getEngine().setStencilBuffer(false);
  70721. }),
  70722. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  70723. mesh.getEngine().setStencilBuffer(true);
  70724. }),
  70725. };
  70726. }
  70727. };
  70728. /**
  70729. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  70730. * @param mesh The mesh to highlight
  70731. */
  70732. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  70733. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  70734. if (meshExcluded) {
  70735. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  70736. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  70737. }
  70738. this._excludedMeshes[mesh.uniqueId] = undefined;
  70739. };
  70740. /**
  70741. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  70742. * @param mesh The mesh to highlight
  70743. * @param color The color of the highlight
  70744. * @param glowEmissiveOnly Extract the glow from the emissive texture
  70745. */
  70746. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  70747. var _this = this;
  70748. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  70749. var meshHighlight = this._meshes[mesh.uniqueId];
  70750. if (meshHighlight) {
  70751. meshHighlight.color = color;
  70752. }
  70753. else {
  70754. this._meshes[mesh.uniqueId] = {
  70755. mesh: mesh,
  70756. color: color,
  70757. // Lambda required for capture due to Observable this context
  70758. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  70759. if (_this._excludedMeshes[mesh.uniqueId]) {
  70760. _this.defaultStencilReference(mesh);
  70761. }
  70762. else {
  70763. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  70764. }
  70765. }),
  70766. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  70767. glowEmissiveOnly: glowEmissiveOnly
  70768. };
  70769. }
  70770. this._shouldRender = true;
  70771. };
  70772. /**
  70773. * Remove a mesh from the highlight layer in order to make it stop glowing.
  70774. * @param mesh The mesh to highlight
  70775. */
  70776. HighlightLayer.prototype.removeMesh = function (mesh) {
  70777. var meshHighlight = this._meshes[mesh.uniqueId];
  70778. if (meshHighlight) {
  70779. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  70780. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  70781. }
  70782. this._meshes[mesh.uniqueId] = undefined;
  70783. this._shouldRender = false;
  70784. for (var meshHighlightToCheck in this._meshes) {
  70785. if (meshHighlightToCheck) {
  70786. this._shouldRender = true;
  70787. break;
  70788. }
  70789. }
  70790. };
  70791. /**
  70792. * Returns true if the layer contains information to display, otherwise false.
  70793. */
  70794. HighlightLayer.prototype.shouldRender = function () {
  70795. return this.isEnabled && this._shouldRender;
  70796. };
  70797. /**
  70798. * Sets the main texture desired size which is the closest power of two
  70799. * of the engine canvas size.
  70800. */
  70801. HighlightLayer.prototype.setMainTextureSize = function () {
  70802. if (this._options.mainTextureFixedSize) {
  70803. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  70804. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  70805. }
  70806. else {
  70807. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  70808. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  70809. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  70810. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  70811. }
  70812. };
  70813. /**
  70814. * Force the stencil to the normal expected value for none glowing parts
  70815. */
  70816. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  70817. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  70818. };
  70819. /**
  70820. * Dispose only the render target textures and post process.
  70821. */
  70822. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  70823. this._blurTexture.dispose();
  70824. this._mainTexture.dispose();
  70825. this._downSamplePostprocess.dispose();
  70826. this._horizontalBlurPostprocess.dispose();
  70827. this._verticalBlurPostprocess.dispose();
  70828. };
  70829. /**
  70830. * Dispose the highlight layer and free resources.
  70831. */
  70832. HighlightLayer.prototype.dispose = function () {
  70833. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70834. if (vertexBuffer) {
  70835. vertexBuffer.dispose();
  70836. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70837. }
  70838. if (this._indexBuffer) {
  70839. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  70840. this._indexBuffer = null;
  70841. }
  70842. // Clean textures and post processes
  70843. this.disposeTextureAndPostProcesses();
  70844. // Clean mesh references
  70845. for (var id in this._meshes) {
  70846. var meshHighlight = this._meshes[id];
  70847. if (meshHighlight && meshHighlight.mesh) {
  70848. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  70849. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  70850. }
  70851. }
  70852. this._meshes = null;
  70853. for (var id in this._excludedMeshes) {
  70854. var meshHighlight = this._excludedMeshes[id];
  70855. if (meshHighlight) {
  70856. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  70857. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  70858. }
  70859. }
  70860. this._excludedMeshes = null;
  70861. // Remove from scene
  70862. var index = this._scene.highlightLayers.indexOf(this, 0);
  70863. if (index > -1) {
  70864. this._scene.highlightLayers.splice(index, 1);
  70865. }
  70866. // Callback
  70867. this.onDisposeObservable.notifyObservers(this);
  70868. this.onDisposeObservable.clear();
  70869. this.onBeforeRenderMainTextureObservable.clear();
  70870. this.onBeforeBlurObservable.clear();
  70871. this.onBeforeComposeObservable.clear();
  70872. this.onAfterComposeObservable.clear();
  70873. this.onSizeChangedObservable.clear();
  70874. };
  70875. /**
  70876. * The neutral color used during the preparation of the glow effect.
  70877. * This is black by default as the blend operation is a blend operation.
  70878. */
  70879. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  70880. /**
  70881. * Stencil value used for glowing meshes.
  70882. */
  70883. HighlightLayer.glowingMeshStencilReference = 0x02;
  70884. /**
  70885. * Stencil value used for the other meshes in the scene.
  70886. */
  70887. HighlightLayer.normalMeshStencilReference = 0x01;
  70888. return HighlightLayer;
  70889. }());
  70890. BABYLON.HighlightLayer = HighlightLayer;
  70891. })(BABYLON || (BABYLON = {}));
  70892. //# sourceMappingURL=babylon.highlightlayer.js.map
  70893. var BABYLON;
  70894. (function (BABYLON) {
  70895. var AssetTaskState;
  70896. (function (AssetTaskState) {
  70897. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  70898. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  70899. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  70900. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  70901. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  70902. var AbstractAssetTask = (function () {
  70903. function AbstractAssetTask() {
  70904. this.isCompleted = false;
  70905. this.taskState = AssetTaskState.INIT;
  70906. }
  70907. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  70908. var _this = this;
  70909. this.taskState = AssetTaskState.RUNNING;
  70910. this.runTask(scene, function () {
  70911. _this.onDoneCallback(onSuccess, onError);
  70912. }, function (msg, exception) {
  70913. _this.onErrorCallback(onError, msg, exception);
  70914. });
  70915. };
  70916. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  70917. throw new Error("runTask is not implemented");
  70918. };
  70919. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  70920. this.taskState = AssetTaskState.ERROR;
  70921. this.errorObject = {
  70922. message: message,
  70923. exception: exception
  70924. };
  70925. if (this.onError) {
  70926. this.onError(this, message, exception);
  70927. }
  70928. onError();
  70929. };
  70930. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  70931. try {
  70932. this.taskState = AssetTaskState.DONE;
  70933. this.isCompleted = true;
  70934. if (this.onSuccess) {
  70935. this.onSuccess(this);
  70936. }
  70937. onSuccess();
  70938. }
  70939. catch (e) {
  70940. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  70941. }
  70942. };
  70943. return AbstractAssetTask;
  70944. }());
  70945. BABYLON.AbstractAssetTask = AbstractAssetTask;
  70946. var MeshAssetTask = (function (_super) {
  70947. __extends(MeshAssetTask, _super);
  70948. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  70949. var _this = _super.call(this) || this;
  70950. _this.name = name;
  70951. _this.meshesNames = meshesNames;
  70952. _this.rootUrl = rootUrl;
  70953. _this.sceneFilename = sceneFilename;
  70954. return _this;
  70955. }
  70956. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  70957. var _this = this;
  70958. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  70959. _this.loadedMeshes = meshes;
  70960. _this.loadedParticleSystems = particleSystems;
  70961. _this.loadedSkeletons = skeletons;
  70962. onSuccess();
  70963. }, null, function (scene, message, exception) {
  70964. onError(message, exception);
  70965. });
  70966. };
  70967. return MeshAssetTask;
  70968. }(AbstractAssetTask));
  70969. BABYLON.MeshAssetTask = MeshAssetTask;
  70970. var TextFileAssetTask = (function (_super) {
  70971. __extends(TextFileAssetTask, _super);
  70972. function TextFileAssetTask(name, url) {
  70973. var _this = _super.call(this) || this;
  70974. _this.name = name;
  70975. _this.url = url;
  70976. return _this;
  70977. }
  70978. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  70979. var _this = this;
  70980. BABYLON.Tools.LoadFile(this.url, function (data) {
  70981. _this.text = data;
  70982. onSuccess();
  70983. }, null, scene.database, false, function (request, exception) {
  70984. onError(request.status + " " + request.statusText, exception);
  70985. });
  70986. };
  70987. return TextFileAssetTask;
  70988. }(AbstractAssetTask));
  70989. BABYLON.TextFileAssetTask = TextFileAssetTask;
  70990. var BinaryFileAssetTask = (function (_super) {
  70991. __extends(BinaryFileAssetTask, _super);
  70992. function BinaryFileAssetTask(name, url) {
  70993. var _this = _super.call(this) || this;
  70994. _this.name = name;
  70995. _this.url = url;
  70996. return _this;
  70997. }
  70998. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  70999. var _this = this;
  71000. BABYLON.Tools.LoadFile(this.url, function (data) {
  71001. _this.data = data;
  71002. onSuccess();
  71003. }, null, scene.database, true, function (request, exception) {
  71004. onError(request.status + " " + request.statusText, exception);
  71005. });
  71006. };
  71007. return BinaryFileAssetTask;
  71008. }(AbstractAssetTask));
  71009. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  71010. var ImageAssetTask = (function (_super) {
  71011. __extends(ImageAssetTask, _super);
  71012. function ImageAssetTask(name, url) {
  71013. var _this = _super.call(this) || this;
  71014. _this.name = name;
  71015. _this.url = url;
  71016. return _this;
  71017. }
  71018. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  71019. var _this = this;
  71020. var img = new Image();
  71021. BABYLON.Tools.SetCorsBehavior(this.url, img);
  71022. img.onload = function () {
  71023. _this.image = img;
  71024. onSuccess();
  71025. };
  71026. img.onerror = function (err) {
  71027. onError("Error loading image", err);
  71028. };
  71029. img.src = this.url;
  71030. };
  71031. return ImageAssetTask;
  71032. }(AbstractAssetTask));
  71033. BABYLON.ImageAssetTask = ImageAssetTask;
  71034. var TextureAssetTask = (function (_super) {
  71035. __extends(TextureAssetTask, _super);
  71036. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  71037. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71038. var _this = _super.call(this) || this;
  71039. _this.name = name;
  71040. _this.url = url;
  71041. _this.noMipmap = noMipmap;
  71042. _this.invertY = invertY;
  71043. _this.samplingMode = samplingMode;
  71044. return _this;
  71045. }
  71046. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  71047. var onload = function () {
  71048. onSuccess();
  71049. };
  71050. var onerror = function (msg, exception) {
  71051. onError(msg, exception);
  71052. };
  71053. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  71054. };
  71055. return TextureAssetTask;
  71056. }(AbstractAssetTask));
  71057. BABYLON.TextureAssetTask = TextureAssetTask;
  71058. var CubeTextureAssetTask = (function (_super) {
  71059. __extends(CubeTextureAssetTask, _super);
  71060. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  71061. var _this = _super.call(this) || this;
  71062. _this.name = name;
  71063. _this.url = url;
  71064. _this.extensions = extensions;
  71065. _this.noMipmap = noMipmap;
  71066. _this.files = files;
  71067. return _this;
  71068. }
  71069. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  71070. var onload = function () {
  71071. onSuccess();
  71072. };
  71073. var onerror = function (msg, exception) {
  71074. onError(msg, exception);
  71075. };
  71076. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  71077. };
  71078. return CubeTextureAssetTask;
  71079. }(AbstractAssetTask));
  71080. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  71081. var HDRCubeTextureAssetTask = (function (_super) {
  71082. __extends(HDRCubeTextureAssetTask, _super);
  71083. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  71084. if (noMipmap === void 0) { noMipmap = false; }
  71085. if (generateHarmonics === void 0) { generateHarmonics = true; }
  71086. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  71087. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  71088. var _this = _super.call(this) || this;
  71089. _this.name = name;
  71090. _this.url = url;
  71091. _this.size = size;
  71092. _this.noMipmap = noMipmap;
  71093. _this.generateHarmonics = generateHarmonics;
  71094. _this.useInGammaSpace = useInGammaSpace;
  71095. _this.usePMREMGenerator = usePMREMGenerator;
  71096. return _this;
  71097. }
  71098. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  71099. var onload = function () {
  71100. onSuccess();
  71101. };
  71102. var onerror = function (message, exception) {
  71103. onError(message, exception);
  71104. };
  71105. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  71106. };
  71107. return HDRCubeTextureAssetTask;
  71108. }(AbstractAssetTask));
  71109. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  71110. var AssetsManager = (function () {
  71111. function AssetsManager(scene) {
  71112. this.tasks = new Array();
  71113. this.waitingTasksCount = 0;
  71114. //Observables
  71115. this.onTaskSuccessObservable = new BABYLON.Observable();
  71116. this.onTaskErrorObservable = new BABYLON.Observable();
  71117. this.onTasksDoneObservable = new BABYLON.Observable();
  71118. this.useDefaultLoadingScreen = true;
  71119. this._scene = scene;
  71120. }
  71121. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  71122. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  71123. this.tasks.push(task);
  71124. return task;
  71125. };
  71126. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  71127. var task = new TextFileAssetTask(taskName, url);
  71128. this.tasks.push(task);
  71129. return task;
  71130. };
  71131. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  71132. var task = new BinaryFileAssetTask(taskName, url);
  71133. this.tasks.push(task);
  71134. return task;
  71135. };
  71136. AssetsManager.prototype.addImageTask = function (taskName, url) {
  71137. var task = new ImageAssetTask(taskName, url);
  71138. this.tasks.push(task);
  71139. return task;
  71140. };
  71141. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  71142. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71143. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  71144. this.tasks.push(task);
  71145. return task;
  71146. };
  71147. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  71148. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  71149. this.tasks.push(task);
  71150. return task;
  71151. };
  71152. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  71153. if (noMipmap === void 0) { noMipmap = false; }
  71154. if (generateHarmonics === void 0) { generateHarmonics = true; }
  71155. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  71156. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  71157. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  71158. this.tasks.push(task);
  71159. return task;
  71160. };
  71161. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  71162. this.waitingTasksCount--;
  71163. if (this.waitingTasksCount === 0) {
  71164. try {
  71165. if (this.onFinish) {
  71166. this.onFinish(this.tasks);
  71167. }
  71168. this.onTasksDoneObservable.notifyObservers(this.tasks);
  71169. }
  71170. catch (e) {
  71171. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  71172. console.log(e);
  71173. }
  71174. this._scene.getEngine().hideLoadingUI();
  71175. }
  71176. };
  71177. AssetsManager.prototype._runTask = function (task) {
  71178. var _this = this;
  71179. var done = function () {
  71180. try {
  71181. if (_this.onTaskSuccess) {
  71182. _this.onTaskSuccess(task);
  71183. }
  71184. _this.onTaskSuccessObservable.notifyObservers(task);
  71185. _this._decreaseWaitingTasksCount();
  71186. }
  71187. catch (e) {
  71188. error("Error executing task success callbacks", e);
  71189. }
  71190. };
  71191. var error = function (message, exception) {
  71192. task.errorObject = task.errorObject || {
  71193. message: message,
  71194. exception: exception
  71195. };
  71196. if (_this.onTaskError) {
  71197. _this.onTaskError(task);
  71198. }
  71199. _this.onTaskErrorObservable.notifyObservers(task);
  71200. _this._decreaseWaitingTasksCount();
  71201. };
  71202. task.run(this._scene, done, error);
  71203. };
  71204. AssetsManager.prototype.reset = function () {
  71205. this.tasks = new Array();
  71206. return this;
  71207. };
  71208. AssetsManager.prototype.load = function () {
  71209. this.waitingTasksCount = this.tasks.length;
  71210. if (this.waitingTasksCount === 0) {
  71211. if (this.onFinish) {
  71212. this.onFinish(this.tasks);
  71213. }
  71214. this.onTasksDoneObservable.notifyObservers(this.tasks);
  71215. return this;
  71216. }
  71217. if (this.useDefaultLoadingScreen) {
  71218. this._scene.getEngine().displayLoadingUI();
  71219. }
  71220. for (var index = 0; index < this.tasks.length; index++) {
  71221. var task = this.tasks[index];
  71222. this._runTask(task);
  71223. }
  71224. return this;
  71225. };
  71226. return AssetsManager;
  71227. }());
  71228. BABYLON.AssetsManager = AssetsManager;
  71229. })(BABYLON || (BABYLON = {}));
  71230. //# sourceMappingURL=babylon.assetsManager.js.map
  71231. var BABYLON;
  71232. (function (BABYLON) {
  71233. var MapTexture = (function (_super) {
  71234. __extends(MapTexture, _super);
  71235. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  71236. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71237. if (useMipMap === void 0) { useMipMap = false; }
  71238. if (margin === void 0) { margin = 0; }
  71239. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  71240. _this.name = name;
  71241. _this._size = size;
  71242. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71243. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71244. // Create the rectPackMap that will allocate portion of the texture
  71245. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  71246. // Create the texture that will store the content
  71247. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  71248. return _this;
  71249. }
  71250. /**
  71251. * Allocate a rectangle of a given size in the texture map
  71252. * @param size the size of the rectangle to allocation
  71253. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  71254. */
  71255. MapTexture.prototype.allocateRect = function (size) {
  71256. return this._rectPackingMap.addRect(size);
  71257. };
  71258. /**
  71259. * Free a given rectangle from the texture map
  71260. * @param rectInfo the instance corresponding to the rect to free.
  71261. */
  71262. MapTexture.prototype.freeRect = function (rectInfo) {
  71263. if (rectInfo) {
  71264. rectInfo.freeContent();
  71265. }
  71266. };
  71267. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  71268. /**
  71269. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  71270. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  71271. * @returns {}
  71272. */
  71273. get: function () {
  71274. return this._rectPackingMap.freeSpace;
  71275. },
  71276. enumerable: true,
  71277. configurable: true
  71278. });
  71279. /**
  71280. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  71281. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  71282. * Don't forget to call unbindTexture when you're done rendering
  71283. * @param rect the zone to render to
  71284. * @param clear true to clear the portion's color/depth data
  71285. */
  71286. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  71287. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  71288. };
  71289. /**
  71290. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  71291. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  71292. * Don't forget to call unbindTexture when you're done rendering
  71293. * @param pos the position into the texture
  71294. * @param size the portion to fit the clip space to
  71295. * @param clear true to clear the portion's color/depth data
  71296. */
  71297. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  71298. var engine = this.getScene().getEngine();
  71299. engine.bindFramebuffer(this._texture);
  71300. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  71301. if (clear) {
  71302. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  71303. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  71304. }
  71305. };
  71306. /**
  71307. * Unbind the texture map from the rendering engine.
  71308. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  71309. * @param dumpForDebug if set to true the content of the texture map will be dumped to a picture file that will be sent to the internet browser.
  71310. */
  71311. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  71312. // Dump ?
  71313. if (dumpForDebug) {
  71314. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  71315. }
  71316. var engine = this.getScene().getEngine();
  71317. if (this._replacedViewport) {
  71318. engine.setViewport(this._replacedViewport);
  71319. this._replacedViewport = null;
  71320. }
  71321. engine.unBindFramebuffer(this._texture);
  71322. };
  71323. Object.defineProperty(MapTexture.prototype, "canRescale", {
  71324. get: function () {
  71325. return false;
  71326. },
  71327. enumerable: true,
  71328. configurable: true
  71329. });
  71330. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  71331. // Anyway, there's not much point to use this method for this kind of texture I guess
  71332. MapTexture.prototype.clone = function () {
  71333. return null;
  71334. };
  71335. return MapTexture;
  71336. }(BABYLON.Texture));
  71337. BABYLON.MapTexture = MapTexture;
  71338. })(BABYLON || (BABYLON = {}));
  71339. //# sourceMappingURL=babylon.mapTexture.js.map
  71340. var BABYLON;
  71341. (function (BABYLON) {
  71342. /**
  71343. * This class describe a rectangle that were added to the map.
  71344. * You have access to its coordinates either in pixel or normalized (UV)
  71345. */
  71346. var PackedRect = (function () {
  71347. function PackedRect(root, parent, pos, size) {
  71348. this._pos = pos;
  71349. this._size = size;
  71350. this._root = root;
  71351. this._parent = parent;
  71352. this._contentSize = null;
  71353. this._bottomNode = null;
  71354. this._leftNode = null;
  71355. this._initialSize = null;
  71356. this._rightNode = null;
  71357. }
  71358. Object.defineProperty(PackedRect.prototype, "pos", {
  71359. /**
  71360. * @returns the position of this node into the map
  71361. */
  71362. get: function () {
  71363. return this._pos;
  71364. },
  71365. enumerable: true,
  71366. configurable: true
  71367. });
  71368. Object.defineProperty(PackedRect.prototype, "contentSize", {
  71369. /**
  71370. * @returns the size of the rectangle this node handles
  71371. */
  71372. get: function () {
  71373. return this._contentSize;
  71374. },
  71375. enumerable: true,
  71376. configurable: true
  71377. });
  71378. /**
  71379. * Retrieve the inner position (considering the margin) and stores it into the res object
  71380. * @param res must be a valid Vector2 that will contain the inner position after this call
  71381. */
  71382. PackedRect.prototype.getInnerPosToRef = function (res) {
  71383. var m = this._root._margin;
  71384. res.x = this._pos.x + m;
  71385. res.y = this._pos.y + m;
  71386. };
  71387. /**
  71388. * Retrieve the inner size (considering the margin) and stores it into the res object
  71389. * @param res must be a valid Size that will contain the inner size after this call
  71390. */
  71391. PackedRect.prototype.getInnerSizeToRef = function (res) {
  71392. var m = this._root._margin;
  71393. res.width = this._contentSize.width - (m * 2);
  71394. res.height = this._contentSize.height - (m * 2);
  71395. };
  71396. Object.defineProperty(PackedRect.prototype, "UVs", {
  71397. /**
  71398. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  71399. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  71400. */
  71401. get: function () {
  71402. if (!this._contentSize) {
  71403. throw new Error("Can't compute UVs for this object because it's nor allocated");
  71404. }
  71405. return this.getUVsForCustomSize(this._contentSize);
  71406. },
  71407. enumerable: true,
  71408. configurable: true
  71409. });
  71410. /**
  71411. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  71412. * and then using only a part of the PackRect.
  71413. * This method will return the UVs for this part by given the custom size of what you really use
  71414. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  71415. */
  71416. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  71417. var mainWidth = this._root._size.width;
  71418. var mainHeight = this._root._size.height;
  71419. var margin = this._root._margin;
  71420. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  71421. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  71422. var uvs = new Array();
  71423. uvs.push(topLeft);
  71424. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  71425. uvs.push(rightBottom);
  71426. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  71427. return uvs;
  71428. };
  71429. /**
  71430. * Free this rectangle from the map.
  71431. * Call this method when you no longer need the rectangle to be in the map.
  71432. */
  71433. PackedRect.prototype.freeContent = function () {
  71434. if (!this.contentSize) {
  71435. return;
  71436. }
  71437. this._contentSize = null;
  71438. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  71439. this.attemptDefrag();
  71440. };
  71441. Object.defineProperty(PackedRect.prototype, "isUsed", {
  71442. get: function () {
  71443. return this._contentSize != null || this._leftNode != null;
  71444. },
  71445. enumerable: true,
  71446. configurable: true
  71447. });
  71448. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  71449. var node = this.findNode(contentSize);
  71450. // Not enough space...
  71451. if (!node) {
  71452. return null;
  71453. }
  71454. node.splitNode(contentSize);
  71455. return node;
  71456. };
  71457. PackedRect.prototype.findNode = function (size) {
  71458. var resNode = null;
  71459. var margin = this._root._margin * 2;
  71460. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  71461. if (this.isUsed) {
  71462. if (this._leftNode) {
  71463. resNode = this._leftNode.findNode(size);
  71464. }
  71465. if (!resNode && this._rightNode) {
  71466. resNode = this._rightNode.findNode(size);
  71467. }
  71468. if (!resNode && this._bottomNode) {
  71469. resNode = this._bottomNode.findNode(size);
  71470. }
  71471. }
  71472. else if (this._initialSize) {
  71473. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  71474. resNode = this;
  71475. }
  71476. else {
  71477. return null;
  71478. }
  71479. }
  71480. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  71481. resNode = this;
  71482. }
  71483. return resNode;
  71484. };
  71485. PackedRect.prototype.splitNode = function (contentSize) {
  71486. var cs = PackedRect.TpsSize;
  71487. var margin = this._root._margin * 2;
  71488. cs.copyFrom(contentSize);
  71489. cs.width += margin;
  71490. cs.height += margin;
  71491. // If there's no contentSize but an initialSize it means this node were previously allocated, but freed, we need to create a _leftNode as subNode and use to allocate the space we need (and this node will have a right/bottom subNode for the space left as this._initialSize may be greater than contentSize)
  71492. if (!this._contentSize && this._initialSize) {
  71493. this._contentSize = cs.clone();
  71494. this._leftNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y), new BABYLON.Size(this._initialSize.width, this._initialSize.height));
  71495. return this._leftNode.splitNode(contentSize);
  71496. }
  71497. else {
  71498. this._contentSize = cs.clone();
  71499. this._initialSize = cs.clone();
  71500. if (cs.width !== this._size.width) {
  71501. this._rightNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x + cs.width, this._pos.y), new BABYLON.Size(this._size.width - cs.width, cs.height));
  71502. }
  71503. if (cs.height !== this._size.height) {
  71504. this._bottomNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y + cs.height), new BABYLON.Size(this._size.width, this._size.height - cs.height));
  71505. }
  71506. return this;
  71507. }
  71508. };
  71509. PackedRect.prototype.attemptDefrag = function () {
  71510. if (!this.isUsed && this.isRecursiveFree) {
  71511. this.clearNode();
  71512. if (this._parent) {
  71513. this._parent.attemptDefrag();
  71514. }
  71515. }
  71516. };
  71517. PackedRect.prototype.clearNode = function () {
  71518. this._initialSize = null;
  71519. this._rightNode = null;
  71520. this._bottomNode = null;
  71521. };
  71522. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  71523. get: function () {
  71524. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  71525. },
  71526. enumerable: true,
  71527. configurable: true
  71528. });
  71529. PackedRect.prototype.evalFreeSize = function (size) {
  71530. var levelSize = 0;
  71531. if (!this.isUsed) {
  71532. var margin = this._root._margin;
  71533. var is = this._initialSize;
  71534. if (is) {
  71535. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  71536. }
  71537. else {
  71538. var size_1 = this._size;
  71539. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  71540. }
  71541. }
  71542. if (this._rightNode) {
  71543. levelSize += this._rightNode.evalFreeSize(0);
  71544. }
  71545. if (this._bottomNode) {
  71546. levelSize += this._bottomNode.evalFreeSize(0);
  71547. }
  71548. return levelSize + size;
  71549. };
  71550. PackedRect.TpsSize = BABYLON.Size.Zero();
  71551. return PackedRect;
  71552. }());
  71553. BABYLON.PackedRect = PackedRect;
  71554. /**
  71555. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  71556. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  71557. * Note that this class allows allocated Rectangles to be freed: that is the map is dynamically maintained so you can add/remove rectangle based on their life-cycle.
  71558. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  71559. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  71560. */
  71561. var RectPackingMap = (function (_super) {
  71562. __extends(RectPackingMap, _super);
  71563. /**
  71564. * Create an instance of the object with a dimension using the given size
  71565. * @param size The dimension of the rectangle that will contain all the sub ones.
  71566. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  71567. */
  71568. function RectPackingMap(size, margin) {
  71569. if (margin === void 0) { margin = 0; }
  71570. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  71571. _this._margin = margin;
  71572. _this._root = _this;
  71573. return _this;
  71574. }
  71575. /**
  71576. * Add a rectangle, finding the best location to store it into the map
  71577. * @param size the dimension of the rectangle to store
  71578. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  71579. */
  71580. RectPackingMap.prototype.addRect = function (size) {
  71581. var node = this.findAndSplitNode(size);
  71582. return node;
  71583. };
  71584. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  71585. /**
  71586. * Return the current space free normalized between [0;1]
  71587. * @returns {}
  71588. */
  71589. get: function () {
  71590. var freeSize = 0;
  71591. freeSize = this.evalFreeSize(freeSize);
  71592. return freeSize / (this._size.width * this._size.height);
  71593. },
  71594. enumerable: true,
  71595. configurable: true
  71596. });
  71597. return RectPackingMap;
  71598. }(PackedRect));
  71599. BABYLON.RectPackingMap = RectPackingMap;
  71600. })(BABYLON || (BABYLON = {}));
  71601. //# sourceMappingURL=babylon.rectPackingMap.js.map
  71602. var BABYLON;
  71603. (function (BABYLON) {
  71604. var serializedGeometries = [];
  71605. var serializeGeometry = function (geometry, serializationGeometries) {
  71606. if (serializedGeometries[geometry.id]) {
  71607. return;
  71608. }
  71609. if (geometry.doNotSerialize) {
  71610. return;
  71611. }
  71612. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  71613. serializationGeometries.boxes.push(geometry.serialize());
  71614. }
  71615. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  71616. serializationGeometries.spheres.push(geometry.serialize());
  71617. }
  71618. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  71619. serializationGeometries.cylinders.push(geometry.serialize());
  71620. }
  71621. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  71622. serializationGeometries.toruses.push(geometry.serialize());
  71623. }
  71624. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  71625. serializationGeometries.grounds.push(geometry.serialize());
  71626. }
  71627. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  71628. serializationGeometries.planes.push(geometry.serialize());
  71629. }
  71630. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  71631. serializationGeometries.torusKnots.push(geometry.serialize());
  71632. }
  71633. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  71634. throw new Error("Unknown primitive type");
  71635. }
  71636. else {
  71637. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  71638. }
  71639. serializedGeometries[geometry.id] = true;
  71640. };
  71641. var serializeMesh = function (mesh, serializationScene) {
  71642. var serializationObject = {};
  71643. // Geometry
  71644. var geometry = mesh._geometry;
  71645. if (geometry) {
  71646. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  71647. // 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
  71648. serializeGeometry(geometry, serializationScene.geometries);
  71649. }
  71650. }
  71651. // Custom
  71652. if (mesh.serialize) {
  71653. mesh.serialize(serializationObject);
  71654. }
  71655. return serializationObject;
  71656. };
  71657. var finalizeSingleMesh = function (mesh, serializationObject) {
  71658. //only works if the mesh is already loaded
  71659. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  71660. //serialize material
  71661. if (mesh.material) {
  71662. if (mesh.material instanceof BABYLON.StandardMaterial) {
  71663. serializationObject.materials = serializationObject.materials || [];
  71664. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  71665. serializationObject.materials.push(mesh.material.serialize());
  71666. }
  71667. }
  71668. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  71669. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  71670. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  71671. serializationObject.multiMaterials.push(mesh.material.serialize());
  71672. }
  71673. }
  71674. }
  71675. //serialize geometry
  71676. var geometry = mesh._geometry;
  71677. if (geometry) {
  71678. if (!serializationObject.geometries) {
  71679. serializationObject.geometries = {};
  71680. serializationObject.geometries.boxes = [];
  71681. serializationObject.geometries.spheres = [];
  71682. serializationObject.geometries.cylinders = [];
  71683. serializationObject.geometries.toruses = [];
  71684. serializationObject.geometries.grounds = [];
  71685. serializationObject.geometries.planes = [];
  71686. serializationObject.geometries.torusKnots = [];
  71687. serializationObject.geometries.vertexData = [];
  71688. }
  71689. serializeGeometry(geometry, serializationObject.geometries);
  71690. }
  71691. // Skeletons
  71692. if (mesh.skeleton) {
  71693. serializationObject.skeletons = serializationObject.skeletons || [];
  71694. serializationObject.skeletons.push(mesh.skeleton.serialize());
  71695. }
  71696. //serialize the actual mesh
  71697. serializationObject.meshes = serializationObject.meshes || [];
  71698. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  71699. }
  71700. };
  71701. var SceneSerializer = (function () {
  71702. function SceneSerializer() {
  71703. }
  71704. SceneSerializer.ClearCache = function () {
  71705. serializedGeometries = [];
  71706. };
  71707. SceneSerializer.Serialize = function (scene) {
  71708. var serializationObject = {};
  71709. SceneSerializer.ClearCache();
  71710. // Scene
  71711. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  71712. serializationObject.autoClear = scene.autoClear;
  71713. serializationObject.clearColor = scene.clearColor.asArray();
  71714. serializationObject.ambientColor = scene.ambientColor.asArray();
  71715. serializationObject.gravity = scene.gravity.asArray();
  71716. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  71717. serializationObject.workerCollisions = scene.workerCollisions;
  71718. // Fog
  71719. if (scene.fogMode && scene.fogMode !== 0) {
  71720. serializationObject.fogMode = scene.fogMode;
  71721. serializationObject.fogColor = scene.fogColor.asArray();
  71722. serializationObject.fogStart = scene.fogStart;
  71723. serializationObject.fogEnd = scene.fogEnd;
  71724. serializationObject.fogDensity = scene.fogDensity;
  71725. }
  71726. //Physics
  71727. if (scene.isPhysicsEnabled()) {
  71728. serializationObject.physicsEnabled = true;
  71729. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  71730. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  71731. }
  71732. // Metadata
  71733. if (scene.metadata) {
  71734. serializationObject.metadata = scene.metadata;
  71735. }
  71736. // Morph targets
  71737. serializationObject.morphTargetManagers = [];
  71738. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  71739. var abstractMesh = _a[_i];
  71740. var manager = abstractMesh.morphTargetManager;
  71741. if (manager) {
  71742. serializationObject.morphTargetManagers.push(manager.serialize());
  71743. }
  71744. }
  71745. // Lights
  71746. serializationObject.lights = [];
  71747. var index;
  71748. var light;
  71749. for (index = 0; index < scene.lights.length; index++) {
  71750. light = scene.lights[index];
  71751. if (!light.doNotSerialize) {
  71752. serializationObject.lights.push(light.serialize());
  71753. }
  71754. }
  71755. // Cameras
  71756. serializationObject.cameras = [];
  71757. for (index = 0; index < scene.cameras.length; index++) {
  71758. var camera = scene.cameras[index];
  71759. if (!camera.doNotSerialize) {
  71760. serializationObject.cameras.push(camera.serialize());
  71761. }
  71762. }
  71763. if (scene.activeCamera) {
  71764. serializationObject.activeCameraID = scene.activeCamera.id;
  71765. }
  71766. // Animations
  71767. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  71768. // Materials
  71769. serializationObject.materials = [];
  71770. serializationObject.multiMaterials = [];
  71771. var material;
  71772. for (index = 0; index < scene.materials.length; index++) {
  71773. material = scene.materials[index];
  71774. if (!material.doNotSerialize) {
  71775. serializationObject.materials.push(material.serialize());
  71776. }
  71777. }
  71778. // MultiMaterials
  71779. serializationObject.multiMaterials = [];
  71780. for (index = 0; index < scene.multiMaterials.length; index++) {
  71781. var multiMaterial = scene.multiMaterials[index];
  71782. serializationObject.multiMaterials.push(multiMaterial.serialize());
  71783. }
  71784. // Skeletons
  71785. serializationObject.skeletons = [];
  71786. for (index = 0; index < scene.skeletons.length; index++) {
  71787. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  71788. }
  71789. // Geometries
  71790. serializationObject.geometries = {};
  71791. serializationObject.geometries.boxes = [];
  71792. serializationObject.geometries.spheres = [];
  71793. serializationObject.geometries.cylinders = [];
  71794. serializationObject.geometries.toruses = [];
  71795. serializationObject.geometries.grounds = [];
  71796. serializationObject.geometries.planes = [];
  71797. serializationObject.geometries.torusKnots = [];
  71798. serializationObject.geometries.vertexData = [];
  71799. serializedGeometries = [];
  71800. var geometries = scene.getGeometries();
  71801. for (index = 0; index < geometries.length; index++) {
  71802. var geometry = geometries[index];
  71803. if (geometry.isReady()) {
  71804. serializeGeometry(geometry, serializationObject.geometries);
  71805. }
  71806. }
  71807. // Meshes
  71808. serializationObject.meshes = [];
  71809. for (index = 0; index < scene.meshes.length; index++) {
  71810. var abstractMesh = scene.meshes[index];
  71811. if (abstractMesh instanceof BABYLON.Mesh) {
  71812. var mesh = abstractMesh;
  71813. if (!mesh.doNotSerialize) {
  71814. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  71815. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  71816. }
  71817. }
  71818. }
  71819. }
  71820. // Particles Systems
  71821. serializationObject.particleSystems = [];
  71822. for (index = 0; index < scene.particleSystems.length; index++) {
  71823. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  71824. }
  71825. // Lens flares
  71826. serializationObject.lensFlareSystems = [];
  71827. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  71828. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  71829. }
  71830. // Shadows
  71831. serializationObject.shadowGenerators = [];
  71832. for (index = 0; index < scene.lights.length; index++) {
  71833. light = scene.lights[index];
  71834. var shadowGenerator = light.getShadowGenerator();
  71835. if (shadowGenerator) {
  71836. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  71837. }
  71838. }
  71839. // Action Manager
  71840. if (scene.actionManager) {
  71841. serializationObject.actions = scene.actionManager.serialize("scene");
  71842. }
  71843. // Audio
  71844. serializationObject.sounds = [];
  71845. for (index = 0; index < scene.soundTracks.length; index++) {
  71846. var soundtrack = scene.soundTracks[index];
  71847. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  71848. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  71849. }
  71850. }
  71851. return serializationObject;
  71852. };
  71853. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  71854. if (withParents === void 0) { withParents = false; }
  71855. if (withChildren === void 0) { withChildren = false; }
  71856. var serializationObject = {};
  71857. SceneSerializer.ClearCache();
  71858. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  71859. if (withParents || withChildren) {
  71860. //deliberate for loop! not for each, appended should be processed as well.
  71861. for (var i = 0; i < toSerialize.length; ++i) {
  71862. if (withChildren) {
  71863. toSerialize[i].getDescendants().forEach(function (node) {
  71864. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  71865. toSerialize.push(node);
  71866. }
  71867. });
  71868. }
  71869. //make sure the array doesn't contain the object already
  71870. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  71871. toSerialize.push(toSerialize[i].parent);
  71872. }
  71873. }
  71874. }
  71875. toSerialize.forEach(function (mesh) {
  71876. finalizeSingleMesh(mesh, serializationObject);
  71877. });
  71878. return serializationObject;
  71879. };
  71880. return SceneSerializer;
  71881. }());
  71882. BABYLON.SceneSerializer = SceneSerializer;
  71883. })(BABYLON || (BABYLON = {}));
  71884. //# sourceMappingURL=babylon.sceneSerializer.js.map
  71885. var BABYLON;
  71886. (function (BABYLON) {
  71887. var ReflectionProbe = (function () {
  71888. function ReflectionProbe(name, size, scene, generateMipMaps) {
  71889. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71890. var _this = this;
  71891. this.name = name;
  71892. this._viewMatrix = BABYLON.Matrix.Identity();
  71893. this._target = BABYLON.Vector3.Zero();
  71894. this._add = BABYLON.Vector3.Zero();
  71895. this.invertYAxis = false;
  71896. this.position = BABYLON.Vector3.Zero();
  71897. this._scene = scene;
  71898. this._scene.reflectionProbes.push(this);
  71899. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  71900. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  71901. switch (faceIndex) {
  71902. case 0:
  71903. _this._add.copyFromFloats(1, 0, 0);
  71904. break;
  71905. case 1:
  71906. _this._add.copyFromFloats(-1, 0, 0);
  71907. break;
  71908. case 2:
  71909. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  71910. break;
  71911. case 3:
  71912. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  71913. break;
  71914. case 4:
  71915. _this._add.copyFromFloats(0, 0, 1);
  71916. break;
  71917. case 5:
  71918. _this._add.copyFromFloats(0, 0, -1);
  71919. break;
  71920. }
  71921. if (_this._attachedMesh) {
  71922. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  71923. }
  71924. _this.position.addToRef(_this._add, _this._target);
  71925. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  71926. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  71927. });
  71928. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  71929. scene.updateTransformMatrix(true);
  71930. });
  71931. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  71932. }
  71933. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  71934. get: function () {
  71935. return this._renderTargetTexture.samples;
  71936. },
  71937. set: function (value) {
  71938. this._renderTargetTexture.samples = value;
  71939. },
  71940. enumerable: true,
  71941. configurable: true
  71942. });
  71943. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  71944. get: function () {
  71945. return this._renderTargetTexture.refreshRate;
  71946. },
  71947. set: function (value) {
  71948. this._renderTargetTexture.refreshRate = value;
  71949. },
  71950. enumerable: true,
  71951. configurable: true
  71952. });
  71953. ReflectionProbe.prototype.getScene = function () {
  71954. return this._scene;
  71955. };
  71956. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  71957. get: function () {
  71958. return this._renderTargetTexture;
  71959. },
  71960. enumerable: true,
  71961. configurable: true
  71962. });
  71963. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  71964. get: function () {
  71965. return this._renderTargetTexture.renderList;
  71966. },
  71967. enumerable: true,
  71968. configurable: true
  71969. });
  71970. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  71971. this._attachedMesh = mesh;
  71972. };
  71973. /**
  71974. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  71975. *
  71976. * @param renderingGroupId The rendering group id corresponding to its index
  71977. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  71978. */
  71979. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  71980. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  71981. };
  71982. ReflectionProbe.prototype.dispose = function () {
  71983. var index = this._scene.reflectionProbes.indexOf(this);
  71984. if (index !== -1) {
  71985. // Remove from the scene if found
  71986. this._scene.reflectionProbes.splice(index, 1);
  71987. }
  71988. if (this._renderTargetTexture) {
  71989. this._renderTargetTexture.dispose();
  71990. this._renderTargetTexture = null;
  71991. }
  71992. };
  71993. return ReflectionProbe;
  71994. }());
  71995. BABYLON.ReflectionProbe = ReflectionProbe;
  71996. })(BABYLON || (BABYLON = {}));
  71997. //# sourceMappingURL=babylon.reflectionProbe.js.map
  71998. var BABYLON;
  71999. (function (BABYLON) {
  72000. var Layer = (function () {
  72001. function Layer(name, imgUrl, scene, isBackground, color) {
  72002. this.name = name;
  72003. this.scale = new BABYLON.Vector2(1, 1);
  72004. this.offset = new BABYLON.Vector2(0, 0);
  72005. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  72006. this.layerMask = 0x0FFFFFFF;
  72007. this._vertexBuffers = {};
  72008. // Events
  72009. /**
  72010. * An event triggered when the layer is disposed.
  72011. * @type {BABYLON.Observable}
  72012. */
  72013. this.onDisposeObservable = new BABYLON.Observable();
  72014. /**
  72015. * An event triggered before rendering the scene
  72016. * @type {BABYLON.Observable}
  72017. */
  72018. this.onBeforeRenderObservable = new BABYLON.Observable();
  72019. /**
  72020. * An event triggered after rendering the scene
  72021. * @type {BABYLON.Observable}
  72022. */
  72023. this.onAfterRenderObservable = new BABYLON.Observable();
  72024. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  72025. this.isBackground = isBackground === undefined ? true : isBackground;
  72026. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  72027. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72028. this._scene.layers.push(this);
  72029. var engine = this._scene.getEngine();
  72030. // VBO
  72031. var vertices = [];
  72032. vertices.push(1, 1);
  72033. vertices.push(-1, 1);
  72034. vertices.push(-1, -1);
  72035. vertices.push(1, -1);
  72036. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72037. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  72038. this._createIndexBuffer();
  72039. // Effects
  72040. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  72041. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  72042. }
  72043. Object.defineProperty(Layer.prototype, "onDispose", {
  72044. set: function (callback) {
  72045. if (this._onDisposeObserver) {
  72046. this.onDisposeObservable.remove(this._onDisposeObserver);
  72047. }
  72048. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  72049. },
  72050. enumerable: true,
  72051. configurable: true
  72052. });
  72053. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  72054. set: function (callback) {
  72055. if (this._onBeforeRenderObserver) {
  72056. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  72057. }
  72058. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  72059. },
  72060. enumerable: true,
  72061. configurable: true
  72062. });
  72063. Object.defineProperty(Layer.prototype, "onAfterRender", {
  72064. set: function (callback) {
  72065. if (this._onAfterRenderObserver) {
  72066. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  72067. }
  72068. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  72069. },
  72070. enumerable: true,
  72071. configurable: true
  72072. });
  72073. Layer.prototype._createIndexBuffer = function () {
  72074. var engine = this._scene.getEngine();
  72075. // Indices
  72076. var indices = [];
  72077. indices.push(0);
  72078. indices.push(1);
  72079. indices.push(2);
  72080. indices.push(0);
  72081. indices.push(2);
  72082. indices.push(3);
  72083. this._indexBuffer = engine.createIndexBuffer(indices);
  72084. };
  72085. Layer.prototype._rebuild = function () {
  72086. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  72087. this._createIndexBuffer();
  72088. };
  72089. Layer.prototype.render = function () {
  72090. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  72091. // Check
  72092. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  72093. return;
  72094. var engine = this._scene.getEngine();
  72095. this.onBeforeRenderObservable.notifyObservers(this);
  72096. // Render
  72097. engine.enableEffect(currentEffect);
  72098. engine.setState(false);
  72099. // Texture
  72100. currentEffect.setTexture("textureSampler", this.texture);
  72101. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  72102. // Color
  72103. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  72104. // Scale / offset
  72105. currentEffect.setVector2("offset", this.offset);
  72106. currentEffect.setVector2("scale", this.scale);
  72107. // VBOs
  72108. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  72109. // Draw order
  72110. if (!this.alphaTest) {
  72111. engine.setAlphaMode(this.alphaBlendingMode);
  72112. engine.draw(true, 0, 6);
  72113. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  72114. }
  72115. else {
  72116. engine.draw(true, 0, 6);
  72117. }
  72118. this.onAfterRenderObservable.notifyObservers(this);
  72119. };
  72120. Layer.prototype.dispose = function () {
  72121. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72122. if (vertexBuffer) {
  72123. vertexBuffer.dispose();
  72124. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72125. }
  72126. if (this._indexBuffer) {
  72127. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  72128. this._indexBuffer = null;
  72129. }
  72130. if (this.texture) {
  72131. this.texture.dispose();
  72132. this.texture = null;
  72133. }
  72134. // Remove from scene
  72135. var index = this._scene.layers.indexOf(this);
  72136. this._scene.layers.splice(index, 1);
  72137. // Callback
  72138. this.onDisposeObservable.notifyObservers(this);
  72139. this.onDisposeObservable.clear();
  72140. this.onAfterRenderObservable.clear();
  72141. this.onBeforeRenderObservable.clear();
  72142. };
  72143. return Layer;
  72144. }());
  72145. BABYLON.Layer = Layer;
  72146. })(BABYLON || (BABYLON = {}));
  72147. //# sourceMappingURL=babylon.layer.js.map
  72148. var BABYLON;
  72149. (function (BABYLON) {
  72150. var TextureTools = (function () {
  72151. function TextureTools() {
  72152. }
  72153. /**
  72154. * Uses the GPU to create a copy texture rescaled at a given size
  72155. * @param texture Texture to copy from
  72156. * @param width Desired width
  72157. * @param height Desired height
  72158. * @return Generated texture
  72159. */
  72160. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  72161. if (useBilinearMode === void 0) { useBilinearMode = true; }
  72162. var scene = texture.getScene();
  72163. var engine = scene.getEngine();
  72164. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  72165. rtt.wrapU = texture.wrapU;
  72166. rtt.wrapV = texture.wrapV;
  72167. rtt.uOffset = texture.uOffset;
  72168. rtt.vOffset = texture.vOffset;
  72169. rtt.uScale = texture.uScale;
  72170. rtt.vScale = texture.vScale;
  72171. rtt.uAng = texture.uAng;
  72172. rtt.vAng = texture.vAng;
  72173. rtt.wAng = texture.wAng;
  72174. rtt.coordinatesIndex = texture.coordinatesIndex;
  72175. rtt.level = texture.level;
  72176. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  72177. rtt._texture.isReady = false;
  72178. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72179. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72180. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72181. passPostProcess.getEffect().executeWhenCompiled(function () {
  72182. passPostProcess.onApply = function (effect) {
  72183. effect.setTexture("textureSampler", texture);
  72184. };
  72185. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  72186. engine.unBindFramebuffer(rtt.getInternalTexture());
  72187. rtt.disposeFramebufferObjects();
  72188. passPostProcess.dispose();
  72189. rtt._texture.isReady = true;
  72190. });
  72191. return rtt;
  72192. };
  72193. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  72194. if (!scene._environmentBRDFTexture) {
  72195. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72196. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72197. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72198. scene._environmentBRDFTexture = texture;
  72199. }
  72200. return scene._environmentBRDFTexture;
  72201. };
  72202. 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=";
  72203. return TextureTools;
  72204. }());
  72205. BABYLON.TextureTools = TextureTools;
  72206. })(BABYLON || (BABYLON = {}));
  72207. //# sourceMappingURL=babylon.textureTools.js.map
  72208. var BABYLON;
  72209. (function (BABYLON) {
  72210. var FramingBehavior = (function () {
  72211. function FramingBehavior() {
  72212. this._mode = FramingBehavior.FitFrustumSidesMode;
  72213. this._radiusScale = 1.0;
  72214. this._positionScale = 0.5;
  72215. this._defaultElevation = 0.3;
  72216. this._elevationReturnTime = 1500;
  72217. this._elevationReturnWaitTime = 1000;
  72218. this._zoomStopsAnimation = false;
  72219. this._framingTime = 1500;
  72220. this._isPointerDown = false;
  72221. this._lastInteractionTime = -Infinity;
  72222. // Framing control
  72223. this._animatables = new Array();
  72224. this._betaIsAnimating = false;
  72225. }
  72226. Object.defineProperty(FramingBehavior.prototype, "name", {
  72227. get: function () {
  72228. return "Framing";
  72229. },
  72230. enumerable: true,
  72231. configurable: true
  72232. });
  72233. Object.defineProperty(FramingBehavior.prototype, "mode", {
  72234. /**
  72235. * Gets current mode used by the behavior.
  72236. */
  72237. get: function () {
  72238. return this._mode;
  72239. },
  72240. /**
  72241. * Sets the current mode used by the behavior
  72242. */
  72243. set: function (mode) {
  72244. this._mode = mode;
  72245. },
  72246. enumerable: true,
  72247. configurable: true
  72248. });
  72249. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  72250. /**
  72251. * Gets the scale applied to the radius
  72252. */
  72253. get: function () {
  72254. return this._radiusScale;
  72255. },
  72256. /**
  72257. * Sets the scale applied to the radius (1 by default)
  72258. */
  72259. set: function (radius) {
  72260. this._radiusScale = radius;
  72261. },
  72262. enumerable: true,
  72263. configurable: true
  72264. });
  72265. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  72266. /**
  72267. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  72268. */
  72269. get: function () {
  72270. return this._positionScale;
  72271. },
  72272. /**
  72273. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  72274. */
  72275. set: function (scale) {
  72276. this._positionScale = scale;
  72277. },
  72278. enumerable: true,
  72279. configurable: true
  72280. });
  72281. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  72282. /**
  72283. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  72284. * behaviour is triggered, in radians.
  72285. */
  72286. get: function () {
  72287. return this._defaultElevation;
  72288. },
  72289. /**
  72290. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  72291. * behaviour is triggered, in radians.
  72292. */
  72293. set: function (elevation) {
  72294. this._defaultElevation = elevation;
  72295. },
  72296. enumerable: true,
  72297. configurable: true
  72298. });
  72299. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  72300. /**
  72301. * Gets the time (in milliseconds) taken to return to the default beta position.
  72302. * Negative value indicates camera should not return to default.
  72303. */
  72304. get: function () {
  72305. return this._elevationReturnTime;
  72306. },
  72307. /**
  72308. * Sets the time (in milliseconds) taken to return to the default beta position.
  72309. * Negative value indicates camera should not return to default.
  72310. */
  72311. set: function (speed) {
  72312. this._elevationReturnTime = speed;
  72313. },
  72314. enumerable: true,
  72315. configurable: true
  72316. });
  72317. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  72318. /**
  72319. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  72320. */
  72321. get: function () {
  72322. return this._elevationReturnWaitTime;
  72323. },
  72324. /**
  72325. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  72326. */
  72327. set: function (time) {
  72328. this._elevationReturnWaitTime = time;
  72329. },
  72330. enumerable: true,
  72331. configurable: true
  72332. });
  72333. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  72334. /**
  72335. * Gets the flag that indicates if user zooming should stop animation.
  72336. */
  72337. get: function () {
  72338. return this._zoomStopsAnimation;
  72339. },
  72340. /**
  72341. * Sets the flag that indicates if user zooming should stop animation.
  72342. */
  72343. set: function (flag) {
  72344. this._zoomStopsAnimation = flag;
  72345. },
  72346. enumerable: true,
  72347. configurable: true
  72348. });
  72349. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  72350. /**
  72351. * Gets the transition time when framing the mesh, in milliseconds
  72352. */
  72353. get: function () {
  72354. return this._framingTime;
  72355. },
  72356. /**
  72357. * Sets the transition time when framing the mesh, in milliseconds
  72358. */
  72359. set: function (time) {
  72360. this._framingTime = time;
  72361. },
  72362. enumerable: true,
  72363. configurable: true
  72364. });
  72365. FramingBehavior.prototype.attach = function (camera) {
  72366. var _this = this;
  72367. this._attachedCamera = camera;
  72368. var scene = this._attachedCamera.getScene();
  72369. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  72370. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  72371. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  72372. _this._isPointerDown = true;
  72373. return;
  72374. }
  72375. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  72376. _this._isPointerDown = false;
  72377. }
  72378. });
  72379. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  72380. if (mesh) {
  72381. _this.zoomOnMesh(mesh);
  72382. }
  72383. });
  72384. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  72385. // Stop the animation if there is user interaction and the animation should stop for this interaction
  72386. _this._applyUserInteraction();
  72387. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  72388. // back to the default position after a given timeout
  72389. _this._maintainCameraAboveGround();
  72390. });
  72391. };
  72392. FramingBehavior.prototype.detach = function () {
  72393. var scene = this._attachedCamera.getScene();
  72394. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  72395. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  72396. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  72397. this._attachedCamera = null;
  72398. };
  72399. /**
  72400. * Targets the given mesh and updates zoom level accordingly.
  72401. * @param mesh The mesh to target.
  72402. * @param radius Optional. If a cached radius position already exists, overrides default.
  72403. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  72404. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  72405. * @param onAnimationEnd Callback triggered at the end of the framing animation
  72406. */
  72407. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  72408. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  72409. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  72410. mesh.computeWorldMatrix(true);
  72411. var boundingBox = mesh.getBoundingInfo().boundingBox;
  72412. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  72413. };
  72414. /**
  72415. * Targets the given mesh and updates zoom level accordingly.
  72416. * @param mesh The mesh to target.
  72417. * @param radius Optional. If a cached radius position already exists, overrides default.
  72418. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  72419. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  72420. * @param onAnimationEnd Callback triggered at the end of the framing animation
  72421. */
  72422. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  72423. var _this = this;
  72424. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  72425. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  72426. var zoomTarget;
  72427. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  72428. var bottom = minimumWorld.y;
  72429. var top = maximumWorld.y;
  72430. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  72431. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  72432. if (focusOnOriginXZ) {
  72433. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  72434. }
  72435. else {
  72436. var centerWorld = minimumWorld.add(radiusWorld);
  72437. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  72438. }
  72439. if (!this._vectorTransition) {
  72440. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  72441. }
  72442. this._betaIsAnimating = true;
  72443. this._animatables.push(BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime));
  72444. // sets the radius and lower radius bounds
  72445. // Small delta ensures camera is not always at lower zoom limit.
  72446. var radius = 0;
  72447. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  72448. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  72449. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  72450. radius = position;
  72451. }
  72452. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  72453. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  72454. if (this._attachedCamera.lowerRadiusLimit === null) {
  72455. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  72456. }
  72457. }
  72458. // Set sensibilities
  72459. var extend = maximumWorld.subtract(minimumWorld).length();
  72460. this._attachedCamera.panningSensibility = 5000 / extend;
  72461. this._attachedCamera.wheelPrecision = 100 / radius;
  72462. // transition to new radius
  72463. if (!this._radiusTransition) {
  72464. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  72465. }
  72466. this._animatables.push(BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  72467. if (onAnimationEnd) {
  72468. onAnimationEnd();
  72469. }
  72470. _this._attachedCamera.storeState();
  72471. }));
  72472. };
  72473. /**
  72474. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  72475. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  72476. * frustum width.
  72477. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  72478. * to fully enclose the mesh in the viewing frustum.
  72479. */
  72480. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  72481. var size = maximumWorld.subtract(minimumWorld);
  72482. var boxVectorGlobalDiagonal = size.length();
  72483. var frustumSlope = this._getFrustumSlope();
  72484. // Formula for setting distance
  72485. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  72486. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  72487. // Horizon distance
  72488. var radius = radiusWithoutFraming * this._radiusScale;
  72489. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  72490. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  72491. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  72492. var camera = this._attachedCamera;
  72493. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  72494. // Don't exceed the requested limit
  72495. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  72496. }
  72497. // Don't exceed the upper radius limit
  72498. if (camera.upperRadiusLimit) {
  72499. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  72500. }
  72501. return distance;
  72502. };
  72503. /**
  72504. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  72505. * is automatically returned to its default position (expected to be above ground plane).
  72506. */
  72507. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  72508. var _this = this;
  72509. if (this._elevationReturnTime < 0) {
  72510. return;
  72511. }
  72512. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  72513. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  72514. var limitBeta = Math.PI * 0.5;
  72515. // Bring the camera back up if below the ground plane
  72516. if (!this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  72517. this._betaIsAnimating = true;
  72518. //Transition to new position
  72519. this.stopAllAnimations();
  72520. if (!this._betaTransition) {
  72521. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  72522. }
  72523. this._animatables.push(BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  72524. _this._clearAnimationLocks();
  72525. _this.stopAllAnimations();
  72526. }));
  72527. }
  72528. };
  72529. /**
  72530. * Returns the frustum slope based on the canvas ratio and camera FOV
  72531. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  72532. */
  72533. FramingBehavior.prototype._getFrustumSlope = function () {
  72534. // Calculate the viewport ratio
  72535. // Aspect Ratio is Height/Width.
  72536. var camera = this._attachedCamera;
  72537. var engine = camera.getScene().getEngine();
  72538. var aspectRatio = engine.getAspectRatio(camera);
  72539. // Camera FOV is the vertical field of view (top-bottom) in radians.
  72540. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  72541. var frustumSlopeY = Math.tan(camera.fov / 2);
  72542. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  72543. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  72544. // along the forward vector.
  72545. var frustumSlopeX = frustumSlopeY * aspectRatio;
  72546. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  72547. };
  72548. /**
  72549. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  72550. */
  72551. FramingBehavior.prototype._clearAnimationLocks = function () {
  72552. this._betaIsAnimating = false;
  72553. };
  72554. /**
  72555. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  72556. */
  72557. FramingBehavior.prototype._applyUserInteraction = function () {
  72558. if (this.isUserIsMoving) {
  72559. this._lastInteractionTime = BABYLON.Tools.Now;
  72560. this.stopAllAnimations();
  72561. this._clearAnimationLocks();
  72562. }
  72563. };
  72564. /**
  72565. * Stops and removes all animations that have been applied to the camera
  72566. */
  72567. FramingBehavior.prototype.stopAllAnimations = function () {
  72568. this._attachedCamera.animations = [];
  72569. while (this._animatables.length) {
  72570. if (this._animatables[0]) {
  72571. this._animatables[0].onAnimationEnd = null;
  72572. this._animatables[0].stop();
  72573. }
  72574. this._animatables.shift();
  72575. }
  72576. };
  72577. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  72578. /**
  72579. * Gets a value indicating if the user is moving the camera
  72580. */
  72581. get: function () {
  72582. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  72583. this._attachedCamera.inertialBetaOffset !== 0 ||
  72584. this._attachedCamera.inertialRadiusOffset !== 0 ||
  72585. this._attachedCamera.inertialPanningX !== 0 ||
  72586. this._attachedCamera.inertialPanningY !== 0 ||
  72587. this._isPointerDown;
  72588. },
  72589. enumerable: true,
  72590. configurable: true
  72591. });
  72592. /**
  72593. * The easing function used by animations
  72594. */
  72595. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  72596. /**
  72597. * The easing mode used by animations
  72598. */
  72599. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  72600. // Statics
  72601. /**
  72602. * The camera can move all the way towards the mesh.
  72603. */
  72604. FramingBehavior.IgnoreBoundsSizeMode = 0;
  72605. /**
  72606. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  72607. */
  72608. FramingBehavior.FitFrustumSidesMode = 1;
  72609. return FramingBehavior;
  72610. }());
  72611. BABYLON.FramingBehavior = FramingBehavior;
  72612. })(BABYLON || (BABYLON = {}));
  72613. //# sourceMappingURL=babylon.framingBehavior.js.map
  72614. var BABYLON;
  72615. (function (BABYLON) {
  72616. /**
  72617. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  72618. */
  72619. var BouncingBehavior = (function () {
  72620. function BouncingBehavior() {
  72621. /**
  72622. * The duration of the animation, in milliseconds
  72623. */
  72624. this.transitionDuration = 450;
  72625. /**
  72626. * Length of the distance animated by the transition when lower radius is reached
  72627. */
  72628. this.lowerRadiusTransitionRange = 2;
  72629. /**
  72630. * Length of the distance animated by the transition when upper radius is reached
  72631. */
  72632. this.upperRadiusTransitionRange = -2;
  72633. this._autoTransitionRange = false;
  72634. // Animations
  72635. this._radiusIsAnimating = false;
  72636. this._radiusBounceTransition = null;
  72637. this._animatables = new Array();
  72638. }
  72639. Object.defineProperty(BouncingBehavior.prototype, "name", {
  72640. get: function () {
  72641. return "Bouncing";
  72642. },
  72643. enumerable: true,
  72644. configurable: true
  72645. });
  72646. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  72647. /**
  72648. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  72649. */
  72650. get: function () {
  72651. return this._autoTransitionRange;
  72652. },
  72653. /**
  72654. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  72655. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  72656. */
  72657. set: function (value) {
  72658. var _this = this;
  72659. if (this._autoTransitionRange === value) {
  72660. return;
  72661. }
  72662. this._autoTransitionRange = value;
  72663. var camera = this._attachedCamera;
  72664. if (value) {
  72665. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  72666. if (!mesh) {
  72667. return;
  72668. }
  72669. mesh.computeWorldMatrix(true);
  72670. var diagonal = mesh.getBoundingInfo().diagonalLength;
  72671. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  72672. _this.upperRadiusTransitionRange = diagonal * 0.05;
  72673. });
  72674. }
  72675. else if (this._onMeshTargetChangedObserver) {
  72676. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  72677. }
  72678. },
  72679. enumerable: true,
  72680. configurable: true
  72681. });
  72682. BouncingBehavior.prototype.attach = function (camera) {
  72683. var _this = this;
  72684. this._attachedCamera = camera;
  72685. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  72686. // Add the bounce animation to the lower radius limit
  72687. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  72688. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  72689. }
  72690. // Add the bounce animation to the upper radius limit
  72691. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  72692. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  72693. }
  72694. });
  72695. };
  72696. BouncingBehavior.prototype.detach = function () {
  72697. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  72698. if (this._onMeshTargetChangedObserver) {
  72699. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  72700. }
  72701. this._attachedCamera = null;
  72702. };
  72703. /**
  72704. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  72705. * @param radiusLimit The limit to check against.
  72706. * @return Bool to indicate if at limit.
  72707. */
  72708. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  72709. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  72710. return true;
  72711. }
  72712. return false;
  72713. };
  72714. /**
  72715. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  72716. * @param radiusDelta The delta by which to animate to. Can be negative.
  72717. */
  72718. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  72719. var _this = this;
  72720. if (!this._radiusBounceTransition) {
  72721. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  72722. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  72723. }
  72724. // Prevent zoom until bounce has completed
  72725. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  72726. this._attachedCamera.wheelPrecision = Infinity;
  72727. this._attachedCamera.inertialRadiusOffset = 0;
  72728. // Animate to the radius limit
  72729. this.stopAllAnimations();
  72730. this._radiusIsAnimating = true;
  72731. this._animatables.push(BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); }));
  72732. };
  72733. /**
  72734. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  72735. */
  72736. BouncingBehavior.prototype._clearAnimationLocks = function () {
  72737. this._radiusIsAnimating = false;
  72738. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  72739. };
  72740. /**
  72741. * Stops and removes all animations that have been applied to the camera
  72742. */
  72743. BouncingBehavior.prototype.stopAllAnimations = function () {
  72744. this._attachedCamera.animations = [];
  72745. while (this._animatables.length) {
  72746. this._animatables[0].onAnimationEnd = null;
  72747. this._animatables[0].stop();
  72748. this._animatables.shift();
  72749. }
  72750. };
  72751. /**
  72752. * The easing function used by animations
  72753. */
  72754. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  72755. /**
  72756. * The easing mode used by animations
  72757. */
  72758. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  72759. return BouncingBehavior;
  72760. }());
  72761. BABYLON.BouncingBehavior = BouncingBehavior;
  72762. })(BABYLON || (BABYLON = {}));
  72763. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  72764. var BABYLON;
  72765. (function (BABYLON) {
  72766. var AutoRotationBehavior = (function () {
  72767. function AutoRotationBehavior() {
  72768. this._zoomStopsAnimation = false;
  72769. this._idleRotationSpeed = 0.05;
  72770. this._idleRotationWaitTime = 2000;
  72771. this._idleRotationSpinupTime = 2000;
  72772. this._isPointerDown = false;
  72773. this._lastFrameTime = null;
  72774. this._lastInteractionTime = -Infinity;
  72775. this._cameraRotationSpeed = 0;
  72776. this._lastFrameRadius = 0;
  72777. }
  72778. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  72779. get: function () {
  72780. return "AutoRotation";
  72781. },
  72782. enumerable: true,
  72783. configurable: true
  72784. });
  72785. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  72786. /**
  72787. * Gets the flag that indicates if user zooming should stop animation.
  72788. */
  72789. get: function () {
  72790. return this._zoomStopsAnimation;
  72791. },
  72792. /**
  72793. * Sets the flag that indicates if user zooming should stop animation.
  72794. */
  72795. set: function (flag) {
  72796. this._zoomStopsAnimation = flag;
  72797. },
  72798. enumerable: true,
  72799. configurable: true
  72800. });
  72801. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  72802. /**
  72803. * Gets the default speed at which the camera rotates around the model.
  72804. */
  72805. get: function () {
  72806. return this._idleRotationSpeed;
  72807. },
  72808. /**
  72809. * Sets the default speed at which the camera rotates around the model.
  72810. */
  72811. set: function (speed) {
  72812. this._idleRotationSpeed = speed;
  72813. },
  72814. enumerable: true,
  72815. configurable: true
  72816. });
  72817. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  72818. /**
  72819. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  72820. */
  72821. get: function () {
  72822. return this._idleRotationWaitTime;
  72823. },
  72824. /**
  72825. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  72826. */
  72827. set: function (time) {
  72828. this._idleRotationWaitTime = time;
  72829. },
  72830. enumerable: true,
  72831. configurable: true
  72832. });
  72833. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  72834. /**
  72835. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  72836. */
  72837. get: function () {
  72838. return this._idleRotationSpinupTime;
  72839. },
  72840. /**
  72841. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  72842. */
  72843. set: function (time) {
  72844. this._idleRotationSpinupTime = time;
  72845. },
  72846. enumerable: true,
  72847. configurable: true
  72848. });
  72849. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  72850. /**
  72851. * Gets a value indicating if the camera is currently rotating because of this behavior
  72852. */
  72853. get: function () {
  72854. return Math.abs(this._cameraRotationSpeed) > 0;
  72855. },
  72856. enumerable: true,
  72857. configurable: true
  72858. });
  72859. AutoRotationBehavior.prototype.attach = function (camera) {
  72860. var _this = this;
  72861. this._attachedCamera = camera;
  72862. var scene = this._attachedCamera.getScene();
  72863. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  72864. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  72865. _this._isPointerDown = true;
  72866. return;
  72867. }
  72868. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  72869. _this._isPointerDown = false;
  72870. }
  72871. });
  72872. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  72873. var now = BABYLON.Tools.Now;
  72874. var dt = 0;
  72875. if (_this._lastFrameTime != null) {
  72876. dt = now - _this._lastFrameTime;
  72877. }
  72878. _this._lastFrameTime = now;
  72879. // Stop the animation if there is user interaction and the animation should stop for this interaction
  72880. _this._applyUserInteraction();
  72881. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  72882. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  72883. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  72884. // Step camera rotation by rotation speed
  72885. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  72886. });
  72887. };
  72888. AutoRotationBehavior.prototype.detach = function () {
  72889. var scene = this._attachedCamera.getScene();
  72890. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  72891. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  72892. this._attachedCamera = null;
  72893. };
  72894. /**
  72895. * Returns true if user is scrolling.
  72896. * @return true if user is scrolling.
  72897. */
  72898. AutoRotationBehavior.prototype._userIsZooming = function () {
  72899. return this._attachedCamera.inertialRadiusOffset !== 0;
  72900. };
  72901. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  72902. var zoomHasHitLimit = false;
  72903. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  72904. zoomHasHitLimit = true;
  72905. }
  72906. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  72907. this._lastFrameRadius = this._attachedCamera.radius;
  72908. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  72909. };
  72910. /**
  72911. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  72912. */
  72913. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  72914. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  72915. this._lastInteractionTime = BABYLON.Tools.Now;
  72916. }
  72917. };
  72918. // Tools
  72919. AutoRotationBehavior.prototype._userIsMoving = function () {
  72920. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  72921. this._attachedCamera.inertialBetaOffset !== 0 ||
  72922. this._attachedCamera.inertialRadiusOffset !== 0 ||
  72923. this._attachedCamera.inertialPanningX !== 0 ||
  72924. this._attachedCamera.inertialPanningY !== 0 ||
  72925. this._isPointerDown;
  72926. };
  72927. return AutoRotationBehavior;
  72928. }());
  72929. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  72930. })(BABYLON || (BABYLON = {}));
  72931. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  72932. var BABYLON;
  72933. (function (BABYLON) {
  72934. var NullEngineOptions = (function () {
  72935. function NullEngineOptions() {
  72936. this.renderWidth = 512;
  72937. this.renderHeight = 256;
  72938. this.textureSize = 512;
  72939. }
  72940. return NullEngineOptions;
  72941. }());
  72942. BABYLON.NullEngineOptions = NullEngineOptions;
  72943. /**
  72944. * The null engine class provides support for headless version of babylon.js.
  72945. * This can be used in server side scenario or for testing purposes
  72946. */
  72947. var NullEngine = (function (_super) {
  72948. __extends(NullEngine, _super);
  72949. function NullEngine(options) {
  72950. if (options === void 0) { options = new NullEngineOptions(); }
  72951. var _this = _super.call(this, null) || this;
  72952. _this._options = options;
  72953. // Init caps
  72954. // We consider we are on a webgl1 capable device
  72955. _this._caps = new BABYLON.EngineCapabilities();
  72956. _this._caps.maxTexturesImageUnits = 16;
  72957. _this._caps.maxVertexTextureImageUnits = 16;
  72958. _this._caps.maxTextureSize = 512;
  72959. _this._caps.maxCubemapTextureSize = 512;
  72960. _this._caps.maxRenderTextureSize = 512;
  72961. _this._caps.maxVertexAttribs = 16;
  72962. _this._caps.maxVaryingVectors = 16;
  72963. _this._caps.maxFragmentUniformVectors = 16;
  72964. _this._caps.maxVertexUniformVectors = 16;
  72965. // Extensions
  72966. _this._caps.standardDerivatives = false;
  72967. _this._caps.astc = null;
  72968. _this._caps.s3tc = null;
  72969. _this._caps.pvrtc = null;
  72970. _this._caps.etc1 = null;
  72971. _this._caps.etc2 = null;
  72972. _this._caps.textureAnisotropicFilterExtension = null;
  72973. _this._caps.maxAnisotropy = 0;
  72974. _this._caps.uintIndices = false;
  72975. _this._caps.fragmentDepthSupported = false;
  72976. _this._caps.highPrecisionShaderSupported = true;
  72977. _this._caps.colorBufferFloat = false;
  72978. _this._caps.textureFloat = false;
  72979. _this._caps.textureFloatLinearFiltering = false;
  72980. _this._caps.textureFloatRender = false;
  72981. _this._caps.textureHalfFloat = false;
  72982. _this._caps.textureHalfFloatLinearFiltering = false;
  72983. _this._caps.textureHalfFloatRender = false;
  72984. _this._caps.textureLOD = false;
  72985. _this._caps.drawBuffersExtension = false;
  72986. _this._caps.depthTextureExtension = false;
  72987. _this._caps.vertexArrayObject = false;
  72988. _this._caps.instancedArrays = false;
  72989. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  72990. // Wrappers
  72991. if (typeof URL === "undefined") {
  72992. URL = {
  72993. createObjectURL: function () { },
  72994. revokeObjectURL: function () { }
  72995. };
  72996. }
  72997. if (typeof Blob === "undefined") {
  72998. Blob = function () { };
  72999. }
  73000. return _this;
  73001. }
  73002. NullEngine.prototype.createVertexBuffer = function (vertices) {
  73003. return {
  73004. capacity: 0,
  73005. references: 1,
  73006. is32Bits: false
  73007. };
  73008. };
  73009. NullEngine.prototype.createIndexBuffer = function (indices) {
  73010. return {
  73011. capacity: 0,
  73012. references: 1,
  73013. is32Bits: false
  73014. };
  73015. };
  73016. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  73017. if (stencil === void 0) { stencil = false; }
  73018. };
  73019. NullEngine.prototype.getRenderWidth = function (useScreen) {
  73020. if (useScreen === void 0) { useScreen = false; }
  73021. if (!useScreen && this._currentRenderTarget) {
  73022. return this._currentRenderTarget.width;
  73023. }
  73024. return this._options.renderWidth;
  73025. };
  73026. NullEngine.prototype.getRenderHeight = function (useScreen) {
  73027. if (useScreen === void 0) { useScreen = false; }
  73028. if (!useScreen && this._currentRenderTarget) {
  73029. return this._currentRenderTarget.height;
  73030. }
  73031. return this._options.renderHeight;
  73032. };
  73033. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  73034. this._cachedViewport = viewport;
  73035. };
  73036. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  73037. return {
  73038. __SPECTOR_rebuildProgram: undefined,
  73039. };
  73040. };
  73041. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  73042. return [];
  73043. };
  73044. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  73045. return [];
  73046. };
  73047. NullEngine.prototype.bindSamplers = function (effect) {
  73048. this._currentEffect = null;
  73049. };
  73050. NullEngine.prototype.enableEffect = function (effect) {
  73051. this._currentEffect = effect;
  73052. if (effect.onBind) {
  73053. effect.onBind(effect);
  73054. }
  73055. effect.onBindObservable.notifyObservers(effect);
  73056. };
  73057. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  73058. if (zOffset === void 0) { zOffset = 0; }
  73059. if (reverseSide === void 0) { reverseSide = false; }
  73060. };
  73061. NullEngine.prototype.setIntArray = function (uniform, array) {
  73062. };
  73063. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  73064. };
  73065. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  73066. };
  73067. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  73068. };
  73069. NullEngine.prototype.setFloatArray = function (uniform, array) {
  73070. };
  73071. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  73072. };
  73073. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  73074. };
  73075. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  73076. };
  73077. NullEngine.prototype.setArray = function (uniform, array) {
  73078. };
  73079. NullEngine.prototype.setArray2 = function (uniform, array) {
  73080. };
  73081. NullEngine.prototype.setArray3 = function (uniform, array) {
  73082. };
  73083. NullEngine.prototype.setArray4 = function (uniform, array) {
  73084. };
  73085. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  73086. };
  73087. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  73088. };
  73089. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  73090. };
  73091. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  73092. };
  73093. NullEngine.prototype.setFloat = function (uniform, value) {
  73094. };
  73095. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  73096. };
  73097. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  73098. };
  73099. NullEngine.prototype.setBool = function (uniform, bool) {
  73100. };
  73101. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  73102. };
  73103. NullEngine.prototype.setColor3 = function (uniform, color3) {
  73104. };
  73105. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  73106. };
  73107. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  73108. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  73109. if (this._alphaMode === mode) {
  73110. return;
  73111. }
  73112. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  73113. if (!noDepthWriteChange) {
  73114. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  73115. }
  73116. this._alphaMode = mode;
  73117. };
  73118. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  73119. };
  73120. NullEngine.prototype.wipeCaches = function (bruteForce) {
  73121. if (this.preventCacheWipeBetweenFrames) {
  73122. return;
  73123. }
  73124. this.resetTextureCache();
  73125. this._currentEffect = null;
  73126. if (bruteForce) {
  73127. this._currentProgram = null;
  73128. this._stencilState.reset();
  73129. this._depthCullingState.reset();
  73130. this.setDepthFunctionToLessOrEqual();
  73131. this._alphaState.reset();
  73132. }
  73133. this._cachedVertexBuffers = null;
  73134. this._cachedIndexBuffer = null;
  73135. this._cachedEffectForVertexBuffers = null;
  73136. };
  73137. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  73138. };
  73139. NullEngine.prototype._createTexture = function () {
  73140. return {};
  73141. };
  73142. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  73143. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73144. if (onLoad === void 0) { onLoad = null; }
  73145. if (onError === void 0) { onError = null; }
  73146. if (buffer === void 0) { buffer = null; }
  73147. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  73148. var url = String(urlArg);
  73149. texture.url = url;
  73150. texture.generateMipMaps = !noMipmap;
  73151. texture.samplingMode = samplingMode;
  73152. texture.invertY = invertY;
  73153. texture.baseWidth = this._options.textureSize;
  73154. texture.baseHeight = this._options.textureSize;
  73155. texture.width = this._options.textureSize;
  73156. texture.height = this._options.textureSize;
  73157. texture.format = format;
  73158. texture.isReady = true;
  73159. if (onLoad) {
  73160. onLoad();
  73161. }
  73162. return texture;
  73163. };
  73164. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  73165. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  73166. if (options !== undefined && typeof options === "object") {
  73167. fullOptions.generateMipMaps = options.generateMipMaps;
  73168. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  73169. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  73170. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  73171. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  73172. }
  73173. else {
  73174. fullOptions.generateMipMaps = options;
  73175. fullOptions.generateDepthBuffer = true;
  73176. fullOptions.generateStencilBuffer = false;
  73177. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73178. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  73179. }
  73180. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  73181. var width = size.width || size;
  73182. var height = size.height || size;
  73183. texture._depthStencilBuffer = {};
  73184. texture._framebuffer = {};
  73185. texture.baseWidth = width;
  73186. texture.baseHeight = height;
  73187. texture.width = width;
  73188. texture.height = height;
  73189. texture.isReady = true;
  73190. texture.samples = 1;
  73191. texture.generateMipMaps = fullOptions.generateMipMaps;
  73192. texture.samplingMode = fullOptions.samplingMode;
  73193. texture.type = fullOptions.type;
  73194. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  73195. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  73196. return texture;
  73197. };
  73198. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  73199. texture.samplingMode = samplingMode;
  73200. };
  73201. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  73202. if (this._currentRenderTarget) {
  73203. this.unBindFramebuffer(this._currentRenderTarget);
  73204. }
  73205. this._currentRenderTarget = texture;
  73206. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  73207. if (this._cachedViewport && !forceFullscreenViewport) {
  73208. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  73209. }
  73210. };
  73211. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  73212. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  73213. this._currentRenderTarget = null;
  73214. if (onBeforeUnbind) {
  73215. if (texture._MSAAFramebuffer) {
  73216. this._currentFramebuffer = texture._framebuffer;
  73217. }
  73218. onBeforeUnbind();
  73219. }
  73220. this._currentFramebuffer = null;
  73221. };
  73222. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  73223. var vbo = {
  73224. capacity: 1,
  73225. references: 1,
  73226. is32Bits: false
  73227. };
  73228. return vbo;
  73229. };
  73230. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  73231. if (offset === void 0) { offset = 0; }
  73232. };
  73233. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  73234. };
  73235. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  73236. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  73237. this._activeTexturesCache[this._activeTexture] = texture;
  73238. }
  73239. };
  73240. NullEngine.prototype._bindTexture = function (channel, texture) {
  73241. if (channel < 0) {
  73242. return;
  73243. }
  73244. this._bindTextureDirectly(0, texture);
  73245. };
  73246. return NullEngine;
  73247. }(BABYLON.Engine));
  73248. BABYLON.NullEngine = NullEngine;
  73249. })(BABYLON || (BABYLON = {}));
  73250. //# sourceMappingURL=babylon.nullEngine.js.map
  73251. 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<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\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef 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\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<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(USESPHERICALINFRAGMENT)\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\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\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(USESPHERICALINFRAGMENT)\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(USESPHERICALINFRAGMENT)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=abs(texture2D(textureSampler,vUV).r);\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,1.0);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}"};
  73252. 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}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\nuniform sampler2D txColorTransform;\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#ifdef COLORGRADING\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;\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\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(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#else\nshadow=1.;\n#endif\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","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};"};
  73253. (function universalModuleDefinition(root, factory) {
  73254. if (root && root["BABYLON"]) {
  73255. return;
  73256. }
  73257. if(true)
  73258. module.exports = factory();
  73259. else if(typeof define === 'function' && define.amd)
  73260. define([], factory);
  73261. else if(typeof exports === 'object')
  73262. exports["BABYLON"] = factory();
  73263. else {
  73264. root["BABYLON"] = factory();
  73265. }
  73266. })(this, function() {
  73267. return BABYLON;
  73268. });
  73269. /***/ }),
  73270. /* 1 */
  73271. /***/ (function(module, exports) {
  73272. var g;
  73273. // This works in non-strict mode
  73274. g = (function() {
  73275. return this;
  73276. })();
  73277. try {
  73278. // This works if eval is allowed (see CSP)
  73279. g = g || Function("return this")() || (1,eval)("this");
  73280. } catch(e) {
  73281. // This works if the window reference is available
  73282. if(typeof window === "object")
  73283. g = window;
  73284. }
  73285. // g can still be undefined, but nothing to do about it...
  73286. // We return undefined, instead of nothing here, so it's
  73287. // easier to handle this case. if(!global) { ...}
  73288. module.exports = g;
  73289. /***/ }),
  73290. /* 2 */
  73291. /***/ (function(module, exports, __webpack_require__) {
  73292. "use strict";
  73293. Object.defineProperty(exports, "__esModule", { value: true });
  73294. var templateManager_1 = __webpack_require__(6);
  73295. var loader_1 = __webpack_require__(10);
  73296. var babylonjs_1 = __webpack_require__(0);
  73297. var AbstractViewer = (function () {
  73298. function AbstractViewer(containerElement, initialConfiguration) {
  73299. if (initialConfiguration === void 0) { initialConfiguration = { defaultViewer: true }; }
  73300. var _this = this;
  73301. this.containerElement = containerElement;
  73302. if (containerElement.id) {
  73303. this.baseId = containerElement.id;
  73304. }
  73305. else {
  73306. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  73307. }
  73308. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  73309. this.prepareContainerElement();
  73310. loader_1.default.loadConfiguration(initialConfiguration).then(function (configuration) {
  73311. _this.configuration = configuration;
  73312. var templateConfiguration = _this.configuration.template || {};
  73313. _this.templateManager.initTemplate(templateConfiguration);
  73314. _this.templateManager.onAllLoaded.add(function () {
  73315. _this.onTemplatesLoaded();
  73316. });
  73317. });
  73318. }
  73319. AbstractViewer.prototype.getBaseId = function () {
  73320. return this.baseId;
  73321. };
  73322. AbstractViewer.prototype.onTemplatesLoaded = function () {
  73323. var _this = this;
  73324. return this.initEngine().then(function () {
  73325. return _this.loadModel();
  73326. }).then(function () {
  73327. return _this;
  73328. });
  73329. };
  73330. AbstractViewer.prototype.initEngine = function () {
  73331. var _this = this;
  73332. var canvasElement = this.templateManager.getCanvas();
  73333. if (!canvasElement) {
  73334. return Promise.reject('Canvas element not found!');
  73335. }
  73336. var config = this.configuration.engine || {};
  73337. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing);
  73338. window.addEventListener('resize', function () {
  73339. _this.engine.resize();
  73340. });
  73341. this.engine.runRenderLoop(function () {
  73342. _this.scene && _this.scene.render();
  73343. });
  73344. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  73345. this.engine.setHardwareScalingLevel(scale);
  73346. return Promise.resolve(this.engine);
  73347. };
  73348. AbstractViewer.prototype.initScene = function () {
  73349. if (this.scene) {
  73350. this.scene.dispose();
  73351. }
  73352. this.scene = new babylonjs_1.Scene(this.engine);
  73353. this.scene.createDefaultCameraOrLight(true, true, true);
  73354. return Promise.resolve(this.scene);
  73355. };
  73356. AbstractViewer.prototype.loadModel = function (model, clearScene) {
  73357. var _this = this;
  73358. if (model === void 0) { model = this.configuration.model; }
  73359. if (clearScene === void 0) { clearScene = true; }
  73360. var modelUrl = (typeof model === 'string') ? model : model.url;
  73361. var parts = modelUrl.split('/');
  73362. var filename = parts.pop();
  73363. var base = parts.join('/') + '/';
  73364. return Promise.resolve().then(function () {
  73365. if (!_this.scene || clearScene)
  73366. return _this.initScene();
  73367. else
  73368. return _this.scene;
  73369. }).then(function () {
  73370. return new Promise(function (resolve, reject) {
  73371. babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, _this.scene, function (meshes) {
  73372. resolve(meshes);
  73373. }, undefined, function (e, m, exception) {
  73374. console.log(m, exception);
  73375. reject(m);
  73376. });
  73377. });
  73378. }).then(function (meshes) {
  73379. return _this.onModelLoaded(meshes);
  73380. });
  73381. };
  73382. AbstractViewer.prototype.onModelLoaded = function (meshes) {
  73383. console.log("model loaded");
  73384. return Promise.resolve(this.scene);
  73385. };
  73386. return AbstractViewer;
  73387. }());
  73388. exports.AbstractViewer = AbstractViewer;
  73389. /***/ }),
  73390. /* 3 */
  73391. /***/ (function(module, exports, __webpack_require__) {
  73392. "use strict";
  73393. Object.defineProperty(exports, "__esModule", { value: true });
  73394. function isUrl(urlToCheck) {
  73395. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  73396. return true;
  73397. }
  73398. return false;
  73399. }
  73400. exports.isUrl = isUrl;
  73401. function loadFile(url) {
  73402. return new Promise(function (resolve, reject) {
  73403. var xhr = new XMLHttpRequest();
  73404. xhr.open('GET', url);
  73405. xhr.send();
  73406. xhr.onreadystatechange = function () {
  73407. var DONE = 4;
  73408. var OK = 200;
  73409. if (xhr.readyState === DONE) {
  73410. if (xhr.status === OK) {
  73411. resolve(xhr.responseText);
  73412. }
  73413. }
  73414. else {
  73415. console.log('Error: ' + xhr.status, url);
  73416. reject('Error: ' + xhr.status);
  73417. }
  73418. };
  73419. });
  73420. }
  73421. exports.loadFile = loadFile;
  73422. function kebabToCamel(s) {
  73423. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  73424. }
  73425. exports.kebabToCamel = kebabToCamel;
  73426. function camelToKebab(str) {
  73427. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  73428. }
  73429. exports.camelToKebab = camelToKebab;
  73430. /***/ }),
  73431. /* 4 */
  73432. /***/ (function(module, exports, __webpack_require__) {
  73433. "use strict";
  73434. Object.defineProperty(exports, "__esModule", { value: true });
  73435. var babylonjs_1 = __webpack_require__(0);
  73436. var helper_1 = __webpack_require__(3);
  73437. var HTMLMapper = (function () {
  73438. function HTMLMapper() {
  73439. }
  73440. HTMLMapper.prototype.map = function (element) {
  73441. var config = {};
  73442. var _loop_1 = function (attrIdx) {
  73443. var attr = element.attributes.item(attrIdx);
  73444. var split = attr.nodeName.split('.');
  73445. split.reduce(function (currentConfig, key, idx) {
  73446. var camelKey = helper_1.kebabToCamel(key);
  73447. if (idx === split.length - 1) {
  73448. var val = attr.nodeValue;
  73449. if (val === "true") {
  73450. val = true;
  73451. }
  73452. else if (val === "false") {
  73453. val = false;
  73454. }
  73455. else {
  73456. var number = parseFloat(val);
  73457. if (!isNaN(number)) {
  73458. val = number;
  73459. }
  73460. }
  73461. currentConfig[camelKey] = val;
  73462. }
  73463. else {
  73464. currentConfig[camelKey] = currentConfig[camelKey] || {};
  73465. }
  73466. return currentConfig[camelKey];
  73467. }, config);
  73468. };
  73469. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  73470. _loop_1(attrIdx);
  73471. }
  73472. return config;
  73473. };
  73474. return HTMLMapper;
  73475. }());
  73476. var JSONMapper = (function () {
  73477. function JSONMapper() {
  73478. }
  73479. JSONMapper.prototype.map = function (rawSource) {
  73480. return JSON.parse(rawSource);
  73481. };
  73482. return JSONMapper;
  73483. }());
  73484. var DOMMapper = (function () {
  73485. function DOMMapper() {
  73486. }
  73487. DOMMapper.prototype.map = function (baseElement) {
  73488. var htmlMapper = new HTMLMapper();
  73489. var config = htmlMapper.map(baseElement);
  73490. var traverseChildren = function (element, partConfig) {
  73491. var children = element.children;
  73492. if (children.length) {
  73493. for (var i = 0; i < children.length; ++i) {
  73494. var item = children.item(i);
  73495. var configMapped = htmlMapper.map(item);
  73496. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  73497. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  73498. partConfig[key] = [];
  73499. }
  73500. else {
  73501. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  73502. partConfig.push(configMapped);
  73503. }
  73504. else if (partConfig[key]) {
  73505. element.setAttribute('array', 'true');
  73506. var oldItem = partConfig[key];
  73507. partConfig = [oldItem, configMapped];
  73508. }
  73509. else {
  73510. partConfig[key] = configMapped;
  73511. }
  73512. }
  73513. traverseChildren(item, partConfig[key] || configMapped);
  73514. }
  73515. }
  73516. return partConfig;
  73517. };
  73518. traverseChildren(baseElement, config);
  73519. return config;
  73520. };
  73521. return DOMMapper;
  73522. }());
  73523. var MapperManager = (function () {
  73524. function MapperManager() {
  73525. this.mappers = {
  73526. "html": new HTMLMapper(),
  73527. "json": new JSONMapper(),
  73528. "dom": new DOMMapper()
  73529. };
  73530. }
  73531. MapperManager.prototype.getMapper = function (type) {
  73532. if (!this.mappers[type]) {
  73533. babylonjs_1.Tools.Error("No mapper defined for " + type);
  73534. }
  73535. return this.mappers[type] || this.mappers[MapperManager.DefaultMapper];
  73536. };
  73537. MapperManager.prototype.registerMapper = function (type, mapper) {
  73538. this.mappers[type] = mapper;
  73539. };
  73540. MapperManager.DefaultMapper = 'json';
  73541. return MapperManager;
  73542. }());
  73543. exports.MapperManager = MapperManager;
  73544. exports.mapperManager = new MapperManager();
  73545. exports.default = exports.mapperManager;
  73546. /***/ }),
  73547. /* 5 */
  73548. /***/ (function(module, exports, __webpack_require__) {
  73549. "use strict";
  73550. /* WEBPACK VAR INJECTION */(function(global) {
  73551. Object.defineProperty(exports, "__esModule", { value: true });
  73552. var viewer_1 = __webpack_require__(2);
  73553. exports.AbstractViewer = viewer_1.AbstractViewer;
  73554. __webpack_require__(0);
  73555. __webpack_require__(20);
  73556. __webpack_require__(21);
  73557. var initializer_1 = __webpack_require__(22);
  73558. exports.InitTags = initializer_1.InitTags;
  73559. global.Promise = __webpack_require__(24).Promise;
  73560. initializer_1.InitTags();
  73561. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1)))
  73562. /***/ }),
  73563. /* 6 */
  73564. /***/ (function(module, exports, __webpack_require__) {
  73565. "use strict";
  73566. Object.defineProperty(exports, "__esModule", { value: true });
  73567. var babylonjs_1 = __webpack_require__(0);
  73568. var helper_1 = __webpack_require__(3);
  73569. var TemplateManager = (function () {
  73570. function TemplateManager(containerElement) {
  73571. this.containerElement = containerElement;
  73572. this.templates = {};
  73573. this.onInit = new babylonjs_1.Observable();
  73574. this.onLoaded = new babylonjs_1.Observable();
  73575. this.onStateChange = new babylonjs_1.Observable();
  73576. this.onAllLoaded = new babylonjs_1.Observable();
  73577. }
  73578. TemplateManager.prototype.initTemplate = function (configuration, name, parentTemplate) {
  73579. var _this = this;
  73580. if (name === void 0) { name = 'main'; }
  73581. var template = new Template(name, configuration);
  73582. this.templates[name] = template;
  73583. var childrenMap = configuration.children || {};
  73584. var childrenTemplates = Object.keys(childrenMap).map(function (name) {
  73585. return _this.initTemplate(childrenMap[name], name, template);
  73586. });
  73587. template.onLoaded.add(function () {
  73588. var addToParent = function () {
  73589. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  73590. template.appendTo(containingElement);
  73591. _this.checkLoadedState();
  73592. };
  73593. if (parentTemplate && !parentTemplate.parent) {
  73594. parentTemplate.onAppended.add(function () {
  73595. addToParent();
  73596. });
  73597. }
  73598. else {
  73599. addToParent();
  73600. }
  73601. });
  73602. return template;
  73603. };
  73604. TemplateManager.prototype.getCanvas = function () {
  73605. return this.containerElement.querySelector('canvas');
  73606. };
  73607. TemplateManager.prototype.getTemplate = function (name) {
  73608. return this.templates[name];
  73609. };
  73610. TemplateManager.prototype.checkLoadedState = function () {
  73611. var _this = this;
  73612. var done = Object.keys(this.templates).every(function (key) {
  73613. return _this.templates[key].isLoaded && !!_this.templates[key].parent;
  73614. });
  73615. if (done) {
  73616. this.onAllLoaded.notifyObservers(this);
  73617. }
  73618. };
  73619. return TemplateManager;
  73620. }());
  73621. exports.TemplateManager = TemplateManager;
  73622. var Handlebars = __webpack_require__(9);
  73623. var Template = (function () {
  73624. function Template(name, configuration) {
  73625. var _this = this;
  73626. this.name = name;
  73627. this.configuration = configuration;
  73628. this.onInit = new babylonjs_1.Observable();
  73629. this.onLoaded = new babylonjs_1.Observable();
  73630. this.onAppended = new babylonjs_1.Observable();
  73631. this.onStateChange = new babylonjs_1.Observable();
  73632. this.onEventTriggered = new babylonjs_1.Observable();
  73633. this.isLoaded = false;
  73634. this.onInit.notifyObservers(this);
  73635. var htmlContentPromise = getTemplateAsHtml(configuration);
  73636. htmlContentPromise.then(function (htmlTemplate) {
  73637. if (htmlTemplate) {
  73638. var compiledTemplate = Handlebars.compile(htmlTemplate);
  73639. var config = _this.configuration.config || {};
  73640. var rawHtml = compiledTemplate(config);
  73641. _this.fragment = document.createRange().createContextualFragment(rawHtml);
  73642. _this.isLoaded = true;
  73643. _this.onLoaded.notifyObservers(_this);
  73644. }
  73645. });
  73646. }
  73647. Template.prototype.appendTo = function (parent) {
  73648. var _this = this;
  73649. if (this.parent) {
  73650. console.error('Alread appanded to ', this.parent);
  73651. }
  73652. else {
  73653. this.parent = parent;
  73654. if (this.configuration.id) {
  73655. this.parent.id = this.configuration.id;
  73656. }
  73657. this.parent.appendChild(this.fragment);
  73658. setTimeout(function () {
  73659. _this.registerEvents();
  73660. _this.onAppended.notifyObservers(_this);
  73661. });
  73662. }
  73663. };
  73664. Template.prototype.show = function (visibilityFunction) {
  73665. var _this = this;
  73666. if (visibilityFunction) {
  73667. return visibilityFunction(this).then(function () {
  73668. _this.onStateChange.notifyObservers(_this);
  73669. return _this;
  73670. });
  73671. }
  73672. else {
  73673. this.parent.style.display = 'flex';
  73674. this.onStateChange.notifyObservers(this);
  73675. return Promise.resolve(this);
  73676. }
  73677. };
  73678. Template.prototype.hide = function (visibilityFunction) {
  73679. var _this = this;
  73680. if (visibilityFunction) {
  73681. return visibilityFunction(this).then(function () {
  73682. _this.onStateChange.notifyObservers(_this);
  73683. return _this;
  73684. });
  73685. }
  73686. else {
  73687. this.parent.style.display = 'none';
  73688. this.onStateChange.notifyObservers(this);
  73689. return Promise.resolve(this);
  73690. }
  73691. };
  73692. Template.prototype.registerEvents = function () {
  73693. var _this = this;
  73694. if (this.configuration.events) {
  73695. Object.keys(this.configuration.events).forEach(function (eventName) {
  73696. if (_this.configuration.events && _this.configuration.events[eventName]) {
  73697. var functionToFire_1 = function (selector, event) {
  73698. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  73699. };
  73700. if (typeof _this.configuration.events[eventName] === 'boolean') {
  73701. _this.parent.addEventListener(eventName, functionToFire_1.bind(_this, '#' + _this.parent.id), false);
  73702. }
  73703. else {
  73704. var selectorsArray = _this.configuration.events[eventName];
  73705. selectorsArray.forEach(function (selector) {
  73706. var htmlElement = _this.parent.querySelector(selector);
  73707. htmlElement && htmlElement.addEventListener(eventName, functionToFire_1.bind(_this, selector), false);
  73708. });
  73709. }
  73710. }
  73711. });
  73712. }
  73713. };
  73714. return Template;
  73715. }());
  73716. exports.Template = Template;
  73717. function getTemplateAsHtml(templateConfig) {
  73718. if (!templateConfig) {
  73719. return Promise.reject('No templateConfig provided');
  73720. }
  73721. else if (templateConfig.html) {
  73722. return Promise.resolve(templateConfig.html);
  73723. }
  73724. else {
  73725. var location_1 = getTemplateLocation(templateConfig);
  73726. if (helper_1.isUrl(location_1)) {
  73727. return helper_1.loadFile(location_1);
  73728. }
  73729. else {
  73730. location_1 = location_1.replace('#', '');
  73731. var element = document.getElementById('#' + location_1);
  73732. if (element) {
  73733. return Promise.resolve(element.innerHTML);
  73734. }
  73735. else {
  73736. return Promise.reject('Template ID not found');
  73737. }
  73738. }
  73739. }
  73740. }
  73741. exports.getTemplateAsHtml = getTemplateAsHtml;
  73742. function getTemplateLocation(templateConfig) {
  73743. if (!templateConfig || typeof templateConfig === 'string') {
  73744. return templateConfig;
  73745. }
  73746. else {
  73747. return templateConfig.location;
  73748. }
  73749. }
  73750. exports.getTemplateLocation = getTemplateLocation;
  73751. /***/ }),
  73752. /* 7 */
  73753. /***/ (function(module, exports, __webpack_require__) {
  73754. var require;var require;/*
  73755. * Copyright (c) 2015 cannon.js Authors
  73756. *
  73757. * Permission is hereby granted, free of charge, to any person
  73758. * obtaining a copy of this software and associated documentation
  73759. * files (the "Software"), to deal in the Software without
  73760. * restriction, including without limitation the rights to use, copy,
  73761. * modify, merge, publish, distribute, sublicense, and/or sell copies
  73762. * of the Software, and to permit persons to whom the Software is
  73763. * furnished to do so, subject to the following conditions:
  73764. *
  73765. * The above copyright notice and this permission notice shall be
  73766. * included in all copies or substantial portions of the Software.
  73767. *
  73768. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  73769. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  73770. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  73771. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  73772. * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  73773. * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  73774. * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  73775. */
  73776. !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){
  73777. module.exports={
  73778. "name": "cannon",
  73779. "version": "0.6.2",
  73780. "description": "A lightweight 3D physics engine written in JavaScript.",
  73781. "homepage": "https://github.com/schteppe/cannon.js",
  73782. "author": "Stefan Hedman <schteppe@gmail.com> (http://steffe.se)",
  73783. "keywords": [
  73784. "cannon.js",
  73785. "cannon",
  73786. "physics",
  73787. "engine",
  73788. "3d"
  73789. ],
  73790. "main": "./build/cannon.js",
  73791. "engines": {
  73792. "node": "*"
  73793. },
  73794. "repository": {
  73795. "type": "git",
  73796. "url": "https://github.com/schteppe/cannon.js.git"
  73797. },
  73798. "bugs": {
  73799. "url": "https://github.com/schteppe/cannon.js/issues"
  73800. },
  73801. "licenses": [
  73802. {
  73803. "type": "MIT"
  73804. }
  73805. ],
  73806. "devDependencies": {
  73807. "jshint": "latest",
  73808. "uglify-js": "latest",
  73809. "nodeunit": "^0.9.0",
  73810. "grunt": "~0.4.0",
  73811. "grunt-contrib-jshint": "~0.1.1",
  73812. "grunt-contrib-nodeunit": "^0.4.1",
  73813. "grunt-contrib-concat": "~0.1.3",
  73814. "grunt-contrib-uglify": "^0.5.1",
  73815. "grunt-browserify": "^2.1.4",
  73816. "grunt-contrib-yuidoc": "^0.5.2",
  73817. "browserify": "*"
  73818. },
  73819. "dependencies": {}
  73820. }
  73821. },{}],2:[function(_dereq_,module,exports){
  73822. // Export classes
  73823. module.exports = {
  73824. version : _dereq_('../package.json').version,
  73825. AABB : _dereq_('./collision/AABB'),
  73826. ArrayCollisionMatrix : _dereq_('./collision/ArrayCollisionMatrix'),
  73827. Body : _dereq_('./objects/Body'),
  73828. Box : _dereq_('./shapes/Box'),
  73829. Broadphase : _dereq_('./collision/Broadphase'),
  73830. Constraint : _dereq_('./constraints/Constraint'),
  73831. ContactEquation : _dereq_('./equations/ContactEquation'),
  73832. Narrowphase : _dereq_('./world/Narrowphase'),
  73833. ConeTwistConstraint : _dereq_('./constraints/ConeTwistConstraint'),
  73834. ContactMaterial : _dereq_('./material/ContactMaterial'),
  73835. ConvexPolyhedron : _dereq_('./shapes/ConvexPolyhedron'),
  73836. Cylinder : _dereq_('./shapes/Cylinder'),
  73837. DistanceConstraint : _dereq_('./constraints/DistanceConstraint'),
  73838. Equation : _dereq_('./equations/Equation'),
  73839. EventTarget : _dereq_('./utils/EventTarget'),
  73840. FrictionEquation : _dereq_('./equations/FrictionEquation'),
  73841. GSSolver : _dereq_('./solver/GSSolver'),
  73842. GridBroadphase : _dereq_('./collision/GridBroadphase'),
  73843. Heightfield : _dereq_('./shapes/Heightfield'),
  73844. HingeConstraint : _dereq_('./constraints/HingeConstraint'),
  73845. LockConstraint : _dereq_('./constraints/LockConstraint'),
  73846. Mat3 : _dereq_('./math/Mat3'),
  73847. Material : _dereq_('./material/Material'),
  73848. NaiveBroadphase : _dereq_('./collision/NaiveBroadphase'),
  73849. ObjectCollisionMatrix : _dereq_('./collision/ObjectCollisionMatrix'),
  73850. Pool : _dereq_('./utils/Pool'),
  73851. Particle : _dereq_('./shapes/Particle'),
  73852. Plane : _dereq_('./shapes/Plane'),
  73853. PointToPointConstraint : _dereq_('./constraints/PointToPointConstraint'),
  73854. Quaternion : _dereq_('./math/Quaternion'),
  73855. Ray : _dereq_('./collision/Ray'),
  73856. RaycastVehicle : _dereq_('./objects/RaycastVehicle'),
  73857. RaycastResult : _dereq_('./collision/RaycastResult'),
  73858. RigidVehicle : _dereq_('./objects/RigidVehicle'),
  73859. RotationalEquation : _dereq_('./equations/RotationalEquation'),
  73860. RotationalMotorEquation : _dereq_('./equations/RotationalMotorEquation'),
  73861. SAPBroadphase : _dereq_('./collision/SAPBroadphase'),
  73862. SPHSystem : _dereq_('./objects/SPHSystem'),
  73863. Shape : _dereq_('./shapes/Shape'),
  73864. Solver : _dereq_('./solver/Solver'),
  73865. Sphere : _dereq_('./shapes/Sphere'),
  73866. SplitSolver : _dereq_('./solver/SplitSolver'),
  73867. Spring : _dereq_('./objects/Spring'),
  73868. Trimesh : _dereq_('./shapes/Trimesh'),
  73869. Vec3 : _dereq_('./math/Vec3'),
  73870. Vec3Pool : _dereq_('./utils/Vec3Pool'),
  73871. World : _dereq_('./world/World'),
  73872. };
  73873. },{"../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){
  73874. var Vec3 = _dereq_('../math/Vec3');
  73875. var Utils = _dereq_('../utils/Utils');
  73876. module.exports = AABB;
  73877. /**
  73878. * Axis aligned bounding box class.
  73879. * @class AABB
  73880. * @constructor
  73881. * @param {Object} [options]
  73882. * @param {Vec3} [options.upperBound]
  73883. * @param {Vec3} [options.lowerBound]
  73884. */
  73885. function AABB(options){
  73886. options = options || {};
  73887. /**
  73888. * The lower bound of the bounding box.
  73889. * @property lowerBound
  73890. * @type {Vec3}
  73891. */
  73892. this.lowerBound = new Vec3();
  73893. if(options.lowerBound){
  73894. this.lowerBound.copy(options.lowerBound);
  73895. }
  73896. /**
  73897. * The upper bound of the bounding box.
  73898. * @property upperBound
  73899. * @type {Vec3}
  73900. */
  73901. this.upperBound = new Vec3();
  73902. if(options.upperBound){
  73903. this.upperBound.copy(options.upperBound);
  73904. }
  73905. }
  73906. var tmp = new Vec3();
  73907. /**
  73908. * Set the AABB bounds from a set of points.
  73909. * @method setFromPoints
  73910. * @param {Array} points An array of Vec3's.
  73911. * @param {Vec3} position
  73912. * @param {Quaternion} quaternion
  73913. * @param {number} skinSize
  73914. * @return {AABB} The self object
  73915. */
  73916. AABB.prototype.setFromPoints = function(points, position, quaternion, skinSize){
  73917. var l = this.lowerBound,
  73918. u = this.upperBound,
  73919. q = quaternion;
  73920. // Set to the first point
  73921. l.copy(points[0]);
  73922. if(q){
  73923. q.vmult(l, l);
  73924. }
  73925. u.copy(l);
  73926. for(var i = 1; i<points.length; i++){
  73927. var p = points[i];
  73928. if(q){
  73929. q.vmult(p, tmp);
  73930. p = tmp;
  73931. }
  73932. if(p.x > u.x){ u.x = p.x; }
  73933. if(p.x < l.x){ l.x = p.x; }
  73934. if(p.y > u.y){ u.y = p.y; }
  73935. if(p.y < l.y){ l.y = p.y; }
  73936. if(p.z > u.z){ u.z = p.z; }
  73937. if(p.z < l.z){ l.z = p.z; }
  73938. }
  73939. // Add offset
  73940. if (position) {
  73941. position.vadd(l, l);
  73942. position.vadd(u, u);
  73943. }
  73944. if(skinSize){
  73945. l.x -= skinSize;
  73946. l.y -= skinSize;
  73947. l.z -= skinSize;
  73948. u.x += skinSize;
  73949. u.y += skinSize;
  73950. u.z += skinSize;
  73951. }
  73952. return this;
  73953. };
  73954. /**
  73955. * Copy bounds from an AABB to this AABB
  73956. * @method copy
  73957. * @param {AABB} aabb Source to copy from
  73958. * @return {AABB} The this object, for chainability
  73959. */
  73960. AABB.prototype.copy = function(aabb){
  73961. this.lowerBound.copy(aabb.lowerBound);
  73962. this.upperBound.copy(aabb.upperBound);
  73963. return this;
  73964. };
  73965. /**
  73966. * Clone an AABB
  73967. * @method clone
  73968. */
  73969. AABB.prototype.clone = function(){
  73970. return new AABB().copy(this);
  73971. };
  73972. /**
  73973. * Extend this AABB so that it covers the given AABB too.
  73974. * @method extend
  73975. * @param {AABB} aabb
  73976. */
  73977. AABB.prototype.extend = function(aabb){
  73978. // Extend lower bound
  73979. var l = aabb.lowerBound.x;
  73980. if(this.lowerBound.x > l){
  73981. this.lowerBound.x = l;
  73982. }
  73983. // Upper
  73984. var u = aabb.upperBound.x;
  73985. if(this.upperBound.x < u){
  73986. this.upperBound.x = u;
  73987. }
  73988. // Extend lower bound
  73989. var l = aabb.lowerBound.y;
  73990. if(this.lowerBound.y > l){
  73991. this.lowerBound.y = l;
  73992. }
  73993. // Upper
  73994. var u = aabb.upperBound.y;
  73995. if(this.upperBound.y < u){
  73996. this.upperBound.y = u;
  73997. }
  73998. // Extend lower bound
  73999. var l = aabb.lowerBound.z;
  74000. if(this.lowerBound.z > l){
  74001. this.lowerBound.z = l;
  74002. }
  74003. // Upper
  74004. var u = aabb.upperBound.z;
  74005. if(this.upperBound.z < u){
  74006. this.upperBound.z = u;
  74007. }
  74008. };
  74009. /**
  74010. * Returns true if the given AABB overlaps this AABB.
  74011. * @method overlaps
  74012. * @param {AABB} aabb
  74013. * @return {Boolean}
  74014. */
  74015. AABB.prototype.overlaps = function(aabb){
  74016. var l1 = this.lowerBound,
  74017. u1 = this.upperBound,
  74018. l2 = aabb.lowerBound,
  74019. u2 = aabb.upperBound;
  74020. // l2 u2
  74021. // |---------|
  74022. // |--------|
  74023. // l1 u1
  74024. return ((l2.x <= u1.x && u1.x <= u2.x) || (l1.x <= u2.x && u2.x <= u1.x)) &&
  74025. ((l2.y <= u1.y && u1.y <= u2.y) || (l1.y <= u2.y && u2.y <= u1.y)) &&
  74026. ((l2.z <= u1.z && u1.z <= u2.z) || (l1.z <= u2.z && u2.z <= u1.z));
  74027. };
  74028. /**
  74029. * Returns true if the given AABB is fully contained in this AABB.
  74030. * @method contains
  74031. * @param {AABB} aabb
  74032. * @return {Boolean}
  74033. */
  74034. AABB.prototype.contains = function(aabb){
  74035. var l1 = this.lowerBound,
  74036. u1 = this.upperBound,
  74037. l2 = aabb.lowerBound,
  74038. u2 = aabb.upperBound;
  74039. // l2 u2
  74040. // |---------|
  74041. // |---------------|
  74042. // l1 u1
  74043. return (
  74044. (l1.x <= l2.x && u1.x >= u2.x) &&
  74045. (l1.y <= l2.y && u1.y >= u2.y) &&
  74046. (l1.z <= l2.z && u1.z >= u2.z)
  74047. );
  74048. };
  74049. /**
  74050. * @method getCorners
  74051. * @param {Vec3} a
  74052. * @param {Vec3} b
  74053. * @param {Vec3} c
  74054. * @param {Vec3} d
  74055. * @param {Vec3} e
  74056. * @param {Vec3} f
  74057. * @param {Vec3} g
  74058. * @param {Vec3} h
  74059. */
  74060. AABB.prototype.getCorners = function(a, b, c, d, e, f, g, h){
  74061. var l = this.lowerBound,
  74062. u = this.upperBound;
  74063. a.copy(l);
  74064. b.set( u.x, l.y, l.z );
  74065. c.set( u.x, u.y, l.z );
  74066. d.set( l.x, u.y, u.z );
  74067. e.set( u.x, l.y, l.z );
  74068. f.set( l.x, u.y, l.z );
  74069. g.set( l.x, l.y, u.z );
  74070. h.copy(u);
  74071. };
  74072. var transformIntoFrame_corners = [
  74073. new Vec3(),
  74074. new Vec3(),
  74075. new Vec3(),
  74076. new Vec3(),
  74077. new Vec3(),
  74078. new Vec3(),
  74079. new Vec3(),
  74080. new Vec3()
  74081. ];
  74082. /**
  74083. * Get the representation of an AABB in another frame.
  74084. * @method toLocalFrame
  74085. * @param {Transform} frame
  74086. * @param {AABB} target
  74087. * @return {AABB} The "target" AABB object.
  74088. */
  74089. AABB.prototype.toLocalFrame = function(frame, target){
  74090. var corners = transformIntoFrame_corners;
  74091. var a = corners[0];
  74092. var b = corners[1];
  74093. var c = corners[2];
  74094. var d = corners[3];
  74095. var e = corners[4];
  74096. var f = corners[5];
  74097. var g = corners[6];
  74098. var h = corners[7];
  74099. // Get corners in current frame
  74100. this.getCorners(a, b, c, d, e, f, g, h);
  74101. // Transform them to new local frame
  74102. for(var i=0; i !== 8; i++){
  74103. var corner = corners[i];
  74104. frame.pointToLocal(corner, corner);
  74105. }
  74106. return target.setFromPoints(corners);
  74107. };
  74108. /**
  74109. * Get the representation of an AABB in the global frame.
  74110. * @method toWorldFrame
  74111. * @param {Transform} frame
  74112. * @param {AABB} target
  74113. * @return {AABB} The "target" AABB object.
  74114. */
  74115. AABB.prototype.toWorldFrame = function(frame, target){
  74116. var corners = transformIntoFrame_corners;
  74117. var a = corners[0];
  74118. var b = corners[1];
  74119. var c = corners[2];
  74120. var d = corners[3];
  74121. var e = corners[4];
  74122. var f = corners[5];
  74123. var g = corners[6];
  74124. var h = corners[7];
  74125. // Get corners in current frame
  74126. this.getCorners(a, b, c, d, e, f, g, h);
  74127. // Transform them to new local frame
  74128. for(var i=0; i !== 8; i++){
  74129. var corner = corners[i];
  74130. frame.pointToWorld(corner, corner);
  74131. }
  74132. return target.setFromPoints(corners);
  74133. };
  74134. },{"../math/Vec3":30,"../utils/Utils":53}],4:[function(_dereq_,module,exports){
  74135. module.exports = ArrayCollisionMatrix;
  74136. /**
  74137. * Collision "matrix". It's actually a triangular-shaped array of whether two bodies are touching this step, for reference next step
  74138. * @class ArrayCollisionMatrix
  74139. * @constructor
  74140. */
  74141. function ArrayCollisionMatrix() {
  74142. /**
  74143. * The matrix storage
  74144. * @property matrix
  74145. * @type {Array}
  74146. */
  74147. this.matrix = [];
  74148. }
  74149. /**
  74150. * Get an element
  74151. * @method get
  74152. * @param {Number} i
  74153. * @param {Number} j
  74154. * @return {Number}
  74155. */
  74156. ArrayCollisionMatrix.prototype.get = function(i, j) {
  74157. i = i.index;
  74158. j = j.index;
  74159. if (j > i) {
  74160. var temp = j;
  74161. j = i;
  74162. i = temp;
  74163. }
  74164. return this.matrix[(i*(i + 1)>>1) + j-1];
  74165. };
  74166. /**
  74167. * Set an element
  74168. * @method set
  74169. * @param {Number} i
  74170. * @param {Number} j
  74171. * @param {Number} value
  74172. */
  74173. ArrayCollisionMatrix.prototype.set = function(i, j, value) {
  74174. i = i.index;
  74175. j = j.index;
  74176. if (j > i) {
  74177. var temp = j;
  74178. j = i;
  74179. i = temp;
  74180. }
  74181. this.matrix[(i*(i + 1)>>1) + j-1] = value ? 1 : 0;
  74182. };
  74183. /**
  74184. * Sets all elements to zero
  74185. * @method reset
  74186. */
  74187. ArrayCollisionMatrix.prototype.reset = function() {
  74188. for (var i=0, l=this.matrix.length; i!==l; i++) {
  74189. this.matrix[i]=0;
  74190. }
  74191. };
  74192. /**
  74193. * Sets the max number of objects
  74194. * @method setNumObjects
  74195. * @param {Number} n
  74196. */
  74197. ArrayCollisionMatrix.prototype.setNumObjects = function(n) {
  74198. this.matrix.length = n*(n-1)>>1;
  74199. };
  74200. },{}],5:[function(_dereq_,module,exports){
  74201. var Body = _dereq_('../objects/Body');
  74202. var Vec3 = _dereq_('../math/Vec3');
  74203. var Quaternion = _dereq_('../math/Quaternion');
  74204. var Shape = _dereq_('../shapes/Shape');
  74205. var Plane = _dereq_('../shapes/Plane');
  74206. module.exports = Broadphase;
  74207. /**
  74208. * Base class for broadphase implementations
  74209. * @class Broadphase
  74210. * @constructor
  74211. * @author schteppe
  74212. */
  74213. function Broadphase(){
  74214. /**
  74215. * The world to search for collisions in.
  74216. * @property world
  74217. * @type {World}
  74218. */
  74219. this.world = null;
  74220. /**
  74221. * If set to true, the broadphase uses bounding boxes for intersection test, else it uses bounding spheres.
  74222. * @property useBoundingBoxes
  74223. * @type {Boolean}
  74224. */
  74225. this.useBoundingBoxes = false;
  74226. /**
  74227. * Set to true if the objects in the world moved.
  74228. * @property {Boolean} dirty
  74229. */
  74230. this.dirty = true;
  74231. }
  74232. /**
  74233. * Get the collision pairs from the world
  74234. * @method collisionPairs
  74235. * @param {World} world The world to search in
  74236. * @param {Array} p1 Empty array to be filled with body objects
  74237. * @param {Array} p2 Empty array to be filled with body objects
  74238. */
  74239. Broadphase.prototype.collisionPairs = function(world,p1,p2){
  74240. throw new Error("collisionPairs not implemented for this BroadPhase class!");
  74241. };
  74242. /**
  74243. * Check if a body pair needs to be intersection tested at all.
  74244. * @method needBroadphaseCollision
  74245. * @param {Body} bodyA
  74246. * @param {Body} bodyB
  74247. * @return {bool}
  74248. */
  74249. var Broadphase_needBroadphaseCollision_STATIC_OR_KINEMATIC = Body.STATIC | Body.KINEMATIC;
  74250. Broadphase.prototype.needBroadphaseCollision = function(bodyA,bodyB){
  74251. // Check collision filter masks
  74252. if( (bodyA.collisionFilterGroup & bodyB.collisionFilterMask)===0 || (bodyB.collisionFilterGroup & bodyA.collisionFilterMask)===0){
  74253. return false;
  74254. }
  74255. // Check types
  74256. if(((bodyA.type & Broadphase_needBroadphaseCollision_STATIC_OR_KINEMATIC)!==0 || bodyA.sleepState === Body.SLEEPING) &&
  74257. ((bodyB.type & Broadphase_needBroadphaseCollision_STATIC_OR_KINEMATIC)!==0 || bodyB.sleepState === Body.SLEEPING)) {
  74258. // Both bodies are static, kinematic or sleeping. Skip.
  74259. return false;
  74260. }
  74261. return true;
  74262. };
  74263. /**
  74264. * Check if the bounding volumes of two bodies intersect.
  74265. * @method intersectionTest
  74266. * @param {Body} bodyA
  74267. * @param {Body} bodyB
  74268. * @param {array} pairs1
  74269. * @param {array} pairs2
  74270. */
  74271. Broadphase.prototype.intersectionTest = function(bodyA, bodyB, pairs1, pairs2){
  74272. if(this.useBoundingBoxes){
  74273. this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2);
  74274. } else {
  74275. this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2);
  74276. }
  74277. };
  74278. /**
  74279. * Check if the bounding spheres of two bodies are intersecting.
  74280. * @method doBoundingSphereBroadphase
  74281. * @param {Body} bodyA
  74282. * @param {Body} bodyB
  74283. * @param {Array} pairs1 bodyA is appended to this array if intersection
  74284. * @param {Array} pairs2 bodyB is appended to this array if intersection
  74285. */
  74286. var Broadphase_collisionPairs_r = new Vec3(), // Temp objects
  74287. Broadphase_collisionPairs_normal = new Vec3(),
  74288. Broadphase_collisionPairs_quat = new Quaternion(),
  74289. Broadphase_collisionPairs_relpos = new Vec3();
  74290. Broadphase.prototype.doBoundingSphereBroadphase = function(bodyA,bodyB,pairs1,pairs2){
  74291. var r = Broadphase_collisionPairs_r;
  74292. bodyB.position.vsub(bodyA.position,r);
  74293. var boundingRadiusSum2 = Math.pow(bodyA.boundingRadius + bodyB.boundingRadius, 2);
  74294. var norm2 = r.norm2();
  74295. if(norm2 < boundingRadiusSum2){
  74296. pairs1.push(bodyA);
  74297. pairs2.push(bodyB);
  74298. }
  74299. };
  74300. /**
  74301. * Check if the bounding boxes of two bodies are intersecting.
  74302. * @method doBoundingBoxBroadphase
  74303. * @param {Body} bodyA
  74304. * @param {Body} bodyB
  74305. * @param {Array} pairs1
  74306. * @param {Array} pairs2
  74307. */
  74308. Broadphase.prototype.doBoundingBoxBroadphase = function(bodyA,bodyB,pairs1,pairs2){
  74309. if(bodyA.aabbNeedsUpdate){
  74310. bodyA.computeAABB();
  74311. }
  74312. if(bodyB.aabbNeedsUpdate){
  74313. bodyB.computeAABB();
  74314. }
  74315. // Check AABB / AABB
  74316. if(bodyA.aabb.overlaps(bodyB.aabb)){
  74317. pairs1.push(bodyA);
  74318. pairs2.push(bodyB);
  74319. }
  74320. };
  74321. /**
  74322. * Removes duplicate pairs from the pair arrays.
  74323. * @method makePairsUnique
  74324. * @param {Array} pairs1
  74325. * @param {Array} pairs2
  74326. */
  74327. var Broadphase_makePairsUnique_temp = { keys:[] },
  74328. Broadphase_makePairsUnique_p1 = [],
  74329. Broadphase_makePairsUnique_p2 = [];
  74330. Broadphase.prototype.makePairsUnique = function(pairs1,pairs2){
  74331. var t = Broadphase_makePairsUnique_temp,
  74332. p1 = Broadphase_makePairsUnique_p1,
  74333. p2 = Broadphase_makePairsUnique_p2,
  74334. N = pairs1.length;
  74335. for(var i=0; i!==N; i++){
  74336. p1[i] = pairs1[i];
  74337. p2[i] = pairs2[i];
  74338. }
  74339. pairs1.length = 0;
  74340. pairs2.length = 0;
  74341. for(var i=0; i!==N; i++){
  74342. var id1 = p1[i].id,
  74343. id2 = p2[i].id;
  74344. var key = id1 < id2 ? id1+","+id2 : id2+","+id1;
  74345. t[key] = i;
  74346. t.keys.push(key);
  74347. }
  74348. for(var i=0; i!==t.keys.length; i++){
  74349. var key = t.keys.pop(),
  74350. pairIndex = t[key];
  74351. pairs1.push(p1[pairIndex]);
  74352. pairs2.push(p2[pairIndex]);
  74353. delete t[key];
  74354. }
  74355. };
  74356. /**
  74357. * To be implemented by subcasses
  74358. * @method setWorld
  74359. * @param {World} world
  74360. */
  74361. Broadphase.prototype.setWorld = function(world){
  74362. };
  74363. /**
  74364. * Check if the bounding spheres of two bodies overlap.
  74365. * @method boundingSphereCheck
  74366. * @param {Body} bodyA
  74367. * @param {Body} bodyB
  74368. * @return {boolean}
  74369. */
  74370. var bsc_dist = new Vec3();
  74371. Broadphase.boundingSphereCheck = function(bodyA,bodyB){
  74372. var dist = bsc_dist;
  74373. bodyA.position.vsub(bodyB.position,dist);
  74374. return Math.pow(bodyA.shape.boundingSphereRadius + bodyB.shape.boundingSphereRadius,2) > dist.norm2();
  74375. };
  74376. /**
  74377. * Returns all the bodies within the AABB.
  74378. * @method aabbQuery
  74379. * @param {World} world
  74380. * @param {AABB} aabb
  74381. * @param {array} result An array to store resulting bodies in.
  74382. * @return {array}
  74383. */
  74384. Broadphase.prototype.aabbQuery = function(world, aabb, result){
  74385. console.warn('.aabbQuery is not implemented in this Broadphase subclass.');
  74386. return [];
  74387. };
  74388. },{"../math/Quaternion":28,"../math/Vec3":30,"../objects/Body":31,"../shapes/Plane":42,"../shapes/Shape":43}],6:[function(_dereq_,module,exports){
  74389. module.exports = GridBroadphase;
  74390. var Broadphase = _dereq_('./Broadphase');
  74391. var Vec3 = _dereq_('../math/Vec3');
  74392. var Shape = _dereq_('../shapes/Shape');
  74393. /**
  74394. * Axis aligned uniform grid broadphase.
  74395. * @class GridBroadphase
  74396. * @constructor
  74397. * @extends Broadphase
  74398. * @todo Needs support for more than just planes and spheres.
  74399. * @param {Vec3} aabbMin
  74400. * @param {Vec3} aabbMax
  74401. * @param {Number} nx Number of boxes along x
  74402. * @param {Number} ny Number of boxes along y
  74403. * @param {Number} nz Number of boxes along z
  74404. */
  74405. function GridBroadphase(aabbMin,aabbMax,nx,ny,nz){
  74406. Broadphase.apply(this);
  74407. this.nx = nx || 10;
  74408. this.ny = ny || 10;
  74409. this.nz = nz || 10;
  74410. this.aabbMin = aabbMin || new Vec3(100,100,100);
  74411. this.aabbMax = aabbMax || new Vec3(-100,-100,-100);
  74412. var nbins = this.nx * this.ny * this.nz;
  74413. if (nbins <= 0) {
  74414. throw "GridBroadphase: Each dimension's n must be >0";
  74415. }
  74416. this.bins = [];
  74417. this.binLengths = []; //Rather than continually resizing arrays (thrashing the memory), just record length and allow them to grow
  74418. this.bins.length = nbins;
  74419. this.binLengths.length = nbins;
  74420. for (var i=0;i<nbins;i++) {
  74421. this.bins[i]=[];
  74422. this.binLengths[i]=0;
  74423. }
  74424. }
  74425. GridBroadphase.prototype = new Broadphase();
  74426. GridBroadphase.prototype.constructor = GridBroadphase;
  74427. /**
  74428. * Get all the collision pairs in the physics world
  74429. * @method collisionPairs
  74430. * @param {World} world
  74431. * @param {Array} pairs1
  74432. * @param {Array} pairs2
  74433. */
  74434. var GridBroadphase_collisionPairs_d = new Vec3();
  74435. var GridBroadphase_collisionPairs_binPos = new Vec3();
  74436. GridBroadphase.prototype.collisionPairs = function(world,pairs1,pairs2){
  74437. var N = world.numObjects(),
  74438. bodies = world.bodies;
  74439. var max = this.aabbMax,
  74440. min = this.aabbMin,
  74441. nx = this.nx,
  74442. ny = this.ny,
  74443. nz = this.nz;
  74444. var xstep = ny*nz;
  74445. var ystep = nz;
  74446. var zstep = 1;
  74447. var xmax = max.x,
  74448. ymax = max.y,
  74449. zmax = max.z,
  74450. xmin = min.x,
  74451. ymin = min.y,
  74452. zmin = min.z;
  74453. var xmult = nx / (xmax-xmin),
  74454. ymult = ny / (ymax-ymin),
  74455. zmult = nz / (zmax-zmin);
  74456. var binsizeX = (xmax - xmin) / nx,
  74457. binsizeY = (ymax - ymin) / ny,
  74458. binsizeZ = (zmax - zmin) / nz;
  74459. var binRadius = Math.sqrt(binsizeX*binsizeX + binsizeY*binsizeY + binsizeZ*binsizeZ) * 0.5;
  74460. var types = Shape.types;
  74461. var SPHERE = types.SPHERE,
  74462. PLANE = types.PLANE,
  74463. BOX = types.BOX,
  74464. COMPOUND = types.COMPOUND,
  74465. CONVEXPOLYHEDRON = types.CONVEXPOLYHEDRON;
  74466. var bins=this.bins,
  74467. binLengths=this.binLengths,
  74468. Nbins=this.bins.length;
  74469. // Reset bins
  74470. for(var i=0; i!==Nbins; i++){
  74471. binLengths[i] = 0;
  74472. }
  74473. var ceil = Math.ceil;
  74474. var min = Math.min;
  74475. var max = Math.max;
  74476. function addBoxToBins(x0,y0,z0,x1,y1,z1,bi) {
  74477. var xoff0 = ((x0 - xmin) * xmult)|0,
  74478. yoff0 = ((y0 - ymin) * ymult)|0,
  74479. zoff0 = ((z0 - zmin) * zmult)|0,
  74480. xoff1 = ceil((x1 - xmin) * xmult),
  74481. yoff1 = ceil((y1 - ymin) * ymult),
  74482. zoff1 = ceil((z1 - zmin) * zmult);
  74483. if (xoff0 < 0) { xoff0 = 0; } else if (xoff0 >= nx) { xoff0 = nx - 1; }
  74484. if (yoff0 < 0) { yoff0 = 0; } else if (yoff0 >= ny) { yoff0 = ny - 1; }
  74485. if (zoff0 < 0) { zoff0 = 0; } else if (zoff0 >= nz) { zoff0 = nz - 1; }
  74486. if (xoff1 < 0) { xoff1 = 0; } else if (xoff1 >= nx) { xoff1 = nx - 1; }
  74487. if (yoff1 < 0) { yoff1 = 0; } else if (yoff1 >= ny) { yoff1 = ny - 1; }
  74488. if (zoff1 < 0) { zoff1 = 0; } else if (zoff1 >= nz) { zoff1 = nz - 1; }
  74489. xoff0 *= xstep;
  74490. yoff0 *= ystep;
  74491. zoff0 *= zstep;
  74492. xoff1 *= xstep;
  74493. yoff1 *= ystep;
  74494. zoff1 *= zstep;
  74495. for (var xoff = xoff0; xoff <= xoff1; xoff += xstep) {
  74496. for (var yoff = yoff0; yoff <= yoff1; yoff += ystep) {
  74497. for (var zoff = zoff0; zoff <= zoff1; zoff += zstep) {
  74498. var idx = xoff+yoff+zoff;
  74499. bins[idx][binLengths[idx]++] = bi;
  74500. }
  74501. }
  74502. }
  74503. }
  74504. // Put all bodies into the bins
  74505. for(var i=0; i!==N; i++){
  74506. var bi = bodies[i];
  74507. var si = bi.shape;
  74508. switch(si.type){
  74509. case SPHERE:
  74510. // Put in bin
  74511. // check if overlap with other bins
  74512. var x = bi.position.x,
  74513. y = bi.position.y,
  74514. z = bi.position.z;
  74515. var r = si.radius;
  74516. addBoxToBins(x-r, y-r, z-r, x+r, y+r, z+r, bi);
  74517. break;
  74518. case PLANE:
  74519. if(si.worldNormalNeedsUpdate){
  74520. si.computeWorldNormal(bi.quaternion);
  74521. }
  74522. var planeNormal = si.worldNormal;
  74523. //Relative position from origin of plane object to the first bin
  74524. //Incremented as we iterate through the bins
  74525. var xreset = xmin + binsizeX*0.5 - bi.position.x,
  74526. yreset = ymin + binsizeY*0.5 - bi.position.y,
  74527. zreset = zmin + binsizeZ*0.5 - bi.position.z;
  74528. var d = GridBroadphase_collisionPairs_d;
  74529. d.set(xreset, yreset, zreset);
  74530. for (var xi = 0, xoff = 0; xi !== nx; xi++, xoff += xstep, d.y = yreset, d.x += binsizeX) {
  74531. for (var yi = 0, yoff = 0; yi !== ny; yi++, yoff += ystep, d.z = zreset, d.y += binsizeY) {
  74532. for (var zi = 0, zoff = 0; zi !== nz; zi++, zoff += zstep, d.z += binsizeZ) {
  74533. if (d.dot(planeNormal) < binRadius) {
  74534. var idx = xoff + yoff + zoff;
  74535. bins[idx][binLengths[idx]++] = bi;
  74536. }
  74537. }
  74538. }
  74539. }
  74540. break;
  74541. default:
  74542. if (bi.aabbNeedsUpdate) {
  74543. bi.computeAABB();
  74544. }
  74545. addBoxToBins(
  74546. bi.aabb.lowerBound.x,
  74547. bi.aabb.lowerBound.y,
  74548. bi.aabb.lowerBound.z,
  74549. bi.aabb.upperBound.x,
  74550. bi.aabb.upperBound.y,
  74551. bi.aabb.upperBound.z,
  74552. bi);
  74553. break;
  74554. }
  74555. }
  74556. // Check each bin
  74557. for(var i=0; i!==Nbins; i++){
  74558. var binLength = binLengths[i];
  74559. //Skip bins with no potential collisions
  74560. if (binLength > 1) {
  74561. var bin = bins[i];
  74562. // Do N^2 broadphase inside
  74563. for(var xi=0; xi!==binLength; xi++){
  74564. var bi = bin[xi];
  74565. for(var yi=0; yi!==xi; yi++){
  74566. var bj = bin[yi];
  74567. if(this.needBroadphaseCollision(bi,bj)){
  74568. this.intersectionTest(bi,bj,pairs1,pairs2);
  74569. }
  74570. }
  74571. }
  74572. }
  74573. }
  74574. // for (var zi = 0, zoff=0; zi < nz; zi++, zoff+= zstep) {
  74575. // console.log("layer "+zi);
  74576. // for (var yi = 0, yoff=0; yi < ny; yi++, yoff += ystep) {
  74577. // var row = '';
  74578. // for (var xi = 0, xoff=0; xi < nx; xi++, xoff += xstep) {
  74579. // var idx = xoff + yoff + zoff;
  74580. // row += ' ' + binLengths[idx];
  74581. // }
  74582. // console.log(row);
  74583. // }
  74584. // }
  74585. this.makePairsUnique(pairs1,pairs2);
  74586. };
  74587. },{"../math/Vec3":30,"../shapes/Shape":43,"./Broadphase":5}],7:[function(_dereq_,module,exports){
  74588. module.exports = NaiveBroadphase;
  74589. var Broadphase = _dereq_('./Broadphase');
  74590. var AABB = _dereq_('./AABB');
  74591. /**
  74592. * Naive broadphase implementation, used in lack of better ones.
  74593. * @class NaiveBroadphase
  74594. * @constructor
  74595. * @description The naive broadphase looks at all possible pairs without restriction, therefore it has complexity N^2 (which is bad)
  74596. * @extends Broadphase
  74597. */
  74598. function NaiveBroadphase(){
  74599. Broadphase.apply(this);
  74600. }
  74601. NaiveBroadphase.prototype = new Broadphase();
  74602. NaiveBroadphase.prototype.constructor = NaiveBroadphase;
  74603. /**
  74604. * Get all the collision pairs in the physics world
  74605. * @method collisionPairs
  74606. * @param {World} world
  74607. * @param {Array} pairs1
  74608. * @param {Array} pairs2
  74609. */
  74610. NaiveBroadphase.prototype.collisionPairs = function(world,pairs1,pairs2){
  74611. var bodies = world.bodies,
  74612. n = bodies.length,
  74613. i,j,bi,bj;
  74614. // Naive N^2 ftw!
  74615. for(i=0; i!==n; i++){
  74616. for(j=0; j!==i; j++){
  74617. bi = bodies[i];
  74618. bj = bodies[j];
  74619. if(!this.needBroadphaseCollision(bi,bj)){
  74620. continue;
  74621. }
  74622. this.intersectionTest(bi,bj,pairs1,pairs2);
  74623. }
  74624. }
  74625. };
  74626. var tmpAABB = new AABB();
  74627. /**
  74628. * Returns all the bodies within an AABB.
  74629. * @method aabbQuery
  74630. * @param {World} world
  74631. * @param {AABB} aabb
  74632. * @param {array} result An array to store resulting bodies in.
  74633. * @return {array}
  74634. */
  74635. NaiveBroadphase.prototype.aabbQuery = function(world, aabb, result){
  74636. result = result || [];
  74637. for(var i = 0; i < world.bodies.length; i++){
  74638. var b = world.bodies[i];
  74639. if(b.aabbNeedsUpdate){
  74640. b.computeAABB();
  74641. }
  74642. // Ugly hack until Body gets aabb
  74643. if(b.aabb.overlaps(aabb)){
  74644. result.push(b);
  74645. }
  74646. }
  74647. return result;
  74648. };
  74649. },{"./AABB":3,"./Broadphase":5}],8:[function(_dereq_,module,exports){
  74650. module.exports = ObjectCollisionMatrix;
  74651. /**
  74652. * Records what objects are colliding with each other
  74653. * @class ObjectCollisionMatrix
  74654. * @constructor
  74655. */
  74656. function ObjectCollisionMatrix() {
  74657. /**
  74658. * The matrix storage
  74659. * @property matrix
  74660. * @type {Object}
  74661. */
  74662. this.matrix = {};
  74663. }
  74664. /**
  74665. * @method get
  74666. * @param {Number} i
  74667. * @param {Number} j
  74668. * @return {Number}
  74669. */
  74670. ObjectCollisionMatrix.prototype.get = function(i, j) {
  74671. i = i.id;
  74672. j = j.id;
  74673. if (j > i) {
  74674. var temp = j;
  74675. j = i;
  74676. i = temp;
  74677. }
  74678. return i+'-'+j in this.matrix;
  74679. };
  74680. /**
  74681. * @method set
  74682. * @param {Number} i
  74683. * @param {Number} j
  74684. * @param {Number} value
  74685. */
  74686. ObjectCollisionMatrix.prototype.set = function(i, j, value) {
  74687. i = i.id;
  74688. j = j.id;
  74689. if (j > i) {
  74690. var temp = j;
  74691. j = i;
  74692. i = temp;
  74693. }
  74694. if (value) {
  74695. this.matrix[i+'-'+j] = true;
  74696. }
  74697. else {
  74698. delete this.matrix[i+'-'+j];
  74699. }
  74700. };
  74701. /**
  74702. * Empty the matrix
  74703. * @method reset
  74704. */
  74705. ObjectCollisionMatrix.prototype.reset = function() {
  74706. this.matrix = {};
  74707. };
  74708. /**
  74709. * Set max number of objects
  74710. * @method setNumObjects
  74711. * @param {Number} n
  74712. */
  74713. ObjectCollisionMatrix.prototype.setNumObjects = function(n) {
  74714. };
  74715. },{}],9:[function(_dereq_,module,exports){
  74716. module.exports = Ray;
  74717. var Vec3 = _dereq_('../math/Vec3');
  74718. var Quaternion = _dereq_('../math/Quaternion');
  74719. var Transform = _dereq_('../math/Transform');
  74720. var ConvexPolyhedron = _dereq_('../shapes/ConvexPolyhedron');
  74721. var Box = _dereq_('../shapes/Box');
  74722. var RaycastResult = _dereq_('../collision/RaycastResult');
  74723. var Shape = _dereq_('../shapes/Shape');
  74724. var AABB = _dereq_('../collision/AABB');
  74725. /**
  74726. * A line in 3D space that intersects bodies and return points.
  74727. * @class Ray
  74728. * @constructor
  74729. * @param {Vec3} from
  74730. * @param {Vec3} to
  74731. */
  74732. function Ray(from, to){
  74733. /**
  74734. * @property {Vec3} from
  74735. */
  74736. this.from = from ? from.clone() : new Vec3();
  74737. /**
  74738. * @property {Vec3} to
  74739. */
  74740. this.to = to ? to.clone() : new Vec3();
  74741. /**
  74742. * @private
  74743. * @property {Vec3} _direction
  74744. */
  74745. this._direction = new Vec3();
  74746. /**
  74747. * The precision of the ray. Used when checking parallelity etc.
  74748. * @property {Number} precision
  74749. */
  74750. this.precision = 0.0001;
  74751. /**
  74752. * Set to true if you want the Ray to take .collisionResponse flags into account on bodies and shapes.
  74753. * @property {Boolean} checkCollisionResponse
  74754. */
  74755. this.checkCollisionResponse = true;
  74756. /**
  74757. * If set to true, the ray skips any hits with normal.dot(rayDirection) < 0.
  74758. * @property {Boolean} skipBackfaces
  74759. */
  74760. this.skipBackfaces = false;
  74761. /**
  74762. * @property {number} collisionFilterMask
  74763. * @default -1
  74764. */
  74765. this.collisionFilterMask = -1;
  74766. /**
  74767. * @property {number} collisionFilterGroup
  74768. * @default -1
  74769. */
  74770. this.collisionFilterGroup = -1;
  74771. /**
  74772. * The intersection mode. Should be Ray.ANY, Ray.ALL or Ray.CLOSEST.
  74773. * @property {number} mode
  74774. */
  74775. this.mode = Ray.ANY;
  74776. /**
  74777. * Current result object.
  74778. * @property {RaycastResult} result
  74779. */
  74780. this.result = new RaycastResult();
  74781. /**
  74782. * Will be set to true during intersectWorld() if the ray hit anything.
  74783. * @property {Boolean} hasHit
  74784. */
  74785. this.hasHit = false;
  74786. /**
  74787. * Current, user-provided result callback. Will be used if mode is Ray.ALL.
  74788. * @property {Function} callback
  74789. */
  74790. this.callback = function(result){};
  74791. }
  74792. Ray.prototype.constructor = Ray;
  74793. Ray.CLOSEST = 1;
  74794. Ray.ANY = 2;
  74795. Ray.ALL = 4;
  74796. var tmpAABB = new AABB();
  74797. var tmpArray = [];
  74798. /**
  74799. * Do itersection against all bodies in the given World.
  74800. * @method intersectWorld
  74801. * @param {World} world
  74802. * @param {object} options
  74803. * @return {Boolean} True if the ray hit anything, otherwise false.
  74804. */
  74805. Ray.prototype.intersectWorld = function (world, options) {
  74806. this.mode = options.mode || Ray.ANY;
  74807. this.result = options.result || new RaycastResult();
  74808. this.skipBackfaces = !!options.skipBackfaces;
  74809. this.collisionFilterMask = typeof(options.collisionFilterMask) !== 'undefined' ? options.collisionFilterMask : -1;
  74810. this.collisionFilterGroup = typeof(options.collisionFilterGroup) !== 'undefined' ? options.collisionFilterGroup : -1;
  74811. if(options.from){
  74812. this.from.copy(options.from);
  74813. }
  74814. if(options.to){
  74815. this.to.copy(options.to);
  74816. }
  74817. this.callback = options.callback || function(){};
  74818. this.hasHit = false;
  74819. this.result.reset();
  74820. this._updateDirection();
  74821. this.getAABB(tmpAABB);
  74822. tmpArray.length = 0;
  74823. world.broadphase.aabbQuery(world, tmpAABB, tmpArray);
  74824. this.intersectBodies(tmpArray);
  74825. return this.hasHit;
  74826. };
  74827. var v1 = new Vec3(),
  74828. v2 = new Vec3();
  74829. /*
  74830. * As per "Barycentric Technique" as named here http://www.blackpawn.com/texts/pointinpoly/default.html But without the division
  74831. */
  74832. Ray.pointInTriangle = pointInTriangle;
  74833. function pointInTriangle(p, a, b, c) {
  74834. c.vsub(a,v0);
  74835. b.vsub(a,v1);
  74836. p.vsub(a,v2);
  74837. var dot00 = v0.dot( v0 );
  74838. var dot01 = v0.dot( v1 );
  74839. var dot02 = v0.dot( v2 );
  74840. var dot11 = v1.dot( v1 );
  74841. var dot12 = v1.dot( v2 );
  74842. var u,v;
  74843. return ( (u = dot11 * dot02 - dot01 * dot12) >= 0 ) &&
  74844. ( (v = dot00 * dot12 - dot01 * dot02) >= 0 ) &&
  74845. ( u + v < ( dot00 * dot11 - dot01 * dot01 ) );
  74846. }
  74847. /**
  74848. * Shoot a ray at a body, get back information about the hit.
  74849. * @method intersectBody
  74850. * @private
  74851. * @param {Body} body
  74852. * @param {RaycastResult} [result] Deprecated - set the result property of the Ray instead.
  74853. */
  74854. var intersectBody_xi = new Vec3();
  74855. var intersectBody_qi = new Quaternion();
  74856. Ray.prototype.intersectBody = function (body, result) {
  74857. if(result){
  74858. this.result = result;
  74859. this._updateDirection();
  74860. }
  74861. var checkCollisionResponse = this.checkCollisionResponse;
  74862. if(checkCollisionResponse && !body.collisionResponse){
  74863. return;
  74864. }
  74865. if((this.collisionFilterGroup & body.collisionFilterMask)===0 || (body.collisionFilterGroup & this.collisionFilterMask)===0){
  74866. return;
  74867. }
  74868. var xi = intersectBody_xi;
  74869. var qi = intersectBody_qi;
  74870. for (var i = 0, N = body.shapes.length; i < N; i++) {
  74871. var shape = body.shapes[i];
  74872. if(checkCollisionResponse && !shape.collisionResponse){
  74873. continue; // Skip
  74874. }
  74875. body.quaternion.mult(body.shapeOrientations[i], qi);
  74876. body.quaternion.vmult(body.shapeOffsets[i], xi);
  74877. xi.vadd(body.position, xi);
  74878. this.intersectShape(
  74879. shape,
  74880. qi,
  74881. xi,
  74882. body
  74883. );
  74884. if(this.result._shouldStop){
  74885. break;
  74886. }
  74887. }
  74888. };
  74889. /**
  74890. * @method intersectBodies
  74891. * @param {Array} bodies An array of Body objects.
  74892. * @param {RaycastResult} [result] Deprecated
  74893. */
  74894. Ray.prototype.intersectBodies = function (bodies, result) {
  74895. if(result){
  74896. this.result = result;
  74897. this._updateDirection();
  74898. }
  74899. for ( var i = 0, l = bodies.length; !this.result._shouldStop && i < l; i ++ ) {
  74900. this.intersectBody(bodies[i]);
  74901. }
  74902. };
  74903. /**
  74904. * Updates the _direction vector.
  74905. * @private
  74906. * @method _updateDirection
  74907. */
  74908. Ray.prototype._updateDirection = function(){
  74909. this.to.vsub(this.from, this._direction);
  74910. this._direction.normalize();
  74911. };
  74912. /**
  74913. * @method intersectShape
  74914. * @private
  74915. * @param {Shape} shape
  74916. * @param {Quaternion} quat
  74917. * @param {Vec3} position
  74918. * @param {Body} body
  74919. */
  74920. Ray.prototype.intersectShape = function(shape, quat, position, body){
  74921. var from = this.from;
  74922. // Checking boundingSphere
  74923. var distance = distanceFromIntersection(from, this._direction, position);
  74924. if ( distance > shape.boundingSphereRadius ) {
  74925. return;
  74926. }
  74927. var intersectMethod = this[shape.type];
  74928. if(intersectMethod){
  74929. intersectMethod.call(this, shape, quat, position, body);
  74930. }
  74931. };
  74932. var vector = new Vec3();
  74933. var normal = new Vec3();
  74934. var intersectPoint = new Vec3();
  74935. var a = new Vec3();
  74936. var b = new Vec3();
  74937. var c = new Vec3();
  74938. var d = new Vec3();
  74939. var tmpRaycastResult = new RaycastResult();
  74940. /**
  74941. * @method intersectBox
  74942. * @private
  74943. * @param {Shape} shape
  74944. * @param {Quaternion} quat
  74945. * @param {Vec3} position
  74946. * @param {Body} body
  74947. */
  74948. Ray.prototype.intersectBox = function(shape, quat, position, body){
  74949. return this.intersectConvex(shape.convexPolyhedronRepresentation, quat, position, body);
  74950. };
  74951. Ray.prototype[Shape.types.BOX] = Ray.prototype.intersectBox;
  74952. /**
  74953. * @method intersectPlane
  74954. * @private
  74955. * @param {Shape} shape
  74956. * @param {Quaternion} quat
  74957. * @param {Vec3} position
  74958. * @param {Body} body
  74959. */
  74960. Ray.prototype.intersectPlane = function(shape, quat, position, body){
  74961. var from = this.from;
  74962. var to = this.to;
  74963. var direction = this._direction;
  74964. // Get plane normal
  74965. var worldNormal = new Vec3(0, 0, 1);
  74966. quat.vmult(worldNormal, worldNormal);
  74967. var len = new Vec3();
  74968. from.vsub(position, len);
  74969. var planeToFrom = len.dot(worldNormal);
  74970. to.vsub(position, len);
  74971. var planeToTo = len.dot(worldNormal);
  74972. if(planeToFrom * planeToTo > 0){
  74973. // "from" and "to" are on the same side of the plane... bail out
  74974. return;
  74975. }
  74976. if(from.distanceTo(to) < planeToFrom){
  74977. return;
  74978. }
  74979. var n_dot_dir = worldNormal.dot(direction);
  74980. if (Math.abs(n_dot_dir) < this.precision) {
  74981. // No intersection
  74982. return;
  74983. }
  74984. var planePointToFrom = new Vec3();
  74985. var dir_scaled_with_t = new Vec3();
  74986. var hitPointWorld = new Vec3();
  74987. from.vsub(position, planePointToFrom);
  74988. var t = -worldNormal.dot(planePointToFrom) / n_dot_dir;
  74989. direction.scale(t, dir_scaled_with_t);
  74990. from.vadd(dir_scaled_with_t, hitPointWorld);
  74991. this.reportIntersection(worldNormal, hitPointWorld, shape, body, -1);
  74992. };
  74993. Ray.prototype[Shape.types.PLANE] = Ray.prototype.intersectPlane;
  74994. /**
  74995. * Get the world AABB of the ray.
  74996. * @method getAABB
  74997. * @param {AABB} aabb
  74998. */
  74999. Ray.prototype.getAABB = function(result){
  75000. var to = this.to;
  75001. var from = this.from;
  75002. result.lowerBound.x = Math.min(to.x, from.x);
  75003. result.lowerBound.y = Math.min(to.y, from.y);
  75004. result.lowerBound.z = Math.min(to.z, from.z);
  75005. result.upperBound.x = Math.max(to.x, from.x);
  75006. result.upperBound.y = Math.max(to.y, from.y);
  75007. result.upperBound.z = Math.max(to.z, from.z);
  75008. };
  75009. var intersectConvexOptions = {
  75010. faceList: [0]
  75011. };
  75012. /**
  75013. * @method intersectHeightfield
  75014. * @private
  75015. * @param {Shape} shape
  75016. * @param {Quaternion} quat
  75017. * @param {Vec3} position
  75018. * @param {Body} body
  75019. */
  75020. Ray.prototype.intersectHeightfield = function(shape, quat, position, body){
  75021. var data = shape.data,
  75022. w = shape.elementSize,
  75023. worldPillarOffset = new Vec3();
  75024. // Convert the ray to local heightfield coordinates
  75025. var localRay = new Ray(this.from, this.to);
  75026. Transform.pointToLocalFrame(position, quat, localRay.from, localRay.from);
  75027. Transform.pointToLocalFrame(position, quat, localRay.to, localRay.to);
  75028. // Get the index of the data points to test against
  75029. var index = [];
  75030. var iMinX = null;
  75031. var iMinY = null;
  75032. var iMaxX = null;
  75033. var iMaxY = null;
  75034. var inside = shape.getIndexOfPosition(localRay.from.x, localRay.from.y, index, false);
  75035. if(inside){
  75036. iMinX = index[0];
  75037. iMinY = index[1];
  75038. iMaxX = index[0];
  75039. iMaxY = index[1];
  75040. }
  75041. inside = shape.getIndexOfPosition(localRay.to.x, localRay.to.y, index, false);
  75042. if(inside){
  75043. if (iMinX === null || index[0] < iMinX) { iMinX = index[0]; }
  75044. if (iMaxX === null || index[0] > iMaxX) { iMaxX = index[0]; }
  75045. if (iMinY === null || index[1] < iMinY) { iMinY = index[1]; }
  75046. if (iMaxY === null || index[1] > iMaxY) { iMaxY = index[1]; }
  75047. }
  75048. if(iMinX === null){
  75049. return;
  75050. }
  75051. var minMax = [];
  75052. shape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);
  75053. var min = minMax[0];
  75054. var max = minMax[1];
  75055. // // Bail out if the ray can't touch the bounding box
  75056. // // TODO
  75057. // var aabb = new AABB();
  75058. // this.getAABB(aabb);
  75059. // if(aabb.intersects()){
  75060. // return;
  75061. // }
  75062. for(var i = iMinX; i <= iMaxX; i++){
  75063. for(var j = iMinY; j <= iMaxY; j++){
  75064. if(this.result._shouldStop){
  75065. return;
  75066. }
  75067. // Lower triangle
  75068. shape.getConvexTrianglePillar(i, j, false);
  75069. Transform.pointToWorldFrame(position, quat, shape.pillarOffset, worldPillarOffset);
  75070. this.intersectConvex(shape.pillarConvex, quat, worldPillarOffset, body, intersectConvexOptions);
  75071. if(this.result._shouldStop){
  75072. return;
  75073. }
  75074. // Upper triangle
  75075. shape.getConvexTrianglePillar(i, j, true);
  75076. Transform.pointToWorldFrame(position, quat, shape.pillarOffset, worldPillarOffset);
  75077. this.intersectConvex(shape.pillarConvex, quat, worldPillarOffset, body, intersectConvexOptions);
  75078. }
  75079. }
  75080. };
  75081. Ray.prototype[Shape.types.HEIGHTFIELD] = Ray.prototype.intersectHeightfield;
  75082. var Ray_intersectSphere_intersectionPoint = new Vec3();
  75083. var Ray_intersectSphere_normal = new Vec3();
  75084. /**
  75085. * @method intersectSphere
  75086. * @private
  75087. * @param {Shape} shape
  75088. * @param {Quaternion} quat
  75089. * @param {Vec3} position
  75090. * @param {Body} body
  75091. */
  75092. Ray.prototype.intersectSphere = function(shape, quat, position, body){
  75093. var from = this.from,
  75094. to = this.to,
  75095. r = shape.radius;
  75096. var a = Math.pow(to.x - from.x, 2) + Math.pow(to.y - from.y, 2) + Math.pow(to.z - from.z, 2);
  75097. 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));
  75098. 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);
  75099. var delta = Math.pow(b, 2) - 4 * a * c;
  75100. var intersectionPoint = Ray_intersectSphere_intersectionPoint;
  75101. var normal = Ray_intersectSphere_normal;
  75102. if(delta < 0){
  75103. // No intersection
  75104. return;
  75105. } else if(delta === 0){
  75106. // single intersection point
  75107. from.lerp(to, delta, intersectionPoint);
  75108. intersectionPoint.vsub(position, normal);
  75109. normal.normalize();
  75110. this.reportIntersection(normal, intersectionPoint, shape, body, -1);
  75111. } else {
  75112. var d1 = (- b - Math.sqrt(delta)) / (2 * a);
  75113. var d2 = (- b + Math.sqrt(delta)) / (2 * a);
  75114. if(d1 >= 0 && d1 <= 1){
  75115. from.lerp(to, d1, intersectionPoint);
  75116. intersectionPoint.vsub(position, normal);
  75117. normal.normalize();
  75118. this.reportIntersection(normal, intersectionPoint, shape, body, -1);
  75119. }
  75120. if(this.result._shouldStop){
  75121. return;
  75122. }
  75123. if(d2 >= 0 && d2 <= 1){
  75124. from.lerp(to, d2, intersectionPoint);
  75125. intersectionPoint.vsub(position, normal);
  75126. normal.normalize();
  75127. this.reportIntersection(normal, intersectionPoint, shape, body, -1);
  75128. }
  75129. }
  75130. };
  75131. Ray.prototype[Shape.types.SPHERE] = Ray.prototype.intersectSphere;
  75132. var intersectConvex_normal = new Vec3();
  75133. var intersectConvex_minDistNormal = new Vec3();
  75134. var intersectConvex_minDistIntersect = new Vec3();
  75135. var intersectConvex_vector = new Vec3();
  75136. /**
  75137. * @method intersectConvex
  75138. * @private
  75139. * @param {Shape} shape
  75140. * @param {Quaternion} quat
  75141. * @param {Vec3} position
  75142. * @param {Body} body
  75143. * @param {object} [options]
  75144. * @param {array} [options.faceList]
  75145. */
  75146. Ray.prototype.intersectConvex = function intersectConvex(
  75147. shape,
  75148. quat,
  75149. position,
  75150. body,
  75151. options
  75152. ){
  75153. var minDistNormal = intersectConvex_minDistNormal;
  75154. var normal = intersectConvex_normal;
  75155. var vector = intersectConvex_vector;
  75156. var minDistIntersect = intersectConvex_minDistIntersect;
  75157. var faceList = (options && options.faceList) || null;
  75158. // Checking faces
  75159. var faces = shape.faces,
  75160. vertices = shape.vertices,
  75161. normals = shape.faceNormals;
  75162. var direction = this._direction;
  75163. var from = this.from;
  75164. var to = this.to;
  75165. var fromToDistance = from.distanceTo(to);
  75166. var minDist = -1;
  75167. var Nfaces = faceList ? faceList.length : faces.length;
  75168. var result = this.result;
  75169. for (var j = 0; !result._shouldStop && j < Nfaces; j++) {
  75170. var fi = faceList ? faceList[j] : j;
  75171. var face = faces[fi];
  75172. var faceNormal = normals[fi];
  75173. var q = quat;
  75174. var x = position;
  75175. // determine if ray intersects the plane of the face
  75176. // note: this works regardless of the direction of the face normal
  75177. // Get plane point in world coordinates...
  75178. vector.copy(vertices[face[0]]);
  75179. q.vmult(vector,vector);
  75180. vector.vadd(x,vector);
  75181. // ...but make it relative to the ray from. We'll fix this later.
  75182. vector.vsub(from,vector);
  75183. // Get plane normal
  75184. q.vmult(faceNormal,normal);
  75185. // If this dot product is negative, we have something interesting
  75186. var dot = direction.dot(normal);
  75187. // Bail out if ray and plane are parallel
  75188. if ( Math.abs( dot ) < this.precision ){
  75189. continue;
  75190. }
  75191. // calc distance to plane
  75192. var scalar = normal.dot(vector) / dot;
  75193. // if negative distance, then plane is behind ray
  75194. if (scalar < 0){
  75195. continue;
  75196. }
  75197. // if (dot < 0) {
  75198. // Intersection point is from + direction * scalar
  75199. direction.mult(scalar,intersectPoint);
  75200. intersectPoint.vadd(from,intersectPoint);
  75201. // a is the point we compare points b and c with.
  75202. a.copy(vertices[face[0]]);
  75203. q.vmult(a,a);
  75204. x.vadd(a,a);
  75205. for(var i = 1; !result._shouldStop && i < face.length - 1; i++){
  75206. // Transform 3 vertices to world coords
  75207. b.copy(vertices[face[i]]);
  75208. c.copy(vertices[face[i+1]]);
  75209. q.vmult(b,b);
  75210. q.vmult(c,c);
  75211. x.vadd(b,b);
  75212. x.vadd(c,c);
  75213. var distance = intersectPoint.distanceTo(from);
  75214. if(!(pointInTriangle(intersectPoint, a, b, c) || pointInTriangle(intersectPoint, b, a, c)) || distance > fromToDistance){
  75215. continue;
  75216. }
  75217. this.reportIntersection(normal, intersectPoint, shape, body, fi);
  75218. }
  75219. // }
  75220. }
  75221. };
  75222. Ray.prototype[Shape.types.CONVEXPOLYHEDRON] = Ray.prototype.intersectConvex;
  75223. var intersectTrimesh_normal = new Vec3();
  75224. var intersectTrimesh_localDirection = new Vec3();
  75225. var intersectTrimesh_localFrom = new Vec3();
  75226. var intersectTrimesh_localTo = new Vec3();
  75227. var intersectTrimesh_worldNormal = new Vec3();
  75228. var intersectTrimesh_worldIntersectPoint = new Vec3();
  75229. var intersectTrimesh_localAABB = new AABB();
  75230. var intersectTrimesh_triangles = [];
  75231. var intersectTrimesh_treeTransform = new Transform();
  75232. /**
  75233. * @method intersectTrimesh
  75234. * @private
  75235. * @param {Shape} shape
  75236. * @param {Quaternion} quat
  75237. * @param {Vec3} position
  75238. * @param {Body} body
  75239. * @param {object} [options]
  75240. * @todo Optimize by transforming the world to local space first.
  75241. * @todo Use Octree lookup
  75242. */
  75243. Ray.prototype.intersectTrimesh = function intersectTrimesh(
  75244. mesh,
  75245. quat,
  75246. position,
  75247. body,
  75248. options
  75249. ){
  75250. var normal = intersectTrimesh_normal;
  75251. var triangles = intersectTrimesh_triangles;
  75252. var treeTransform = intersectTrimesh_treeTransform;
  75253. var minDistNormal = intersectConvex_minDistNormal;
  75254. var vector = intersectConvex_vector;
  75255. var minDistIntersect = intersectConvex_minDistIntersect;
  75256. var localAABB = intersectTrimesh_localAABB;
  75257. var localDirection = intersectTrimesh_localDirection;
  75258. var localFrom = intersectTrimesh_localFrom;
  75259. var localTo = intersectTrimesh_localTo;
  75260. var worldIntersectPoint = intersectTrimesh_worldIntersectPoint;
  75261. var worldNormal = intersectTrimesh_worldNormal;
  75262. var faceList = (options && options.faceList) || null;
  75263. // Checking faces
  75264. var indices = mesh.indices,
  75265. vertices = mesh.vertices,
  75266. normals = mesh.faceNormals;
  75267. var from = this.from;
  75268. var to = this.to;
  75269. var direction = this._direction;
  75270. var minDist = -1;
  75271. treeTransform.position.copy(position);
  75272. treeTransform.quaternion.copy(quat);
  75273. // Transform ray to local space!
  75274. Transform.vectorToLocalFrame(position, quat, direction, localDirection);
  75275. //body.vectorToLocalFrame(direction, localDirection);
  75276. Transform.pointToLocalFrame(position, quat, from, localFrom);
  75277. //body.pointToLocalFrame(from, localFrom);
  75278. Transform.pointToLocalFrame(position, quat, to, localTo);
  75279. //body.pointToLocalFrame(to, localTo);
  75280. var fromToDistanceSquared = localFrom.distanceSquared(localTo);
  75281. mesh.tree.rayQuery(this, treeTransform, triangles);
  75282. for (var i = 0, N = triangles.length; !this.result._shouldStop && i !== N; i++) {
  75283. var trianglesIndex = triangles[i];
  75284. mesh.getNormal(trianglesIndex, normal);
  75285. // determine if ray intersects the plane of the face
  75286. // note: this works regardless of the direction of the face normal
  75287. // Get plane point in world coordinates...
  75288. mesh.getVertex(indices[trianglesIndex * 3], a);
  75289. // ...but make it relative to the ray from. We'll fix this later.
  75290. a.vsub(localFrom,vector);
  75291. // Get plane normal
  75292. // quat.vmult(normal, normal);
  75293. // If this dot product is negative, we have something interesting
  75294. var dot = localDirection.dot(normal);
  75295. // Bail out if ray and plane are parallel
  75296. // if (Math.abs( dot ) < this.precision){
  75297. // continue;
  75298. // }
  75299. // calc distance to plane
  75300. var scalar = normal.dot(vector) / dot;
  75301. // if negative distance, then plane is behind ray
  75302. if (scalar < 0){
  75303. continue;
  75304. }
  75305. // Intersection point is from + direction * scalar
  75306. localDirection.scale(scalar,intersectPoint);
  75307. intersectPoint.vadd(localFrom,intersectPoint);
  75308. // Get triangle vertices
  75309. mesh.getVertex(indices[trianglesIndex * 3 + 1], b);
  75310. mesh.getVertex(indices[trianglesIndex * 3 + 2], c);
  75311. var squaredDistance = intersectPoint.distanceSquared(localFrom);
  75312. if(!(pointInTriangle(intersectPoint, b, a, c) || pointInTriangle(intersectPoint, a, b, c)) || squaredDistance > fromToDistanceSquared){
  75313. continue;
  75314. }
  75315. // transform intersectpoint and normal to world
  75316. Transform.vectorToWorldFrame(quat, normal, worldNormal);
  75317. //body.vectorToWorldFrame(normal, worldNormal);
  75318. Transform.pointToWorldFrame(position, quat, intersectPoint, worldIntersectPoint);
  75319. //body.pointToWorldFrame(intersectPoint, worldIntersectPoint);
  75320. this.reportIntersection(worldNormal, worldIntersectPoint, mesh, body, trianglesIndex);
  75321. }
  75322. triangles.length = 0;
  75323. };
  75324. Ray.prototype[Shape.types.TRIMESH] = Ray.prototype.intersectTrimesh;
  75325. /**
  75326. * @method reportIntersection
  75327. * @private
  75328. * @param {Vec3} normal
  75329. * @param {Vec3} hitPointWorld
  75330. * @param {Shape} shape
  75331. * @param {Body} body
  75332. * @return {boolean} True if the intersections should continue
  75333. */
  75334. Ray.prototype.reportIntersection = function(normal, hitPointWorld, shape, body, hitFaceIndex){
  75335. var from = this.from;
  75336. var to = this.to;
  75337. var distance = from.distanceTo(hitPointWorld);
  75338. var result = this.result;
  75339. // Skip back faces?
  75340. if(this.skipBackfaces && normal.dot(this._direction) > 0){
  75341. return;
  75342. }
  75343. result.hitFaceIndex = typeof(hitFaceIndex) !== 'undefined' ? hitFaceIndex : -1;
  75344. switch(this.mode){
  75345. case Ray.ALL:
  75346. this.hasHit = true;
  75347. result.set(
  75348. from,
  75349. to,
  75350. normal,
  75351. hitPointWorld,
  75352. shape,
  75353. body,
  75354. distance
  75355. );
  75356. result.hasHit = true;
  75357. this.callback(result);
  75358. break;
  75359. case Ray.CLOSEST:
  75360. // Store if closer than current closest
  75361. if(distance < result.distance || !result.hasHit){
  75362. this.hasHit = true;
  75363. result.hasHit = true;
  75364. result.set(
  75365. from,
  75366. to,
  75367. normal,
  75368. hitPointWorld,
  75369. shape,
  75370. body,
  75371. distance
  75372. );
  75373. }
  75374. break;
  75375. case Ray.ANY:
  75376. // Report and stop.
  75377. this.hasHit = true;
  75378. result.hasHit = true;
  75379. result.set(
  75380. from,
  75381. to,
  75382. normal,
  75383. hitPointWorld,
  75384. shape,
  75385. body,
  75386. distance
  75387. );
  75388. result._shouldStop = true;
  75389. break;
  75390. }
  75391. };
  75392. var v0 = new Vec3(),
  75393. intersect = new Vec3();
  75394. function distanceFromIntersection(from, direction, position) {
  75395. // v0 is vector from from to position
  75396. position.vsub(from,v0);
  75397. var dot = v0.dot(direction);
  75398. // intersect = direction*dot + from
  75399. direction.mult(dot,intersect);
  75400. intersect.vadd(from,intersect);
  75401. var distance = position.distanceTo(intersect);
  75402. return distance;
  75403. }
  75404. },{"../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){
  75405. var Vec3 = _dereq_('../math/Vec3');
  75406. module.exports = RaycastResult;
  75407. /**
  75408. * Storage for Ray casting data.
  75409. * @class RaycastResult
  75410. * @constructor
  75411. */
  75412. function RaycastResult(){
  75413. /**
  75414. * @property {Vec3} rayFromWorld
  75415. */
  75416. this.rayFromWorld = new Vec3();
  75417. /**
  75418. * @property {Vec3} rayToWorld
  75419. */
  75420. this.rayToWorld = new Vec3();
  75421. /**
  75422. * @property {Vec3} hitNormalWorld
  75423. */
  75424. this.hitNormalWorld = new Vec3();
  75425. /**
  75426. * @property {Vec3} hitPointWorld
  75427. */
  75428. this.hitPointWorld = new Vec3();
  75429. /**
  75430. * @property {boolean} hasHit
  75431. */
  75432. this.hasHit = false;
  75433. /**
  75434. * The hit shape, or null.
  75435. * @property {Shape} shape
  75436. */
  75437. this.shape = null;
  75438. /**
  75439. * The hit body, or null.
  75440. * @property {Body} body
  75441. */
  75442. this.body = null;
  75443. /**
  75444. * The index of the hit triangle, if the hit shape was a trimesh.
  75445. * @property {number} hitFaceIndex
  75446. * @default -1
  75447. */
  75448. this.hitFaceIndex = -1;
  75449. /**
  75450. * Distance to the hit. Will be set to -1 if there was no hit.
  75451. * @property {number} distance
  75452. * @default -1
  75453. */
  75454. this.distance = -1;
  75455. /**
  75456. * If the ray should stop traversing the bodies.
  75457. * @private
  75458. * @property {Boolean} _shouldStop
  75459. * @default false
  75460. */
  75461. this._shouldStop = false;
  75462. }
  75463. /**
  75464. * Reset all result data.
  75465. * @method reset
  75466. */
  75467. RaycastResult.prototype.reset = function () {
  75468. this.rayFromWorld.setZero();
  75469. this.rayToWorld.setZero();
  75470. this.hitNormalWorld.setZero();
  75471. this.hitPointWorld.setZero();
  75472. this.hasHit = false;
  75473. this.shape = null;
  75474. this.body = null;
  75475. this.hitFaceIndex = -1;
  75476. this.distance = -1;
  75477. this._shouldStop = false;
  75478. };
  75479. /**
  75480. * @method abort
  75481. */
  75482. RaycastResult.prototype.abort = function(){
  75483. this._shouldStop = true;
  75484. };
  75485. /**
  75486. * @method set
  75487. * @param {Vec3} rayFromWorld
  75488. * @param {Vec3} rayToWorld
  75489. * @param {Vec3} hitNormalWorld
  75490. * @param {Vec3} hitPointWorld
  75491. * @param {Shape} shape
  75492. * @param {Body} body
  75493. * @param {number} distance
  75494. */
  75495. RaycastResult.prototype.set = function(
  75496. rayFromWorld,
  75497. rayToWorld,
  75498. hitNormalWorld,
  75499. hitPointWorld,
  75500. shape,
  75501. body,
  75502. distance
  75503. ){
  75504. this.rayFromWorld.copy(rayFromWorld);
  75505. this.rayToWorld.copy(rayToWorld);
  75506. this.hitNormalWorld.copy(hitNormalWorld);
  75507. this.hitPointWorld.copy(hitPointWorld);
  75508. this.shape = shape;
  75509. this.body = body;
  75510. this.distance = distance;
  75511. };
  75512. },{"../math/Vec3":30}],11:[function(_dereq_,module,exports){
  75513. var Shape = _dereq_('../shapes/Shape');
  75514. var Broadphase = _dereq_('../collision/Broadphase');
  75515. module.exports = SAPBroadphase;
  75516. /**
  75517. * Sweep and prune broadphase along one axis.
  75518. *
  75519. * @class SAPBroadphase
  75520. * @constructor
  75521. * @param {World} [world]
  75522. * @extends Broadphase
  75523. */
  75524. function SAPBroadphase(world){
  75525. Broadphase.apply(this);
  75526. /**
  75527. * List of bodies currently in the broadphase.
  75528. * @property axisList
  75529. * @type {Array}
  75530. */
  75531. this.axisList = [];
  75532. /**
  75533. * The world to search in.
  75534. * @property world
  75535. * @type {World}
  75536. */
  75537. this.world = null;
  75538. /**
  75539. * 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.
  75540. * @property axisIndex
  75541. * @type {Number}
  75542. */
  75543. this.axisIndex = 0;
  75544. var axisList = this.axisList;
  75545. this._addBodyHandler = function(e){
  75546. axisList.push(e.body);
  75547. };
  75548. this._removeBodyHandler = function(e){
  75549. var idx = axisList.indexOf(e.body);
  75550. if(idx !== -1){
  75551. axisList.splice(idx,1);
  75552. }
  75553. };
  75554. if(world){
  75555. this.setWorld(world);
  75556. }
  75557. }
  75558. SAPBroadphase.prototype = new Broadphase();
  75559. /**
  75560. * Change the world
  75561. * @method setWorld
  75562. * @param {World} world
  75563. */
  75564. SAPBroadphase.prototype.setWorld = function(world){
  75565. // Clear the old axis array
  75566. this.axisList.length = 0;
  75567. // Add all bodies from the new world
  75568. for(var i=0; i<world.bodies.length; i++){
  75569. this.axisList.push(world.bodies[i]);
  75570. }
  75571. // Remove old handlers, if any
  75572. world.removeEventListener("addBody", this._addBodyHandler);
  75573. world.removeEventListener("removeBody", this._removeBodyHandler);
  75574. // Add handlers to update the list of bodies.
  75575. world.addEventListener("addBody", this._addBodyHandler);
  75576. world.addEventListener("removeBody", this._removeBodyHandler);
  75577. this.world = world;
  75578. this.dirty = true;
  75579. };
  75580. /**
  75581. * @static
  75582. * @method insertionSortX
  75583. * @param {Array} a
  75584. * @return {Array}
  75585. */
  75586. SAPBroadphase.insertionSortX = function(a) {
  75587. for(var i=1,l=a.length;i<l;i++) {
  75588. var v = a[i];
  75589. for(var j=i - 1;j>=0;j--) {
  75590. if(a[j].aabb.lowerBound.x <= v.aabb.lowerBound.x){
  75591. break;
  75592. }
  75593. a[j+1] = a[j];
  75594. }
  75595. a[j+1] = v;
  75596. }
  75597. return a;
  75598. };
  75599. /**
  75600. * @static
  75601. * @method insertionSortY
  75602. * @param {Array} a
  75603. * @return {Array}
  75604. */
  75605. SAPBroadphase.insertionSortY = function(a) {
  75606. for(var i=1,l=a.length;i<l;i++) {
  75607. var v = a[i];
  75608. for(var j=i - 1;j>=0;j--) {
  75609. if(a[j].aabb.lowerBound.y <= v.aabb.lowerBound.y){
  75610. break;
  75611. }
  75612. a[j+1] = a[j];
  75613. }
  75614. a[j+1] = v;
  75615. }
  75616. return a;
  75617. };
  75618. /**
  75619. * @static
  75620. * @method insertionSortZ
  75621. * @param {Array} a
  75622. * @return {Array}
  75623. */
  75624. SAPBroadphase.insertionSortZ = function(a) {
  75625. for(var i=1,l=a.length;i<l;i++) {
  75626. var v = a[i];
  75627. for(var j=i - 1;j>=0;j--) {
  75628. if(a[j].aabb.lowerBound.z <= v.aabb.lowerBound.z){
  75629. break;
  75630. }
  75631. a[j+1] = a[j];
  75632. }
  75633. a[j+1] = v;
  75634. }
  75635. return a;
  75636. };
  75637. /**
  75638. * Collect all collision pairs
  75639. * @method collisionPairs
  75640. * @param {World} world
  75641. * @param {Array} p1
  75642. * @param {Array} p2
  75643. */
  75644. SAPBroadphase.prototype.collisionPairs = function(world,p1,p2){
  75645. var bodies = this.axisList,
  75646. N = bodies.length,
  75647. axisIndex = this.axisIndex,
  75648. i, j;
  75649. if(this.dirty){
  75650. this.sortList();
  75651. this.dirty = false;
  75652. }
  75653. // Look through the list
  75654. for(i=0; i !== N; i++){
  75655. var bi = bodies[i];
  75656. for(j=i+1; j < N; j++){
  75657. var bj = bodies[j];
  75658. if(!this.needBroadphaseCollision(bi,bj)){
  75659. continue;
  75660. }
  75661. if(!SAPBroadphase.checkBounds(bi,bj,axisIndex)){
  75662. break;
  75663. }
  75664. this.intersectionTest(bi,bj,p1,p2);
  75665. }
  75666. }
  75667. };
  75668. SAPBroadphase.prototype.sortList = function(){
  75669. var axisList = this.axisList;
  75670. var axisIndex = this.axisIndex;
  75671. var N = axisList.length;
  75672. // Update AABBs
  75673. for(var i = 0; i!==N; i++){
  75674. var bi = axisList[i];
  75675. if(bi.aabbNeedsUpdate){
  75676. bi.computeAABB();
  75677. }
  75678. }
  75679. // Sort the list
  75680. if(axisIndex === 0){
  75681. SAPBroadphase.insertionSortX(axisList);
  75682. } else if(axisIndex === 1){
  75683. SAPBroadphase.insertionSortY(axisList);
  75684. } else if(axisIndex === 2){
  75685. SAPBroadphase.insertionSortZ(axisList);
  75686. }
  75687. };
  75688. /**
  75689. * Check if the bounds of two bodies overlap, along the given SAP axis.
  75690. * @static
  75691. * @method checkBounds
  75692. * @param {Body} bi
  75693. * @param {Body} bj
  75694. * @param {Number} axisIndex
  75695. * @return {Boolean}
  75696. */
  75697. SAPBroadphase.checkBounds = function(bi, bj, axisIndex){
  75698. var biPos;
  75699. var bjPos;
  75700. if(axisIndex === 0){
  75701. biPos = bi.position.x;
  75702. bjPos = bj.position.x;
  75703. } else if(axisIndex === 1){
  75704. biPos = bi.position.y;
  75705. bjPos = bj.position.y;
  75706. } else if(axisIndex === 2){
  75707. biPos = bi.position.z;
  75708. bjPos = bj.position.z;
  75709. }
  75710. var ri = bi.boundingRadius,
  75711. rj = bj.boundingRadius,
  75712. boundA1 = biPos - ri,
  75713. boundA2 = biPos + ri,
  75714. boundB1 = bjPos - rj,
  75715. boundB2 = bjPos + rj;
  75716. return boundB1 < boundA2;
  75717. };
  75718. /**
  75719. * Computes the variance of the body positions and estimates the best
  75720. * axis to use. Will automatically set property .axisIndex.
  75721. * @method autoDetectAxis
  75722. */
  75723. SAPBroadphase.prototype.autoDetectAxis = function(){
  75724. var sumX=0,
  75725. sumX2=0,
  75726. sumY=0,
  75727. sumY2=0,
  75728. sumZ=0,
  75729. sumZ2=0,
  75730. bodies = this.axisList,
  75731. N = bodies.length,
  75732. invN=1/N;
  75733. for(var i=0; i!==N; i++){
  75734. var b = bodies[i];
  75735. var centerX = b.position.x;
  75736. sumX += centerX;
  75737. sumX2 += centerX*centerX;
  75738. var centerY = b.position.y;
  75739. sumY += centerY;
  75740. sumY2 += centerY*centerY;
  75741. var centerZ = b.position.z;
  75742. sumZ += centerZ;
  75743. sumZ2 += centerZ*centerZ;
  75744. }
  75745. var varianceX = sumX2 - sumX*sumX*invN,
  75746. varianceY = sumY2 - sumY*sumY*invN,
  75747. varianceZ = sumZ2 - sumZ*sumZ*invN;
  75748. if(varianceX > varianceY){
  75749. if(varianceX > varianceZ){
  75750. this.axisIndex = 0;
  75751. } else{
  75752. this.axisIndex = 2;
  75753. }
  75754. } else if(varianceY > varianceZ){
  75755. this.axisIndex = 1;
  75756. } else{
  75757. this.axisIndex = 2;
  75758. }
  75759. };
  75760. /**
  75761. * Returns all the bodies within an AABB.
  75762. * @method aabbQuery
  75763. * @param {World} world
  75764. * @param {AABB} aabb
  75765. * @param {array} result An array to store resulting bodies in.
  75766. * @return {array}
  75767. */
  75768. SAPBroadphase.prototype.aabbQuery = function(world, aabb, result){
  75769. result = result || [];
  75770. if(this.dirty){
  75771. this.sortList();
  75772. this.dirty = false;
  75773. }
  75774. var axisIndex = this.axisIndex, axis = 'x';
  75775. if(axisIndex === 1){ axis = 'y'; }
  75776. if(axisIndex === 2){ axis = 'z'; }
  75777. var axisList = this.axisList;
  75778. var lower = aabb.lowerBound[axis];
  75779. var upper = aabb.upperBound[axis];
  75780. for(var i = 0; i < axisList.length; i++){
  75781. var b = axisList[i];
  75782. if(b.aabbNeedsUpdate){
  75783. b.computeAABB();
  75784. }
  75785. if(b.aabb.overlaps(aabb)){
  75786. result.push(b);
  75787. }
  75788. }
  75789. return result;
  75790. };
  75791. },{"../collision/Broadphase":5,"../shapes/Shape":43}],12:[function(_dereq_,module,exports){
  75792. module.exports = ConeTwistConstraint;
  75793. var Constraint = _dereq_('./Constraint');
  75794. var PointToPointConstraint = _dereq_('./PointToPointConstraint');
  75795. var ConeEquation = _dereq_('../equations/ConeEquation');
  75796. var RotationalEquation = _dereq_('../equations/RotationalEquation');
  75797. var ContactEquation = _dereq_('../equations/ContactEquation');
  75798. var Vec3 = _dereq_('../math/Vec3');
  75799. /**
  75800. * @class ConeTwistConstraint
  75801. * @constructor
  75802. * @author schteppe
  75803. * @param {Body} bodyA
  75804. * @param {Body} bodyB
  75805. * @param {object} [options]
  75806. * @param {Vec3} [options.pivotA]
  75807. * @param {Vec3} [options.pivotB]
  75808. * @param {Vec3} [options.axisA]
  75809. * @param {Vec3} [options.axisB]
  75810. * @param {Number} [options.maxForce=1e6]
  75811. * @extends PointToPointConstraint
  75812. */
  75813. function ConeTwistConstraint(bodyA, bodyB, options){
  75814. options = options || {};
  75815. var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;
  75816. // Set pivot point in between
  75817. var pivotA = options.pivotA ? options.pivotA.clone() : new Vec3();
  75818. var pivotB = options.pivotB ? options.pivotB.clone() : new Vec3();
  75819. this.axisA = options.axisA ? options.axisA.clone() : new Vec3();
  75820. this.axisB = options.axisB ? options.axisB.clone() : new Vec3();
  75821. PointToPointConstraint.call(this, bodyA, pivotA, bodyB, pivotB, maxForce);
  75822. this.collideConnected = !!options.collideConnected;
  75823. this.angle = typeof(options.angle) !== 'undefined' ? options.angle : 0;
  75824. /**
  75825. * @property {ConeEquation} coneEquation
  75826. */
  75827. var c = this.coneEquation = new ConeEquation(bodyA,bodyB,options);
  75828. /**
  75829. * @property {RotationalEquation} twistEquation
  75830. */
  75831. var t = this.twistEquation = new RotationalEquation(bodyA,bodyB,options);
  75832. this.twistAngle = typeof(options.twistAngle) !== 'undefined' ? options.twistAngle : 0;
  75833. // Make the cone equation push the bodies toward the cone axis, not outward
  75834. c.maxForce = 0;
  75835. c.minForce = -maxForce;
  75836. // Make the twist equation add torque toward the initial position
  75837. t.maxForce = 0;
  75838. t.minForce = -maxForce;
  75839. this.equations.push(c, t);
  75840. }
  75841. ConeTwistConstraint.prototype = new PointToPointConstraint();
  75842. ConeTwistConstraint.constructor = ConeTwistConstraint;
  75843. var ConeTwistConstraint_update_tmpVec1 = new Vec3();
  75844. var ConeTwistConstraint_update_tmpVec2 = new Vec3();
  75845. ConeTwistConstraint.prototype.update = function(){
  75846. var bodyA = this.bodyA,
  75847. bodyB = this.bodyB,
  75848. cone = this.coneEquation,
  75849. twist = this.twistEquation;
  75850. PointToPointConstraint.prototype.update.call(this);
  75851. // Update the axes to the cone constraint
  75852. bodyA.vectorToWorldFrame(this.axisA, cone.axisA);
  75853. bodyB.vectorToWorldFrame(this.axisB, cone.axisB);
  75854. // Update the world axes in the twist constraint
  75855. this.axisA.tangents(twist.axisA, twist.axisA);
  75856. bodyA.vectorToWorldFrame(twist.axisA, twist.axisA);
  75857. this.axisB.tangents(twist.axisB, twist.axisB);
  75858. bodyB.vectorToWorldFrame(twist.axisB, twist.axisB);
  75859. cone.angle = this.angle;
  75860. twist.maxAngle = this.twistAngle;
  75861. };
  75862. },{"../equations/ConeEquation":18,"../equations/ContactEquation":19,"../equations/RotationalEquation":22,"../math/Vec3":30,"./Constraint":13,"./PointToPointConstraint":17}],13:[function(_dereq_,module,exports){
  75863. module.exports = Constraint;
  75864. var Utils = _dereq_('../utils/Utils');
  75865. /**
  75866. * Constraint base class
  75867. * @class Constraint
  75868. * @author schteppe
  75869. * @constructor
  75870. * @param {Body} bodyA
  75871. * @param {Body} bodyB
  75872. * @param {object} [options]
  75873. * @param {boolean} [options.collideConnected=true]
  75874. * @param {boolean} [options.wakeUpBodies=true]
  75875. */
  75876. function Constraint(bodyA, bodyB, options){
  75877. options = Utils.defaults(options,{
  75878. collideConnected : true,
  75879. wakeUpBodies : true,
  75880. });
  75881. /**
  75882. * Equations to be solved in this constraint
  75883. * @property equations
  75884. * @type {Array}
  75885. */
  75886. this.equations = [];
  75887. /**
  75888. * @property {Body} bodyA
  75889. */
  75890. this.bodyA = bodyA;
  75891. /**
  75892. * @property {Body} bodyB
  75893. */
  75894. this.bodyB = bodyB;
  75895. /**
  75896. * @property {Number} id
  75897. */
  75898. this.id = Constraint.idCounter++;
  75899. /**
  75900. * Set to true if you want the bodies to collide when they are connected.
  75901. * @property collideConnected
  75902. * @type {boolean}
  75903. */
  75904. this.collideConnected = options.collideConnected;
  75905. if(options.wakeUpBodies){
  75906. if(bodyA){
  75907. bodyA.wakeUp();
  75908. }
  75909. if(bodyB){
  75910. bodyB.wakeUp();
  75911. }
  75912. }
  75913. }
  75914. /**
  75915. * Update all the equations with data.
  75916. * @method update
  75917. */
  75918. Constraint.prototype.update = function(){
  75919. throw new Error("method update() not implmemented in this Constraint subclass!");
  75920. };
  75921. /**
  75922. * Enables all equations in the constraint.
  75923. * @method enable
  75924. */
  75925. Constraint.prototype.enable = function(){
  75926. var eqs = this.equations;
  75927. for(var i=0; i<eqs.length; i++){
  75928. eqs[i].enabled = true;
  75929. }
  75930. };
  75931. /**
  75932. * Disables all equations in the constraint.
  75933. * @method disable
  75934. */
  75935. Constraint.prototype.disable = function(){
  75936. var eqs = this.equations;
  75937. for(var i=0; i<eqs.length; i++){
  75938. eqs[i].enabled = false;
  75939. }
  75940. };
  75941. Constraint.idCounter = 0;
  75942. },{"../utils/Utils":53}],14:[function(_dereq_,module,exports){
  75943. module.exports = DistanceConstraint;
  75944. var Constraint = _dereq_('./Constraint');
  75945. var ContactEquation = _dereq_('../equations/ContactEquation');
  75946. /**
  75947. * Constrains two bodies to be at a constant distance from each others center of mass.
  75948. * @class DistanceConstraint
  75949. * @constructor
  75950. * @author schteppe
  75951. * @param {Body} bodyA
  75952. * @param {Body} bodyB
  75953. * @param {Number} [distance] The distance to keep. If undefined, it will be set to the current distance between bodyA and bodyB
  75954. * @param {Number} [maxForce=1e6]
  75955. * @extends Constraint
  75956. */
  75957. function DistanceConstraint(bodyA,bodyB,distance,maxForce){
  75958. Constraint.call(this,bodyA,bodyB);
  75959. if(typeof(distance)==="undefined") {
  75960. distance = bodyA.position.distanceTo(bodyB.position);
  75961. }
  75962. if(typeof(maxForce)==="undefined") {
  75963. maxForce = 1e6;
  75964. }
  75965. /**
  75966. * @property {number} distance
  75967. */
  75968. this.distance = distance;
  75969. /**
  75970. * @property {ContactEquation} distanceEquation
  75971. */
  75972. var eq = this.distanceEquation = new ContactEquation(bodyA, bodyB);
  75973. this.equations.push(eq);
  75974. // Make it bidirectional
  75975. eq.minForce = -maxForce;
  75976. eq.maxForce = maxForce;
  75977. }
  75978. DistanceConstraint.prototype = new Constraint();
  75979. DistanceConstraint.prototype.update = function(){
  75980. var bodyA = this.bodyA;
  75981. var bodyB = this.bodyB;
  75982. var eq = this.distanceEquation;
  75983. var halfDist = this.distance * 0.5;
  75984. var normal = eq.ni;
  75985. bodyB.position.vsub(bodyA.position, normal);
  75986. normal.normalize();
  75987. normal.mult(halfDist, eq.ri);
  75988. normal.mult(-halfDist, eq.rj);
  75989. };
  75990. },{"../equations/ContactEquation":19,"./Constraint":13}],15:[function(_dereq_,module,exports){
  75991. module.exports = HingeConstraint;
  75992. var Constraint = _dereq_('./Constraint');
  75993. var PointToPointConstraint = _dereq_('./PointToPointConstraint');
  75994. var RotationalEquation = _dereq_('../equations/RotationalEquation');
  75995. var RotationalMotorEquation = _dereq_('../equations/RotationalMotorEquation');
  75996. var ContactEquation = _dereq_('../equations/ContactEquation');
  75997. var Vec3 = _dereq_('../math/Vec3');
  75998. /**
  75999. * Hinge constraint. Think of it as a door hinge. It tries to keep the door in the correct place and with the correct orientation.
  76000. * @class HingeConstraint
  76001. * @constructor
  76002. * @author schteppe
  76003. * @param {Body} bodyA
  76004. * @param {Body} bodyB
  76005. * @param {object} [options]
  76006. * @param {Vec3} [options.pivotA] A point defined locally in bodyA. This defines the offset of axisA.
  76007. * @param {Vec3} [options.axisA] An axis that bodyA can rotate around, defined locally in bodyA.
  76008. * @param {Vec3} [options.pivotB]
  76009. * @param {Vec3} [options.axisB]
  76010. * @param {Number} [options.maxForce=1e6]
  76011. * @extends PointToPointConstraint
  76012. */
  76013. function HingeConstraint(bodyA, bodyB, options){
  76014. options = options || {};
  76015. var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;
  76016. var pivotA = options.pivotA ? options.pivotA.clone() : new Vec3();
  76017. var pivotB = options.pivotB ? options.pivotB.clone() : new Vec3();
  76018. PointToPointConstraint.call(this, bodyA, pivotA, bodyB, pivotB, maxForce);
  76019. /**
  76020. * Rotation axis, defined locally in bodyA.
  76021. * @property {Vec3} axisA
  76022. */
  76023. var axisA = this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1,0,0);
  76024. axisA.normalize();
  76025. /**
  76026. * Rotation axis, defined locally in bodyB.
  76027. * @property {Vec3} axisB
  76028. */
  76029. var axisB = this.axisB = options.axisB ? options.axisB.clone() : new Vec3(1,0,0);
  76030. axisB.normalize();
  76031. /**
  76032. * @property {RotationalEquation} rotationalEquation1
  76033. */
  76034. var r1 = this.rotationalEquation1 = new RotationalEquation(bodyA,bodyB,options);
  76035. /**
  76036. * @property {RotationalEquation} rotationalEquation2
  76037. */
  76038. var r2 = this.rotationalEquation2 = new RotationalEquation(bodyA,bodyB,options);
  76039. /**
  76040. * @property {RotationalMotorEquation} motorEquation
  76041. */
  76042. var motor = this.motorEquation = new RotationalMotorEquation(bodyA,bodyB,maxForce);
  76043. motor.enabled = false; // Not enabled by default
  76044. // Equations to be fed to the solver
  76045. this.equations.push(
  76046. r1, // rotational1
  76047. r2, // rotational2
  76048. motor
  76049. );
  76050. }
  76051. HingeConstraint.prototype = new PointToPointConstraint();
  76052. HingeConstraint.constructor = HingeConstraint;
  76053. /**
  76054. * @method enableMotor
  76055. */
  76056. HingeConstraint.prototype.enableMotor = function(){
  76057. this.motorEquation.enabled = true;
  76058. };
  76059. /**
  76060. * @method disableMotor
  76061. */
  76062. HingeConstraint.prototype.disableMotor = function(){
  76063. this.motorEquation.enabled = false;
  76064. };
  76065. /**
  76066. * @method setMotorSpeed
  76067. * @param {number} speed
  76068. */
  76069. HingeConstraint.prototype.setMotorSpeed = function(speed){
  76070. this.motorEquation.targetVelocity = speed;
  76071. };
  76072. /**
  76073. * @method setMotorMaxForce
  76074. * @param {number} maxForce
  76075. */
  76076. HingeConstraint.prototype.setMotorMaxForce = function(maxForce){
  76077. this.motorEquation.maxForce = maxForce;
  76078. this.motorEquation.minForce = -maxForce;
  76079. };
  76080. var HingeConstraint_update_tmpVec1 = new Vec3();
  76081. var HingeConstraint_update_tmpVec2 = new Vec3();
  76082. HingeConstraint.prototype.update = function(){
  76083. var bodyA = this.bodyA,
  76084. bodyB = this.bodyB,
  76085. motor = this.motorEquation,
  76086. r1 = this.rotationalEquation1,
  76087. r2 = this.rotationalEquation2,
  76088. worldAxisA = HingeConstraint_update_tmpVec1,
  76089. worldAxisB = HingeConstraint_update_tmpVec2;
  76090. var axisA = this.axisA;
  76091. var axisB = this.axisB;
  76092. PointToPointConstraint.prototype.update.call(this);
  76093. // Get world axes
  76094. bodyA.quaternion.vmult(axisA, worldAxisA);
  76095. bodyB.quaternion.vmult(axisB, worldAxisB);
  76096. worldAxisA.tangents(r1.axisA, r2.axisA);
  76097. r1.axisB.copy(worldAxisB);
  76098. r2.axisB.copy(worldAxisB);
  76099. if(this.motorEquation.enabled){
  76100. bodyA.quaternion.vmult(this.axisA, motor.axisA);
  76101. bodyB.quaternion.vmult(this.axisB, motor.axisB);
  76102. }
  76103. };
  76104. },{"../equations/ContactEquation":19,"../equations/RotationalEquation":22,"../equations/RotationalMotorEquation":23,"../math/Vec3":30,"./Constraint":13,"./PointToPointConstraint":17}],16:[function(_dereq_,module,exports){
  76105. module.exports = LockConstraint;
  76106. var Constraint = _dereq_('./Constraint');
  76107. var PointToPointConstraint = _dereq_('./PointToPointConstraint');
  76108. var RotationalEquation = _dereq_('../equations/RotationalEquation');
  76109. var RotationalMotorEquation = _dereq_('../equations/RotationalMotorEquation');
  76110. var ContactEquation = _dereq_('../equations/ContactEquation');
  76111. var Vec3 = _dereq_('../math/Vec3');
  76112. /**
  76113. * Lock constraint. Will remove all degrees of freedom between the bodies.
  76114. * @class LockConstraint
  76115. * @constructor
  76116. * @author schteppe
  76117. * @param {Body} bodyA
  76118. * @param {Body} bodyB
  76119. * @param {object} [options]
  76120. * @param {Number} [options.maxForce=1e6]
  76121. * @extends PointToPointConstraint
  76122. */
  76123. function LockConstraint(bodyA, bodyB, options){
  76124. options = options || {};
  76125. var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;
  76126. // Set pivot point in between
  76127. var pivotA = new Vec3();
  76128. var pivotB = new Vec3();
  76129. var halfWay = new Vec3();
  76130. bodyA.position.vadd(bodyB.position, halfWay);
  76131. halfWay.scale(0.5, halfWay);
  76132. bodyB.pointToLocalFrame(halfWay, pivotB);
  76133. bodyA.pointToLocalFrame(halfWay, pivotA);
  76134. PointToPointConstraint.call(this, bodyA, pivotA, bodyB, pivotB, maxForce);
  76135. /**
  76136. * @property {RotationalEquation} rotationalEquation1
  76137. */
  76138. var r1 = this.rotationalEquation1 = new RotationalEquation(bodyA,bodyB,options);
  76139. /**
  76140. * @property {RotationalEquation} rotationalEquation2
  76141. */
  76142. var r2 = this.rotationalEquation2 = new RotationalEquation(bodyA,bodyB,options);
  76143. /**
  76144. * @property {RotationalEquation} rotationalEquation3
  76145. */
  76146. var r3 = this.rotationalEquation3 = new RotationalEquation(bodyA,bodyB,options);
  76147. this.equations.push(r1, r2, r3);
  76148. }
  76149. LockConstraint.prototype = new PointToPointConstraint();
  76150. LockConstraint.constructor = LockConstraint;
  76151. var LockConstraint_update_tmpVec1 = new Vec3();
  76152. var LockConstraint_update_tmpVec2 = new Vec3();
  76153. LockConstraint.prototype.update = function(){
  76154. var bodyA = this.bodyA,
  76155. bodyB = this.bodyB,
  76156. motor = this.motorEquation,
  76157. r1 = this.rotationalEquation1,
  76158. r2 = this.rotationalEquation2,
  76159. r3 = this.rotationalEquation3,
  76160. worldAxisA = LockConstraint_update_tmpVec1,
  76161. worldAxisB = LockConstraint_update_tmpVec2;
  76162. PointToPointConstraint.prototype.update.call(this);
  76163. bodyA.vectorToWorldFrame(Vec3.UNIT_X, r1.axisA);
  76164. bodyB.vectorToWorldFrame(Vec3.UNIT_Y, r1.axisB);
  76165. bodyA.vectorToWorldFrame(Vec3.UNIT_Y, r2.axisA);
  76166. bodyB.vectorToWorldFrame(Vec3.UNIT_Z, r2.axisB);
  76167. bodyA.vectorToWorldFrame(Vec3.UNIT_Z, r3.axisA);
  76168. bodyB.vectorToWorldFrame(Vec3.UNIT_X, r3.axisB);
  76169. };
  76170. },{"../equations/ContactEquation":19,"../equations/RotationalEquation":22,"../equations/RotationalMotorEquation":23,"../math/Vec3":30,"./Constraint":13,"./PointToPointConstraint":17}],17:[function(_dereq_,module,exports){
  76171. module.exports = PointToPointConstraint;
  76172. var Constraint = _dereq_('./Constraint');
  76173. var ContactEquation = _dereq_('../equations/ContactEquation');
  76174. var Vec3 = _dereq_('../math/Vec3');
  76175. /**
  76176. * Connects two bodies at given offset points.
  76177. * @class PointToPointConstraint
  76178. * @extends Constraint
  76179. * @constructor
  76180. * @param {Body} bodyA
  76181. * @param {Vec3} pivotA The point relative to the center of mass of bodyA which bodyA is constrained to.
  76182. * @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.
  76183. * @param {Vec3} pivotB See pivotA.
  76184. * @param {Number} maxForce The maximum force that should be applied to constrain the bodies.
  76185. *
  76186. * @example
  76187. * var bodyA = new Body({ mass: 1 });
  76188. * var bodyB = new Body({ mass: 1 });
  76189. * bodyA.position.set(-1, 0, 0);
  76190. * bodyB.position.set(1, 0, 0);
  76191. * bodyA.addShape(shapeA);
  76192. * bodyB.addShape(shapeB);
  76193. * world.addBody(bodyA);
  76194. * world.addBody(bodyB);
  76195. * var localPivotA = new Vec3(1, 0, 0);
  76196. * var localPivotB = new Vec3(-1, 0, 0);
  76197. * var constraint = new PointToPointConstraint(bodyA, localPivotA, bodyB, localPivotB);
  76198. * world.addConstraint(constraint);
  76199. */
  76200. function PointToPointConstraint(bodyA,pivotA,bodyB,pivotB,maxForce){
  76201. Constraint.call(this,bodyA,bodyB);
  76202. maxForce = typeof(maxForce) !== 'undefined' ? maxForce : 1e6;
  76203. /**
  76204. * Pivot, defined locally in bodyA.
  76205. * @property {Vec3} pivotA
  76206. */
  76207. this.pivotA = pivotA ? pivotA.clone() : new Vec3();
  76208. /**
  76209. * Pivot, defined locally in bodyB.
  76210. * @property {Vec3} pivotB
  76211. */
  76212. this.pivotB = pivotB ? pivotB.clone() : new Vec3();
  76213. /**
  76214. * @property {ContactEquation} equationX
  76215. */
  76216. var x = this.equationX = new ContactEquation(bodyA,bodyB);
  76217. /**
  76218. * @property {ContactEquation} equationY
  76219. */
  76220. var y = this.equationY = new ContactEquation(bodyA,bodyB);
  76221. /**
  76222. * @property {ContactEquation} equationZ
  76223. */
  76224. var z = this.equationZ = new ContactEquation(bodyA,bodyB);
  76225. // Equations to be fed to the solver
  76226. this.equations.push(x, y, z);
  76227. // Make the equations bidirectional
  76228. x.minForce = y.minForce = z.minForce = -maxForce;
  76229. x.maxForce = y.maxForce = z.maxForce = maxForce;
  76230. x.ni.set(1, 0, 0);
  76231. y.ni.set(0, 1, 0);
  76232. z.ni.set(0, 0, 1);
  76233. }
  76234. PointToPointConstraint.prototype = new Constraint();
  76235. PointToPointConstraint.prototype.update = function(){
  76236. var bodyA = this.bodyA;
  76237. var bodyB = this.bodyB;
  76238. var x = this.equationX;
  76239. var y = this.equationY;
  76240. var z = this.equationZ;
  76241. // Rotate the pivots to world space
  76242. bodyA.quaternion.vmult(this.pivotA,x.ri);
  76243. bodyB.quaternion.vmult(this.pivotB,x.rj);
  76244. y.ri.copy(x.ri);
  76245. y.rj.copy(x.rj);
  76246. z.ri.copy(x.ri);
  76247. z.rj.copy(x.rj);
  76248. };
  76249. },{"../equations/ContactEquation":19,"../math/Vec3":30,"./Constraint":13}],18:[function(_dereq_,module,exports){
  76250. module.exports = ConeEquation;
  76251. var Vec3 = _dereq_('../math/Vec3');
  76252. var Mat3 = _dereq_('../math/Mat3');
  76253. var Equation = _dereq_('./Equation');
  76254. /**
  76255. * Cone equation. Works to keep the given body world vectors aligned, or tilted within a given angle from each other.
  76256. * @class ConeEquation
  76257. * @constructor
  76258. * @author schteppe
  76259. * @param {Body} bodyA
  76260. * @param {Body} bodyB
  76261. * @param {Vec3} [options.axisA] Local axis in A
  76262. * @param {Vec3} [options.axisB] Local axis in B
  76263. * @param {Vec3} [options.angle] The "cone angle" to keep
  76264. * @param {number} [options.maxForce=1e6]
  76265. * @extends Equation
  76266. */
  76267. function ConeEquation(bodyA, bodyB, options){
  76268. options = options || {};
  76269. var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;
  76270. Equation.call(this,bodyA,bodyB,-maxForce, maxForce);
  76271. this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);
  76272. this.axisB = options.axisB ? options.axisB.clone() : new Vec3(0, 1, 0);
  76273. /**
  76274. * The cone angle to keep
  76275. * @property {number} angle
  76276. */
  76277. this.angle = typeof(options.angle) !== 'undefined' ? options.angle : 0;
  76278. }
  76279. ConeEquation.prototype = new Equation();
  76280. ConeEquation.prototype.constructor = ConeEquation;
  76281. var tmpVec1 = new Vec3();
  76282. var tmpVec2 = new Vec3();
  76283. ConeEquation.prototype.computeB = function(h){
  76284. var a = this.a,
  76285. b = this.b,
  76286. ni = this.axisA,
  76287. nj = this.axisB,
  76288. nixnj = tmpVec1,
  76289. njxni = tmpVec2,
  76290. GA = this.jacobianElementA,
  76291. GB = this.jacobianElementB;
  76292. // Caluclate cross products
  76293. ni.cross(nj, nixnj);
  76294. nj.cross(ni, njxni);
  76295. // The angle between two vector is:
  76296. // cos(theta) = a * b / (length(a) * length(b) = { len(a) = len(b) = 1 } = a * b
  76297. // g = a * b
  76298. // gdot = (b x a) * wi + (a x b) * wj
  76299. // G = [0 bxa 0 axb]
  76300. // W = [vi wi vj wj]
  76301. GA.rotational.copy(njxni);
  76302. GB.rotational.copy(nixnj);
  76303. var g = Math.cos(this.angle) - ni.dot(nj),
  76304. GW = this.computeGW(),
  76305. GiMf = this.computeGiMf();
  76306. var B = - g * a - GW * b - h * GiMf;
  76307. return B;
  76308. };
  76309. },{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],19:[function(_dereq_,module,exports){
  76310. module.exports = ContactEquation;
  76311. var Equation = _dereq_('./Equation');
  76312. var Vec3 = _dereq_('../math/Vec3');
  76313. var Mat3 = _dereq_('../math/Mat3');
  76314. /**
  76315. * Contact/non-penetration constraint equation
  76316. * @class ContactEquation
  76317. * @constructor
  76318. * @author schteppe
  76319. * @param {Body} bodyA
  76320. * @param {Body} bodyB
  76321. * @extends Equation
  76322. */
  76323. function ContactEquation(bodyA, bodyB, maxForce){
  76324. maxForce = typeof(maxForce) !== 'undefined' ? maxForce : 1e6;
  76325. Equation.call(this, bodyA, bodyB, 0, maxForce);
  76326. /**
  76327. * @property restitution
  76328. * @type {Number}
  76329. */
  76330. this.restitution = 0.0; // "bounciness": u1 = -e*u0
  76331. /**
  76332. * World-oriented vector that goes from the center of bi to the contact point.
  76333. * @property {Vec3} ri
  76334. */
  76335. this.ri = new Vec3();
  76336. /**
  76337. * World-oriented vector that starts in body j position and goes to the contact point.
  76338. * @property {Vec3} rj
  76339. */
  76340. this.rj = new Vec3();
  76341. /**
  76342. * Contact normal, pointing out of body i.
  76343. * @property {Vec3} ni
  76344. */
  76345. this.ni = new Vec3();
  76346. }
  76347. ContactEquation.prototype = new Equation();
  76348. ContactEquation.prototype.constructor = ContactEquation;
  76349. var ContactEquation_computeB_temp1 = new Vec3(); // Temp vectors
  76350. var ContactEquation_computeB_temp2 = new Vec3();
  76351. var ContactEquation_computeB_temp3 = new Vec3();
  76352. ContactEquation.prototype.computeB = function(h){
  76353. var a = this.a,
  76354. b = this.b,
  76355. bi = this.bi,
  76356. bj = this.bj,
  76357. ri = this.ri,
  76358. rj = this.rj,
  76359. rixn = ContactEquation_computeB_temp1,
  76360. rjxn = ContactEquation_computeB_temp2,
  76361. vi = bi.velocity,
  76362. wi = bi.angularVelocity,
  76363. fi = bi.force,
  76364. taui = bi.torque,
  76365. vj = bj.velocity,
  76366. wj = bj.angularVelocity,
  76367. fj = bj.force,
  76368. tauj = bj.torque,
  76369. penetrationVec = ContactEquation_computeB_temp3,
  76370. GA = this.jacobianElementA,
  76371. GB = this.jacobianElementB,
  76372. n = this.ni;
  76373. // Caluclate cross products
  76374. ri.cross(n,rixn);
  76375. rj.cross(n,rjxn);
  76376. // g = xj+rj -(xi+ri)
  76377. // G = [ -ni -rixn ni rjxn ]
  76378. n.negate(GA.spatial);
  76379. rixn.negate(GA.rotational);
  76380. GB.spatial.copy(n);
  76381. GB.rotational.copy(rjxn);
  76382. // Calculate the penetration vector
  76383. penetrationVec.copy(bj.position);
  76384. penetrationVec.vadd(rj,penetrationVec);
  76385. penetrationVec.vsub(bi.position,penetrationVec);
  76386. penetrationVec.vsub(ri,penetrationVec);
  76387. var g = n.dot(penetrationVec);
  76388. // Compute iteration
  76389. var ePlusOne = this.restitution + 1;
  76390. var GW = ePlusOne * vj.dot(n) - ePlusOne * vi.dot(n) + wj.dot(rjxn) - wi.dot(rixn);
  76391. var GiMf = this.computeGiMf();
  76392. var B = - g * a - GW * b - h*GiMf;
  76393. return B;
  76394. };
  76395. var ContactEquation_getImpactVelocityAlongNormal_vi = new Vec3();
  76396. var ContactEquation_getImpactVelocityAlongNormal_vj = new Vec3();
  76397. var ContactEquation_getImpactVelocityAlongNormal_xi = new Vec3();
  76398. var ContactEquation_getImpactVelocityAlongNormal_xj = new Vec3();
  76399. var ContactEquation_getImpactVelocityAlongNormal_relVel = new Vec3();
  76400. /**
  76401. * Get the current relative velocity in the contact point.
  76402. * @method getImpactVelocityAlongNormal
  76403. * @return {number}
  76404. */
  76405. ContactEquation.prototype.getImpactVelocityAlongNormal = function(){
  76406. var vi = ContactEquation_getImpactVelocityAlongNormal_vi;
  76407. var vj = ContactEquation_getImpactVelocityAlongNormal_vj;
  76408. var xi = ContactEquation_getImpactVelocityAlongNormal_xi;
  76409. var xj = ContactEquation_getImpactVelocityAlongNormal_xj;
  76410. var relVel = ContactEquation_getImpactVelocityAlongNormal_relVel;
  76411. this.bi.position.vadd(this.ri, xi);
  76412. this.bj.position.vadd(this.rj, xj);
  76413. this.bi.getVelocityAtWorldPoint(xi, vi);
  76414. this.bj.getVelocityAtWorldPoint(xj, vj);
  76415. vi.vsub(vj, relVel);
  76416. return this.ni.dot(relVel);
  76417. };
  76418. },{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],20:[function(_dereq_,module,exports){
  76419. module.exports = Equation;
  76420. var JacobianElement = _dereq_('../math/JacobianElement'),
  76421. Vec3 = _dereq_('../math/Vec3');
  76422. /**
  76423. * Equation base class
  76424. * @class Equation
  76425. * @constructor
  76426. * @author schteppe
  76427. * @param {Body} bi
  76428. * @param {Body} bj
  76429. * @param {Number} minForce Minimum (read: negative max) force to be applied by the constraint.
  76430. * @param {Number} maxForce Maximum (read: positive max) force to be applied by the constraint.
  76431. */
  76432. function Equation(bi,bj,minForce,maxForce){
  76433. this.id = Equation.id++;
  76434. /**
  76435. * @property {number} minForce
  76436. */
  76437. this.minForce = typeof(minForce)==="undefined" ? -1e6 : minForce;
  76438. /**
  76439. * @property {number} maxForce
  76440. */
  76441. this.maxForce = typeof(maxForce)==="undefined" ? 1e6 : maxForce;
  76442. /**
  76443. * @property bi
  76444. * @type {Body}
  76445. */
  76446. this.bi = bi;
  76447. /**
  76448. * @property bj
  76449. * @type {Body}
  76450. */
  76451. this.bj = bj;
  76452. /**
  76453. * SPOOK parameter
  76454. * @property {number} a
  76455. */
  76456. this.a = 0.0;
  76457. /**
  76458. * SPOOK parameter
  76459. * @property {number} b
  76460. */
  76461. this.b = 0.0;
  76462. /**
  76463. * SPOOK parameter
  76464. * @property {number} eps
  76465. */
  76466. this.eps = 0.0;
  76467. /**
  76468. * @property {JacobianElement} jacobianElementA
  76469. */
  76470. this.jacobianElementA = new JacobianElement();
  76471. /**
  76472. * @property {JacobianElement} jacobianElementB
  76473. */
  76474. this.jacobianElementB = new JacobianElement();
  76475. /**
  76476. * @property {boolean} enabled
  76477. * @default true
  76478. */
  76479. this.enabled = true;
  76480. // Set typical spook params
  76481. this.setSpookParams(1e7,4,1/60);
  76482. }
  76483. Equation.prototype.constructor = Equation;
  76484. Equation.id = 0;
  76485. /**
  76486. * Recalculates a,b,eps.
  76487. * @method setSpookParams
  76488. */
  76489. Equation.prototype.setSpookParams = function(stiffness,relaxation,timeStep){
  76490. var d = relaxation,
  76491. k = stiffness,
  76492. h = timeStep;
  76493. this.a = 4.0 / (h * (1 + 4 * d));
  76494. this.b = (4.0 * d) / (1 + 4 * d);
  76495. this.eps = 4.0 / (h * h * k * (1 + 4 * d));
  76496. };
  76497. /**
  76498. * Computes the RHS of the SPOOK equation
  76499. * @method computeB
  76500. * @return {Number}
  76501. */
  76502. Equation.prototype.computeB = function(a,b,h){
  76503. var GW = this.computeGW(),
  76504. Gq = this.computeGq(),
  76505. GiMf = this.computeGiMf();
  76506. return - Gq * a - GW * b - GiMf*h;
  76507. };
  76508. /**
  76509. * Computes G*q, where q are the generalized body coordinates
  76510. * @method computeGq
  76511. * @return {Number}
  76512. */
  76513. Equation.prototype.computeGq = function(){
  76514. var GA = this.jacobianElementA,
  76515. GB = this.jacobianElementB,
  76516. bi = this.bi,
  76517. bj = this.bj,
  76518. xi = bi.position,
  76519. xj = bj.position;
  76520. return GA.spatial.dot(xi) + GB.spatial.dot(xj);
  76521. };
  76522. var zero = new Vec3();
  76523. /**
  76524. * Computes G*W, where W are the body velocities
  76525. * @method computeGW
  76526. * @return {Number}
  76527. */
  76528. Equation.prototype.computeGW = function(){
  76529. var GA = this.jacobianElementA,
  76530. GB = this.jacobianElementB,
  76531. bi = this.bi,
  76532. bj = this.bj,
  76533. vi = bi.velocity,
  76534. vj = bj.velocity,
  76535. wi = bi.angularVelocity || zero,
  76536. wj = bj.angularVelocity || zero;
  76537. return GA.multiplyVectors(vi,wi) + GB.multiplyVectors(vj,wj);
  76538. };
  76539. /**
  76540. * Computes G*Wlambda, where W are the body velocities
  76541. * @method computeGWlambda
  76542. * @return {Number}
  76543. */
  76544. Equation.prototype.computeGWlambda = function(){
  76545. var GA = this.jacobianElementA,
  76546. GB = this.jacobianElementB,
  76547. bi = this.bi,
  76548. bj = this.bj,
  76549. vi = bi.vlambda,
  76550. vj = bj.vlambda,
  76551. wi = bi.wlambda || zero,
  76552. wj = bj.wlambda || zero;
  76553. return GA.multiplyVectors(vi,wi) + GB.multiplyVectors(vj,wj);
  76554. };
  76555. /**
  76556. * 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.
  76557. * @method computeGiMf
  76558. * @return {Number}
  76559. */
  76560. var iMfi = new Vec3(),
  76561. iMfj = new Vec3(),
  76562. invIi_vmult_taui = new Vec3(),
  76563. invIj_vmult_tauj = new Vec3();
  76564. Equation.prototype.computeGiMf = function(){
  76565. var GA = this.jacobianElementA,
  76566. GB = this.jacobianElementB,
  76567. bi = this.bi,
  76568. bj = this.bj,
  76569. fi = bi.force,
  76570. ti = bi.torque,
  76571. fj = bj.force,
  76572. tj = bj.torque,
  76573. invMassi = bi.invMassSolve,
  76574. invMassj = bj.invMassSolve;
  76575. if(bi.invInertiaWorldSolve){ bi.invInertiaWorldSolve.vmult(ti,invIi_vmult_taui); }
  76576. else { invIi_vmult_taui.set(0,0,0); }
  76577. if(bj.invInertiaWorldSolve){ bj.invInertiaWorldSolve.vmult(tj,invIj_vmult_tauj); }
  76578. else { invIj_vmult_tauj.set(0,0,0); }
  76579. fi.mult(invMassi,iMfi);
  76580. fj.mult(invMassj,iMfj);
  76581. return GA.multiplyVectors(iMfi,invIi_vmult_taui) + GB.multiplyVectors(iMfj,invIj_vmult_tauj);
  76582. };
  76583. /**
  76584. * Computes G*inv(M)*G'
  76585. * @method computeGiMGt
  76586. * @return {Number}
  76587. */
  76588. var tmp = new Vec3();
  76589. Equation.prototype.computeGiMGt = function(){
  76590. var GA = this.jacobianElementA,
  76591. GB = this.jacobianElementB,
  76592. bi = this.bi,
  76593. bj = this.bj,
  76594. invMassi = bi.invMassSolve,
  76595. invMassj = bj.invMassSolve,
  76596. invIi = bi.invInertiaWorldSolve,
  76597. invIj = bj.invInertiaWorldSolve,
  76598. result = invMassi + invMassj;
  76599. if(invIi){
  76600. invIi.vmult(GA.rotational,tmp);
  76601. result += tmp.dot(GA.rotational);
  76602. }
  76603. if(invIj){
  76604. invIj.vmult(GB.rotational,tmp);
  76605. result += tmp.dot(GB.rotational);
  76606. }
  76607. return result;
  76608. };
  76609. var addToWlambda_temp = new Vec3(),
  76610. addToWlambda_Gi = new Vec3(),
  76611. addToWlambda_Gj = new Vec3(),
  76612. addToWlambda_ri = new Vec3(),
  76613. addToWlambda_rj = new Vec3(),
  76614. addToWlambda_Mdiag = new Vec3();
  76615. /**
  76616. * Add constraint velocity to the bodies.
  76617. * @method addToWlambda
  76618. * @param {Number} deltalambda
  76619. */
  76620. Equation.prototype.addToWlambda = function(deltalambda){
  76621. var GA = this.jacobianElementA,
  76622. GB = this.jacobianElementB,
  76623. bi = this.bi,
  76624. bj = this.bj,
  76625. temp = addToWlambda_temp;
  76626. // Add to linear velocity
  76627. // v_lambda += inv(M) * delta_lamba * G
  76628. GA.spatial.mult(bi.invMassSolve * deltalambda,temp);
  76629. bi.vlambda.vadd(temp, bi.vlambda);
  76630. GB.spatial.mult(bj.invMassSolve * deltalambda,temp);
  76631. bj.vlambda.vadd(temp, bj.vlambda);
  76632. // Add to angular velocity
  76633. if(bi.invInertiaWorldSolve){
  76634. bi.invInertiaWorldSolve.vmult(GA.rotational,temp);
  76635. temp.mult(deltalambda,temp);
  76636. bi.wlambda.vadd(temp,bi.wlambda);
  76637. }
  76638. if(bj.invInertiaWorldSolve){
  76639. bj.invInertiaWorldSolve.vmult(GB.rotational,temp);
  76640. temp.mult(deltalambda,temp);
  76641. bj.wlambda.vadd(temp,bj.wlambda);
  76642. }
  76643. };
  76644. /**
  76645. * Compute the denominator part of the SPOOK equation: C = G*inv(M)*G' + eps
  76646. * @method computeInvC
  76647. * @param {Number} eps
  76648. * @return {Number}
  76649. */
  76650. Equation.prototype.computeC = function(){
  76651. return this.computeGiMGt() + this.eps;
  76652. };
  76653. },{"../math/JacobianElement":26,"../math/Vec3":30}],21:[function(_dereq_,module,exports){
  76654. module.exports = FrictionEquation;
  76655. var Equation = _dereq_('./Equation');
  76656. var Vec3 = _dereq_('../math/Vec3');
  76657. var Mat3 = _dereq_('../math/Mat3');
  76658. /**
  76659. * Constrains the slipping in a contact along a tangent
  76660. * @class FrictionEquation
  76661. * @constructor
  76662. * @author schteppe
  76663. * @param {Body} bodyA
  76664. * @param {Body} bodyB
  76665. * @param {Number} slipForce should be +-F_friction = +-mu * F_normal = +-mu * m * g
  76666. * @extends Equation
  76667. */
  76668. function FrictionEquation(bodyA, bodyB, slipForce){
  76669. Equation.call(this,bodyA, bodyB, -slipForce, slipForce);
  76670. this.ri = new Vec3();
  76671. this.rj = new Vec3();
  76672. this.t = new Vec3(); // tangent
  76673. }
  76674. FrictionEquation.prototype = new Equation();
  76675. FrictionEquation.prototype.constructor = FrictionEquation;
  76676. var FrictionEquation_computeB_temp1 = new Vec3();
  76677. var FrictionEquation_computeB_temp2 = new Vec3();
  76678. FrictionEquation.prototype.computeB = function(h){
  76679. var a = this.a,
  76680. b = this.b,
  76681. bi = this.bi,
  76682. bj = this.bj,
  76683. ri = this.ri,
  76684. rj = this.rj,
  76685. rixt = FrictionEquation_computeB_temp1,
  76686. rjxt = FrictionEquation_computeB_temp2,
  76687. t = this.t;
  76688. // Caluclate cross products
  76689. ri.cross(t,rixt);
  76690. rj.cross(t,rjxt);
  76691. // G = [-t -rixt t rjxt]
  76692. // And remember, this is a pure velocity constraint, g is always zero!
  76693. var GA = this.jacobianElementA,
  76694. GB = this.jacobianElementB;
  76695. t.negate(GA.spatial);
  76696. rixt.negate(GA.rotational);
  76697. GB.spatial.copy(t);
  76698. GB.rotational.copy(rjxt);
  76699. var GW = this.computeGW();
  76700. var GiMf = this.computeGiMf();
  76701. var B = - GW * b - h * GiMf;
  76702. return B;
  76703. };
  76704. },{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],22:[function(_dereq_,module,exports){
  76705. module.exports = RotationalEquation;
  76706. var Vec3 = _dereq_('../math/Vec3');
  76707. var Mat3 = _dereq_('../math/Mat3');
  76708. var Equation = _dereq_('./Equation');
  76709. /**
  76710. * Rotational constraint. Works to keep the local vectors orthogonal to each other in world space.
  76711. * @class RotationalEquation
  76712. * @constructor
  76713. * @author schteppe
  76714. * @param {Body} bodyA
  76715. * @param {Body} bodyB
  76716. * @param {Vec3} [options.axisA]
  76717. * @param {Vec3} [options.axisB]
  76718. * @param {number} [options.maxForce]
  76719. * @extends Equation
  76720. */
  76721. function RotationalEquation(bodyA, bodyB, options){
  76722. options = options || {};
  76723. var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;
  76724. Equation.call(this,bodyA,bodyB,-maxForce, maxForce);
  76725. this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);
  76726. this.axisB = options.axisB ? options.axisB.clone() : new Vec3(0, 1, 0);
  76727. this.maxAngle = Math.PI / 2;
  76728. }
  76729. RotationalEquation.prototype = new Equation();
  76730. RotationalEquation.prototype.constructor = RotationalEquation;
  76731. var tmpVec1 = new Vec3();
  76732. var tmpVec2 = new Vec3();
  76733. RotationalEquation.prototype.computeB = function(h){
  76734. var a = this.a,
  76735. b = this.b,
  76736. ni = this.axisA,
  76737. nj = this.axisB,
  76738. nixnj = tmpVec1,
  76739. njxni = tmpVec2,
  76740. GA = this.jacobianElementA,
  76741. GB = this.jacobianElementB;
  76742. // Caluclate cross products
  76743. ni.cross(nj, nixnj);
  76744. nj.cross(ni, njxni);
  76745. // g = ni * nj
  76746. // gdot = (nj x ni) * wi + (ni x nj) * wj
  76747. // G = [0 njxni 0 nixnj]
  76748. // W = [vi wi vj wj]
  76749. GA.rotational.copy(njxni);
  76750. GB.rotational.copy(nixnj);
  76751. var g = Math.cos(this.maxAngle) - ni.dot(nj),
  76752. GW = this.computeGW(),
  76753. GiMf = this.computeGiMf();
  76754. var B = - g * a - GW * b - h * GiMf;
  76755. return B;
  76756. };
  76757. },{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],23:[function(_dereq_,module,exports){
  76758. module.exports = RotationalMotorEquation;
  76759. var Vec3 = _dereq_('../math/Vec3');
  76760. var Mat3 = _dereq_('../math/Mat3');
  76761. var Equation = _dereq_('./Equation');
  76762. /**
  76763. * Rotational motor constraint. Tries to keep the relative angular velocity of the bodies to a given value.
  76764. * @class RotationalMotorEquation
  76765. * @constructor
  76766. * @author schteppe
  76767. * @param {Body} bodyA
  76768. * @param {Body} bodyB
  76769. * @param {Number} maxForce
  76770. * @extends Equation
  76771. */
  76772. function RotationalMotorEquation(bodyA, bodyB, maxForce){
  76773. maxForce = typeof(maxForce)!=='undefined' ? maxForce : 1e6;
  76774. Equation.call(this,bodyA,bodyB,-maxForce,maxForce);
  76775. /**
  76776. * World oriented rotational axis
  76777. * @property {Vec3} axisA
  76778. */
  76779. this.axisA = new Vec3();
  76780. /**
  76781. * World oriented rotational axis
  76782. * @property {Vec3} axisB
  76783. */
  76784. this.axisB = new Vec3(); // World oriented rotational axis
  76785. /**
  76786. * Motor velocity
  76787. * @property {Number} targetVelocity
  76788. */
  76789. this.targetVelocity = 0;
  76790. }
  76791. RotationalMotorEquation.prototype = new Equation();
  76792. RotationalMotorEquation.prototype.constructor = RotationalMotorEquation;
  76793. RotationalMotorEquation.prototype.computeB = function(h){
  76794. var a = this.a,
  76795. b = this.b,
  76796. bi = this.bi,
  76797. bj = this.bj,
  76798. axisA = this.axisA,
  76799. axisB = this.axisB,
  76800. GA = this.jacobianElementA,
  76801. GB = this.jacobianElementB;
  76802. // g = 0
  76803. // gdot = axisA * wi - axisB * wj
  76804. // gdot = G * W = G * [vi wi vj wj]
  76805. // =>
  76806. // G = [0 axisA 0 -axisB]
  76807. GA.rotational.copy(axisA);
  76808. axisB.negate(GB.rotational);
  76809. var GW = this.computeGW() - this.targetVelocity,
  76810. GiMf = this.computeGiMf();
  76811. var B = - GW * b - h * GiMf;
  76812. return B;
  76813. };
  76814. },{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],24:[function(_dereq_,module,exports){
  76815. var Utils = _dereq_('../utils/Utils');
  76816. module.exports = ContactMaterial;
  76817. /**
  76818. * Defines what happens when two materials meet.
  76819. * @class ContactMaterial
  76820. * @constructor
  76821. * @param {Material} m1
  76822. * @param {Material} m2
  76823. * @param {object} [options]
  76824. * @param {Number} [options.friction=0.3]
  76825. * @param {Number} [options.restitution=0.3]
  76826. * @param {number} [options.contactEquationStiffness=1e7]
  76827. * @param {number} [options.contactEquationRelaxation=3]
  76828. * @param {number} [options.frictionEquationStiffness=1e7]
  76829. * @param {Number} [options.frictionEquationRelaxation=3]
  76830. */
  76831. function ContactMaterial(m1, m2, options){
  76832. options = Utils.defaults(options, {
  76833. friction: 0.3,
  76834. restitution: 0.3,
  76835. contactEquationStiffness: 1e7,
  76836. contactEquationRelaxation: 3,
  76837. frictionEquationStiffness: 1e7,
  76838. frictionEquationRelaxation: 3
  76839. });
  76840. /**
  76841. * Identifier of this material
  76842. * @property {Number} id
  76843. */
  76844. this.id = ContactMaterial.idCounter++;
  76845. /**
  76846. * Participating materials
  76847. * @property {Array} materials
  76848. * @todo Should be .materialA and .materialB instead
  76849. */
  76850. this.materials = [m1, m2];
  76851. /**
  76852. * Friction coefficient
  76853. * @property {Number} friction
  76854. */
  76855. this.friction = options.friction;
  76856. /**
  76857. * Restitution coefficient
  76858. * @property {Number} restitution
  76859. */
  76860. this.restitution = options.restitution;
  76861. /**
  76862. * Stiffness of the produced contact equations
  76863. * @property {Number} contactEquationStiffness
  76864. */
  76865. this.contactEquationStiffness = options.contactEquationStiffness;
  76866. /**
  76867. * Relaxation time of the produced contact equations
  76868. * @property {Number} contactEquationRelaxation
  76869. */
  76870. this.contactEquationRelaxation = options.contactEquationRelaxation;
  76871. /**
  76872. * Stiffness of the produced friction equations
  76873. * @property {Number} frictionEquationStiffness
  76874. */
  76875. this.frictionEquationStiffness = options.frictionEquationStiffness;
  76876. /**
  76877. * Relaxation time of the produced friction equations
  76878. * @property {Number} frictionEquationRelaxation
  76879. */
  76880. this.frictionEquationRelaxation = options.frictionEquationRelaxation;
  76881. }
  76882. ContactMaterial.idCounter = 0;
  76883. },{"../utils/Utils":53}],25:[function(_dereq_,module,exports){
  76884. module.exports = Material;
  76885. /**
  76886. * Defines a physics material.
  76887. * @class Material
  76888. * @constructor
  76889. * @param {object} [options]
  76890. * @author schteppe
  76891. */
  76892. function Material(options){
  76893. var name = '';
  76894. options = options || {};
  76895. // Backwards compatibility fix
  76896. if(typeof(options) === 'string'){
  76897. name = options;
  76898. options = {};
  76899. } else if(typeof(options) === 'object') {
  76900. name = '';
  76901. }
  76902. /**
  76903. * @property name
  76904. * @type {String}
  76905. */
  76906. this.name = name;
  76907. /**
  76908. * material id.
  76909. * @property id
  76910. * @type {number}
  76911. */
  76912. this.id = Material.idCounter++;
  76913. /**
  76914. * 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.
  76915. * @property {number} friction
  76916. */
  76917. this.friction = typeof(options.friction) !== 'undefined' ? options.friction : -1;
  76918. /**
  76919. * 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.
  76920. * @property {number} restitution
  76921. */
  76922. this.restitution = typeof(options.restitution) !== 'undefined' ? options.restitution : -1;
  76923. }
  76924. Material.idCounter = 0;
  76925. },{}],26:[function(_dereq_,module,exports){
  76926. module.exports = JacobianElement;
  76927. var Vec3 = _dereq_('./Vec3');
  76928. /**
  76929. * An element containing 6 entries, 3 spatial and 3 rotational degrees of freedom.
  76930. * @class JacobianElement
  76931. * @constructor
  76932. */
  76933. function JacobianElement(){
  76934. /**
  76935. * @property {Vec3} spatial
  76936. */
  76937. this.spatial = new Vec3();
  76938. /**
  76939. * @property {Vec3} rotational
  76940. */
  76941. this.rotational = new Vec3();
  76942. }
  76943. /**
  76944. * Multiply with other JacobianElement
  76945. * @method multiplyElement
  76946. * @param {JacobianElement} element
  76947. * @return {Number}
  76948. */
  76949. JacobianElement.prototype.multiplyElement = function(element){
  76950. return element.spatial.dot(this.spatial) + element.rotational.dot(this.rotational);
  76951. };
  76952. /**
  76953. * Multiply with two vectors
  76954. * @method multiplyVectors
  76955. * @param {Vec3} spatial
  76956. * @param {Vec3} rotational
  76957. * @return {Number}
  76958. */
  76959. JacobianElement.prototype.multiplyVectors = function(spatial,rotational){
  76960. return spatial.dot(this.spatial) + rotational.dot(this.rotational);
  76961. };
  76962. },{"./Vec3":30}],27:[function(_dereq_,module,exports){
  76963. module.exports = Mat3;
  76964. var Vec3 = _dereq_('./Vec3');
  76965. /**
  76966. * A 3x3 matrix.
  76967. * @class Mat3
  76968. * @constructor
  76969. * @param array elements Array of nine elements. Optional.
  76970. * @author schteppe / http://github.com/schteppe
  76971. */
  76972. function Mat3(elements){
  76973. /**
  76974. * A vector of length 9, containing all matrix elements
  76975. * @property {Array} elements
  76976. */
  76977. if(elements){
  76978. this.elements = elements;
  76979. } else {
  76980. this.elements = [0,0,0,0,0,0,0,0,0];
  76981. }
  76982. }
  76983. /**
  76984. * Sets the matrix to identity
  76985. * @method identity
  76986. * @todo Should perhaps be renamed to setIdentity() to be more clear.
  76987. * @todo Create another function that immediately creates an identity matrix eg. eye()
  76988. */
  76989. Mat3.prototype.identity = function(){
  76990. var e = this.elements;
  76991. e[0] = 1;
  76992. e[1] = 0;
  76993. e[2] = 0;
  76994. e[3] = 0;
  76995. e[4] = 1;
  76996. e[5] = 0;
  76997. e[6] = 0;
  76998. e[7] = 0;
  76999. e[8] = 1;
  77000. };
  77001. /**
  77002. * Set all elements to zero
  77003. * @method setZero
  77004. */
  77005. Mat3.prototype.setZero = function(){
  77006. var e = this.elements;
  77007. e[0] = 0;
  77008. e[1] = 0;
  77009. e[2] = 0;
  77010. e[3] = 0;
  77011. e[4] = 0;
  77012. e[5] = 0;
  77013. e[6] = 0;
  77014. e[7] = 0;
  77015. e[8] = 0;
  77016. };
  77017. /**
  77018. * Sets the matrix diagonal elements from a Vec3
  77019. * @method setTrace
  77020. * @param {Vec3} vec3
  77021. */
  77022. Mat3.prototype.setTrace = function(vec3){
  77023. var e = this.elements;
  77024. e[0] = vec3.x;
  77025. e[4] = vec3.y;
  77026. e[8] = vec3.z;
  77027. };
  77028. /**
  77029. * Gets the matrix diagonal elements
  77030. * @method getTrace
  77031. * @return {Vec3}
  77032. */
  77033. Mat3.prototype.getTrace = function(target){
  77034. var target = target || new Vec3();
  77035. var e = this.elements;
  77036. target.x = e[0];
  77037. target.y = e[4];
  77038. target.z = e[8];
  77039. };
  77040. /**
  77041. * Matrix-Vector multiplication
  77042. * @method vmult
  77043. * @param {Vec3} v The vector to multiply with
  77044. * @param {Vec3} target Optional, target to save the result in.
  77045. */
  77046. Mat3.prototype.vmult = function(v,target){
  77047. target = target || new Vec3();
  77048. var e = this.elements,
  77049. x = v.x,
  77050. y = v.y,
  77051. z = v.z;
  77052. target.x = e[0]*x + e[1]*y + e[2]*z;
  77053. target.y = e[3]*x + e[4]*y + e[5]*z;
  77054. target.z = e[6]*x + e[7]*y + e[8]*z;
  77055. return target;
  77056. };
  77057. /**
  77058. * Matrix-scalar multiplication
  77059. * @method smult
  77060. * @param {Number} s
  77061. */
  77062. Mat3.prototype.smult = function(s){
  77063. for(var i=0; i<this.elements.length; i++){
  77064. this.elements[i] *= s;
  77065. }
  77066. };
  77067. /**
  77068. * Matrix multiplication
  77069. * @method mmult
  77070. * @param {Mat3} m Matrix to multiply with from left side.
  77071. * @return {Mat3} The result.
  77072. */
  77073. Mat3.prototype.mmult = function(m,target){
  77074. var r = target || new Mat3();
  77075. for(var i=0; i<3; i++){
  77076. for(var j=0; j<3; j++){
  77077. var sum = 0.0;
  77078. for(var k=0; k<3; k++){
  77079. sum += m.elements[i+k*3] * this.elements[k+j*3];
  77080. }
  77081. r.elements[i+j*3] = sum;
  77082. }
  77083. }
  77084. return r;
  77085. };
  77086. /**
  77087. * Scale each column of the matrix
  77088. * @method scale
  77089. * @param {Vec3} v
  77090. * @return {Mat3} The result.
  77091. */
  77092. Mat3.prototype.scale = function(v,target){
  77093. target = target || new Mat3();
  77094. var e = this.elements,
  77095. t = target.elements;
  77096. for(var i=0; i!==3; i++){
  77097. t[3*i + 0] = v.x * e[3*i + 0];
  77098. t[3*i + 1] = v.y * e[3*i + 1];
  77099. t[3*i + 2] = v.z * e[3*i + 2];
  77100. }
  77101. return target;
  77102. };
  77103. /**
  77104. * Solve Ax=b
  77105. * @method solve
  77106. * @param {Vec3} b The right hand side
  77107. * @param {Vec3} target Optional. Target vector to save in.
  77108. * @return {Vec3} The solution x
  77109. * @todo should reuse arrays
  77110. */
  77111. Mat3.prototype.solve = function(b,target){
  77112. target = target || new Vec3();
  77113. // Construct equations
  77114. var nr = 3; // num rows
  77115. var nc = 4; // num cols
  77116. var eqns = [];
  77117. for(var i=0; i<nr*nc; i++){
  77118. eqns.push(0);
  77119. }
  77120. var i,j;
  77121. for(i=0; i<3; i++){
  77122. for(j=0; j<3; j++){
  77123. eqns[i+nc*j] = this.elements[i+3*j];
  77124. }
  77125. }
  77126. eqns[3+4*0] = b.x;
  77127. eqns[3+4*1] = b.y;
  77128. eqns[3+4*2] = b.z;
  77129. // Compute right upper triangular version of the matrix - Gauss elimination
  77130. var n = 3, k = n, np;
  77131. var kp = 4; // num rows
  77132. var p, els;
  77133. do {
  77134. i = k - n;
  77135. if (eqns[i+nc*i] === 0) {
  77136. // the pivot is null, swap lines
  77137. for (j = i + 1; j < k; j++) {
  77138. if (eqns[i+nc*j] !== 0) {
  77139. np = kp;
  77140. do { // do ligne( i ) = ligne( i ) + ligne( k )
  77141. p = kp - np;
  77142. eqns[p+nc*i] += eqns[p+nc*j];
  77143. } while (--np);
  77144. break;
  77145. }
  77146. }
  77147. }
  77148. if (eqns[i+nc*i] !== 0) {
  77149. for (j = i + 1; j < k; j++) {
  77150. var multiplier = eqns[i+nc*j] / eqns[i+nc*i];
  77151. np = kp;
  77152. do { // do ligne( k ) = ligne( k ) - multiplier * ligne( i )
  77153. p = kp - np;
  77154. eqns[p+nc*j] = p <= i ? 0 : eqns[p+nc*j] - eqns[p+nc*i] * multiplier ;
  77155. } while (--np);
  77156. }
  77157. }
  77158. } while (--n);
  77159. // Get the solution
  77160. target.z = eqns[2*nc+3] / eqns[2*nc+2];
  77161. target.y = (eqns[1*nc+3] - eqns[1*nc+2]*target.z) / eqns[1*nc+1];
  77162. target.x = (eqns[0*nc+3] - eqns[0*nc+2]*target.z - eqns[0*nc+1]*target.y) / eqns[0*nc+0];
  77163. if(isNaN(target.x) || isNaN(target.y) || isNaN(target.z) || target.x===Infinity || target.y===Infinity || target.z===Infinity){
  77164. throw "Could not solve equation! Got x=["+target.toString()+"], b=["+b.toString()+"], A=["+this.toString()+"]";
  77165. }
  77166. return target;
  77167. };
  77168. /**
  77169. * Get an element in the matrix by index. Index starts at 0, not 1!!!
  77170. * @method e
  77171. * @param {Number} row
  77172. * @param {Number} column
  77173. * @param {Number} value Optional. If provided, the matrix element will be set to this value.
  77174. * @return {Number}
  77175. */
  77176. Mat3.prototype.e = function( row , column ,value){
  77177. if(value===undefined){
  77178. return this.elements[column+3*row];
  77179. } else {
  77180. // Set value
  77181. this.elements[column+3*row] = value;
  77182. }
  77183. };
  77184. /**
  77185. * Copy another matrix into this matrix object.
  77186. * @method copy
  77187. * @param {Mat3} source
  77188. * @return {Mat3} this
  77189. */
  77190. Mat3.prototype.copy = function(source){
  77191. for(var i=0; i < source.elements.length; i++){
  77192. this.elements[i] = source.elements[i];
  77193. }
  77194. return this;
  77195. };
  77196. /**
  77197. * Returns a string representation of the matrix.
  77198. * @method toString
  77199. * @return string
  77200. */
  77201. Mat3.prototype.toString = function(){
  77202. var r = "";
  77203. var sep = ",";
  77204. for(var i=0; i<9; i++){
  77205. r += this.elements[i] + sep;
  77206. }
  77207. return r;
  77208. };
  77209. /**
  77210. * reverse the matrix
  77211. * @method reverse
  77212. * @param {Mat3} target Optional. Target matrix to save in.
  77213. * @return {Mat3} The solution x
  77214. */
  77215. Mat3.prototype.reverse = function(target){
  77216. target = target || new Mat3();
  77217. // Construct equations
  77218. var nr = 3; // num rows
  77219. var nc = 6; // num cols
  77220. var eqns = [];
  77221. for(var i=0; i<nr*nc; i++){
  77222. eqns.push(0);
  77223. }
  77224. var i,j;
  77225. for(i=0; i<3; i++){
  77226. for(j=0; j<3; j++){
  77227. eqns[i+nc*j] = this.elements[i+3*j];
  77228. }
  77229. }
  77230. eqns[3+6*0] = 1;
  77231. eqns[3+6*1] = 0;
  77232. eqns[3+6*2] = 0;
  77233. eqns[4+6*0] = 0;
  77234. eqns[4+6*1] = 1;
  77235. eqns[4+6*2] = 0;
  77236. eqns[5+6*0] = 0;
  77237. eqns[5+6*1] = 0;
  77238. eqns[5+6*2] = 1;
  77239. // Compute right upper triangular version of the matrix - Gauss elimination
  77240. var n = 3, k = n, np;
  77241. var kp = nc; // num rows
  77242. var p;
  77243. do {
  77244. i = k - n;
  77245. if (eqns[i+nc*i] === 0) {
  77246. // the pivot is null, swap lines
  77247. for (j = i + 1; j < k; j++) {
  77248. if (eqns[i+nc*j] !== 0) {
  77249. np = kp;
  77250. do { // do line( i ) = line( i ) + line( k )
  77251. p = kp - np;
  77252. eqns[p+nc*i] += eqns[p+nc*j];
  77253. } while (--np);
  77254. break;
  77255. }
  77256. }
  77257. }
  77258. if (eqns[i+nc*i] !== 0) {
  77259. for (j = i + 1; j < k; j++) {
  77260. var multiplier = eqns[i+nc*j] / eqns[i+nc*i];
  77261. np = kp;
  77262. do { // do line( k ) = line( k ) - multiplier * line( i )
  77263. p = kp - np;
  77264. eqns[p+nc*j] = p <= i ? 0 : eqns[p+nc*j] - eqns[p+nc*i] * multiplier ;
  77265. } while (--np);
  77266. }
  77267. }
  77268. } while (--n);
  77269. // eliminate the upper left triangle of the matrix
  77270. i = 2;
  77271. do {
  77272. j = i-1;
  77273. do {
  77274. var multiplier = eqns[i+nc*j] / eqns[i+nc*i];
  77275. np = nc;
  77276. do {
  77277. p = nc - np;
  77278. eqns[p+nc*j] = eqns[p+nc*j] - eqns[p+nc*i] * multiplier ;
  77279. } while (--np);
  77280. } while (j--);
  77281. } while (--i);
  77282. // operations on the diagonal
  77283. i = 2;
  77284. do {
  77285. var multiplier = 1 / eqns[i+nc*i];
  77286. np = nc;
  77287. do {
  77288. p = nc - np;
  77289. eqns[p+nc*i] = eqns[p+nc*i] * multiplier ;
  77290. } while (--np);
  77291. } while (i--);
  77292. i = 2;
  77293. do {
  77294. j = 2;
  77295. do {
  77296. p = eqns[nr+j+nc*i];
  77297. if( isNaN( p ) || p ===Infinity ){
  77298. throw "Could not reverse! A=["+this.toString()+"]";
  77299. }
  77300. target.e( i , j , p );
  77301. } while (j--);
  77302. } while (i--);
  77303. return target;
  77304. };
  77305. /**
  77306. * Set the matrix from a quaterion
  77307. * @method setRotationFromQuaternion
  77308. * @param {Quaternion} q
  77309. */
  77310. Mat3.prototype.setRotationFromQuaternion = function( q ) {
  77311. var x = q.x, y = q.y, z = q.z, w = q.w,
  77312. x2 = x + x, y2 = y + y, z2 = z + z,
  77313. xx = x * x2, xy = x * y2, xz = x * z2,
  77314. yy = y * y2, yz = y * z2, zz = z * z2,
  77315. wx = w * x2, wy = w * y2, wz = w * z2,
  77316. e = this.elements;
  77317. e[3*0 + 0] = 1 - ( yy + zz );
  77318. e[3*0 + 1] = xy - wz;
  77319. e[3*0 + 2] = xz + wy;
  77320. e[3*1 + 0] = xy + wz;
  77321. e[3*1 + 1] = 1 - ( xx + zz );
  77322. e[3*1 + 2] = yz - wx;
  77323. e[3*2 + 0] = xz - wy;
  77324. e[3*2 + 1] = yz + wx;
  77325. e[3*2 + 2] = 1 - ( xx + yy );
  77326. return this;
  77327. };
  77328. /**
  77329. * Transpose the matrix
  77330. * @method transpose
  77331. * @param {Mat3} target Where to store the result.
  77332. * @return {Mat3} The target Mat3, or a new Mat3 if target was omitted.
  77333. */
  77334. Mat3.prototype.transpose = function( target ) {
  77335. target = target || new Mat3();
  77336. var Mt = target.elements,
  77337. M = this.elements;
  77338. for(var i=0; i!==3; i++){
  77339. for(var j=0; j!==3; j++){
  77340. Mt[3*i + j] = M[3*j + i];
  77341. }
  77342. }
  77343. return target;
  77344. };
  77345. },{"./Vec3":30}],28:[function(_dereq_,module,exports){
  77346. module.exports = Quaternion;
  77347. var Vec3 = _dereq_('./Vec3');
  77348. /**
  77349. * 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.
  77350. * @class Quaternion
  77351. * @constructor
  77352. * @param {Number} x Multiplier of the imaginary basis vector i.
  77353. * @param {Number} y Multiplier of the imaginary basis vector j.
  77354. * @param {Number} z Multiplier of the imaginary basis vector k.
  77355. * @param {Number} w Multiplier of the real part.
  77356. * @see http://en.wikipedia.org/wiki/Quaternion
  77357. */
  77358. function Quaternion(x,y,z,w){
  77359. /**
  77360. * @property {Number} x
  77361. */
  77362. this.x = x!==undefined ? x : 0;
  77363. /**
  77364. * @property {Number} y
  77365. */
  77366. this.y = y!==undefined ? y : 0;
  77367. /**
  77368. * @property {Number} z
  77369. */
  77370. this.z = z!==undefined ? z : 0;
  77371. /**
  77372. * The multiplier of the real quaternion basis vector.
  77373. * @property {Number} w
  77374. */
  77375. this.w = w!==undefined ? w : 1;
  77376. }
  77377. /**
  77378. * Set the value of the quaternion.
  77379. * @method set
  77380. * @param {Number} x
  77381. * @param {Number} y
  77382. * @param {Number} z
  77383. * @param {Number} w
  77384. */
  77385. Quaternion.prototype.set = function(x,y,z,w){
  77386. this.x = x;
  77387. this.y = y;
  77388. this.z = z;
  77389. this.w = w;
  77390. };
  77391. /**
  77392. * Convert to a readable format
  77393. * @method toString
  77394. * @return string
  77395. */
  77396. Quaternion.prototype.toString = function(){
  77397. return this.x+","+this.y+","+this.z+","+this.w;
  77398. };
  77399. /**
  77400. * Convert to an Array
  77401. * @method toArray
  77402. * @return Array
  77403. */
  77404. Quaternion.prototype.toArray = function(){
  77405. return [this.x, this.y, this.z, this.w];
  77406. };
  77407. /**
  77408. * Set the quaternion components given an axis and an angle.
  77409. * @method setFromAxisAngle
  77410. * @param {Vec3} axis
  77411. * @param {Number} angle in radians
  77412. */
  77413. Quaternion.prototype.setFromAxisAngle = function(axis,angle){
  77414. var s = Math.sin(angle*0.5);
  77415. this.x = axis.x * s;
  77416. this.y = axis.y * s;
  77417. this.z = axis.z * s;
  77418. this.w = Math.cos(angle*0.5);
  77419. };
  77420. /**
  77421. * Converts the quaternion to axis/angle representation.
  77422. * @method toAxisAngle
  77423. * @param {Vec3} targetAxis Optional. A vector object to reuse for storing the axis.
  77424. * @return Array An array, first elemnt is the axis and the second is the angle in radians.
  77425. */
  77426. Quaternion.prototype.toAxisAngle = function(targetAxis){
  77427. targetAxis = targetAxis || new Vec3();
  77428. this.normalize(); // if w>1 acos and sqrt will produce errors, this cant happen if quaternion is normalised
  77429. var angle = 2 * Math.acos(this.w);
  77430. var s = Math.sqrt(1-this.w*this.w); // assuming quaternion normalised then w is less than 1, so term always positive.
  77431. if (s < 0.001) { // test to avoid divide by zero, s is always positive due to sqrt
  77432. // if s close to zero then direction of axis not important
  77433. targetAxis.x = this.x; // if it is important that axis is normalised then replace with x=1; y=z=0;
  77434. targetAxis.y = this.y;
  77435. targetAxis.z = this.z;
  77436. } else {
  77437. targetAxis.x = this.x / s; // normalise axis
  77438. targetAxis.y = this.y / s;
  77439. targetAxis.z = this.z / s;
  77440. }
  77441. return [targetAxis,angle];
  77442. };
  77443. var sfv_t1 = new Vec3(),
  77444. sfv_t2 = new Vec3();
  77445. /**
  77446. * Set the quaternion value given two vectors. The resulting rotation will be the needed rotation to rotate u to v.
  77447. * @method setFromVectors
  77448. * @param {Vec3} u
  77449. * @param {Vec3} v
  77450. */
  77451. Quaternion.prototype.setFromVectors = function(u,v){
  77452. if(u.isAntiparallelTo(v)){
  77453. var t1 = sfv_t1;
  77454. var t2 = sfv_t2;
  77455. u.tangents(t1,t2);
  77456. this.setFromAxisAngle(t1,Math.PI);
  77457. } else {
  77458. var a = u.cross(v);
  77459. this.x = a.x;
  77460. this.y = a.y;
  77461. this.z = a.z;
  77462. this.w = Math.sqrt(Math.pow(u.norm(),2) * Math.pow(v.norm(),2)) + u.dot(v);
  77463. this.normalize();
  77464. }
  77465. };
  77466. /**
  77467. * Quaternion multiplication
  77468. * @method mult
  77469. * @param {Quaternion} q
  77470. * @param {Quaternion} target Optional.
  77471. * @return {Quaternion}
  77472. */
  77473. var Quaternion_mult_va = new Vec3();
  77474. var Quaternion_mult_vb = new Vec3();
  77475. var Quaternion_mult_vaxvb = new Vec3();
  77476. Quaternion.prototype.mult = function(q,target){
  77477. target = target || new Quaternion();
  77478. var w = this.w,
  77479. va = Quaternion_mult_va,
  77480. vb = Quaternion_mult_vb,
  77481. vaxvb = Quaternion_mult_vaxvb;
  77482. va.set(this.x,this.y,this.z);
  77483. vb.set(q.x,q.y,q.z);
  77484. target.w = w*q.w - va.dot(vb);
  77485. va.cross(vb,vaxvb);
  77486. target.x = w * vb.x + q.w*va.x + vaxvb.x;
  77487. target.y = w * vb.y + q.w*va.y + vaxvb.y;
  77488. target.z = w * vb.z + q.w*va.z + vaxvb.z;
  77489. return target;
  77490. };
  77491. /**
  77492. * Get the inverse quaternion rotation.
  77493. * @method inverse
  77494. * @param {Quaternion} target
  77495. * @return {Quaternion}
  77496. */
  77497. Quaternion.prototype.inverse = function(target){
  77498. var x = this.x, y = this.y, z = this.z, w = this.w;
  77499. target = target || new Quaternion();
  77500. this.conjugate(target);
  77501. var inorm2 = 1/(x*x + y*y + z*z + w*w);
  77502. target.x *= inorm2;
  77503. target.y *= inorm2;
  77504. target.z *= inorm2;
  77505. target.w *= inorm2;
  77506. return target;
  77507. };
  77508. /**
  77509. * Get the quaternion conjugate
  77510. * @method conjugate
  77511. * @param {Quaternion} target
  77512. * @return {Quaternion}
  77513. */
  77514. Quaternion.prototype.conjugate = function(target){
  77515. target = target || new Quaternion();
  77516. target.x = -this.x;
  77517. target.y = -this.y;
  77518. target.z = -this.z;
  77519. target.w = this.w;
  77520. return target;
  77521. };
  77522. /**
  77523. * Normalize the quaternion. Note that this changes the values of the quaternion.
  77524. * @method normalize
  77525. */
  77526. Quaternion.prototype.normalize = function(){
  77527. var l = Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w);
  77528. if ( l === 0 ) {
  77529. this.x = 0;
  77530. this.y = 0;
  77531. this.z = 0;
  77532. this.w = 0;
  77533. } else {
  77534. l = 1 / l;
  77535. this.x *= l;
  77536. this.y *= l;
  77537. this.z *= l;
  77538. this.w *= l;
  77539. }
  77540. };
  77541. /**
  77542. * Approximation of quaternion normalization. Works best when quat is already almost-normalized.
  77543. * @method normalizeFast
  77544. * @see http://jsperf.com/fast-quaternion-normalization
  77545. * @author unphased, https://github.com/unphased
  77546. */
  77547. Quaternion.prototype.normalizeFast = function () {
  77548. var f = (3.0-(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w))/2.0;
  77549. if ( f === 0 ) {
  77550. this.x = 0;
  77551. this.y = 0;
  77552. this.z = 0;
  77553. this.w = 0;
  77554. } else {
  77555. this.x *= f;
  77556. this.y *= f;
  77557. this.z *= f;
  77558. this.w *= f;
  77559. }
  77560. };
  77561. /**
  77562. * Multiply the quaternion by a vector
  77563. * @method vmult
  77564. * @param {Vec3} v
  77565. * @param {Vec3} target Optional
  77566. * @return {Vec3}
  77567. */
  77568. Quaternion.prototype.vmult = function(v,target){
  77569. target = target || new Vec3();
  77570. var x = v.x,
  77571. y = v.y,
  77572. z = v.z;
  77573. var qx = this.x,
  77574. qy = this.y,
  77575. qz = this.z,
  77576. qw = this.w;
  77577. // q*v
  77578. var ix = qw * x + qy * z - qz * y,
  77579. iy = qw * y + qz * x - qx * z,
  77580. iz = qw * z + qx * y - qy * x,
  77581. iw = -qx * x - qy * y - qz * z;
  77582. target.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  77583. target.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  77584. target.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  77585. return target;
  77586. };
  77587. /**
  77588. * Copies value of source to this quaternion.
  77589. * @method copy
  77590. * @param {Quaternion} source
  77591. * @return {Quaternion} this
  77592. */
  77593. Quaternion.prototype.copy = function(source){
  77594. this.x = source.x;
  77595. this.y = source.y;
  77596. this.z = source.z;
  77597. this.w = source.w;
  77598. return this;
  77599. };
  77600. /**
  77601. * Convert the quaternion to euler angle representation. Order: YZX, as this page describes: http://www.euclideanspace.com/maths/standards/index.htm
  77602. * @method toEuler
  77603. * @param {Vec3} target
  77604. * @param string order Three-character string e.g. "YZX", which also is default.
  77605. */
  77606. Quaternion.prototype.toEuler = function(target,order){
  77607. order = order || "YZX";
  77608. var heading, attitude, bank;
  77609. var x = this.x, y = this.y, z = this.z, w = this.w;
  77610. switch(order){
  77611. case "YZX":
  77612. var test = x*y + z*w;
  77613. if (test > 0.499) { // singularity at north pole
  77614. heading = 2 * Math.atan2(x,w);
  77615. attitude = Math.PI/2;
  77616. bank = 0;
  77617. }
  77618. if (test < -0.499) { // singularity at south pole
  77619. heading = -2 * Math.atan2(x,w);
  77620. attitude = - Math.PI/2;
  77621. bank = 0;
  77622. }
  77623. if(isNaN(heading)){
  77624. var sqx = x*x;
  77625. var sqy = y*y;
  77626. var sqz = z*z;
  77627. heading = Math.atan2(2*y*w - 2*x*z , 1 - 2*sqy - 2*sqz); // Heading
  77628. attitude = Math.asin(2*test); // attitude
  77629. bank = Math.atan2(2*x*w - 2*y*z , 1 - 2*sqx - 2*sqz); // bank
  77630. }
  77631. break;
  77632. default:
  77633. throw new Error("Euler order "+order+" not supported yet.");
  77634. }
  77635. target.y = heading;
  77636. target.z = attitude;
  77637. target.x = bank;
  77638. };
  77639. /**
  77640. * See http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  77641. * @method setFromEuler
  77642. * @param {Number} x
  77643. * @param {Number} y
  77644. * @param {Number} z
  77645. * @param {String} order The order to apply angles: 'XYZ' or 'YXZ' or any other combination
  77646. */
  77647. Quaternion.prototype.setFromEuler = function ( x, y, z, order ) {
  77648. order = order || "XYZ";
  77649. var c1 = Math.cos( x / 2 );
  77650. var c2 = Math.cos( y / 2 );
  77651. var c3 = Math.cos( z / 2 );
  77652. var s1 = Math.sin( x / 2 );
  77653. var s2 = Math.sin( y / 2 );
  77654. var s3 = Math.sin( z / 2 );
  77655. if ( order === 'XYZ' ) {
  77656. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  77657. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  77658. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  77659. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  77660. } else if ( order === 'YXZ' ) {
  77661. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  77662. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  77663. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  77664. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  77665. } else if ( order === 'ZXY' ) {
  77666. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  77667. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  77668. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  77669. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  77670. } else if ( order === 'ZYX' ) {
  77671. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  77672. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  77673. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  77674. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  77675. } else if ( order === 'YZX' ) {
  77676. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  77677. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  77678. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  77679. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  77680. } else if ( order === 'XZY' ) {
  77681. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  77682. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  77683. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  77684. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  77685. }
  77686. return this;
  77687. };
  77688. Quaternion.prototype.clone = function(){
  77689. return new Quaternion(this.x, this.y, this.z, this.w);
  77690. };
  77691. },{"./Vec3":30}],29:[function(_dereq_,module,exports){
  77692. var Vec3 = _dereq_('./Vec3');
  77693. var Quaternion = _dereq_('./Quaternion');
  77694. module.exports = Transform;
  77695. /**
  77696. * @class Transform
  77697. * @constructor
  77698. */
  77699. function Transform(options) {
  77700. options = options || {};
  77701. /**
  77702. * @property {Vec3} position
  77703. */
  77704. this.position = new Vec3();
  77705. if(options.position){
  77706. this.position.copy(options.position);
  77707. }
  77708. /**
  77709. * @property {Quaternion} quaternion
  77710. */
  77711. this.quaternion = new Quaternion();
  77712. if(options.quaternion){
  77713. this.quaternion.copy(options.quaternion);
  77714. }
  77715. }
  77716. var tmpQuat = new Quaternion();
  77717. /**
  77718. * @static
  77719. * @method pointToLocaFrame
  77720. * @param {Vec3} position
  77721. * @param {Quaternion} quaternion
  77722. * @param {Vec3} worldPoint
  77723. * @param {Vec3} result
  77724. */
  77725. Transform.pointToLocalFrame = function(position, quaternion, worldPoint, result){
  77726. var result = result || new Vec3();
  77727. worldPoint.vsub(position, result);
  77728. quaternion.conjugate(tmpQuat);
  77729. tmpQuat.vmult(result, result);
  77730. return result;
  77731. };
  77732. /**
  77733. * Get a global point in local transform coordinates.
  77734. * @method pointToLocal
  77735. * @param {Vec3} point
  77736. * @param {Vec3} result
  77737. * @return {Vec3} The "result" vector object
  77738. */
  77739. Transform.prototype.pointToLocal = function(worldPoint, result){
  77740. return Transform.pointToLocalFrame(this.position, this.quaternion, worldPoint, result);
  77741. };
  77742. /**
  77743. * @static
  77744. * @method pointToWorldFrame
  77745. * @param {Vec3} position
  77746. * @param {Vec3} quaternion
  77747. * @param {Vec3} localPoint
  77748. * @param {Vec3} result
  77749. */
  77750. Transform.pointToWorldFrame = function(position, quaternion, localPoint, result){
  77751. var result = result || new Vec3();
  77752. quaternion.vmult(localPoint, result);
  77753. result.vadd(position, result);
  77754. return result;
  77755. };
  77756. /**
  77757. * Get a local point in global transform coordinates.
  77758. * @method pointToWorld
  77759. * @param {Vec3} point
  77760. * @param {Vec3} result
  77761. * @return {Vec3} The "result" vector object
  77762. */
  77763. Transform.prototype.pointToWorld = function(localPoint, result){
  77764. return Transform.pointToWorldFrame(this.position, this.quaternion, localPoint, result);
  77765. };
  77766. Transform.prototype.vectorToWorldFrame = function(localVector, result){
  77767. var result = result || new Vec3();
  77768. this.quaternion.vmult(localVector, result);
  77769. return result;
  77770. };
  77771. Transform.vectorToWorldFrame = function(quaternion, localVector, result){
  77772. quaternion.vmult(localVector, result);
  77773. return result;
  77774. };
  77775. Transform.vectorToLocalFrame = function(position, quaternion, worldVector, result){
  77776. var result = result || new Vec3();
  77777. quaternion.w *= -1;
  77778. quaternion.vmult(worldVector, result);
  77779. quaternion.w *= -1;
  77780. return result;
  77781. };
  77782. },{"./Quaternion":28,"./Vec3":30}],30:[function(_dereq_,module,exports){
  77783. module.exports = Vec3;
  77784. var Mat3 = _dereq_('./Mat3');
  77785. /**
  77786. * 3-dimensional vector
  77787. * @class Vec3
  77788. * @constructor
  77789. * @param {Number} x
  77790. * @param {Number} y
  77791. * @param {Number} z
  77792. * @author schteppe
  77793. * @example
  77794. * var v = new Vec3(1, 2, 3);
  77795. * console.log('x=' + v.x); // x=1
  77796. */
  77797. function Vec3(x,y,z){
  77798. /**
  77799. * @property x
  77800. * @type {Number}
  77801. */
  77802. this.x = x||0.0;
  77803. /**
  77804. * @property y
  77805. * @type {Number}
  77806. */
  77807. this.y = y||0.0;
  77808. /**
  77809. * @property z
  77810. * @type {Number}
  77811. */
  77812. this.z = z||0.0;
  77813. }
  77814. /**
  77815. * @static
  77816. * @property {Vec3} ZERO
  77817. */
  77818. Vec3.ZERO = new Vec3(0, 0, 0);
  77819. /**
  77820. * @static
  77821. * @property {Vec3} UNIT_X
  77822. */
  77823. Vec3.UNIT_X = new Vec3(1, 0, 0);
  77824. /**
  77825. * @static
  77826. * @property {Vec3} UNIT_Y
  77827. */
  77828. Vec3.UNIT_Y = new Vec3(0, 1, 0);
  77829. /**
  77830. * @static
  77831. * @property {Vec3} UNIT_Z
  77832. */
  77833. Vec3.UNIT_Z = new Vec3(0, 0, 1);
  77834. /**
  77835. * Vector cross product
  77836. * @method cross
  77837. * @param {Vec3} v
  77838. * @param {Vec3} target Optional. Target to save in.
  77839. * @return {Vec3}
  77840. */
  77841. Vec3.prototype.cross = function(v,target){
  77842. var vx=v.x, vy=v.y, vz=v.z, x=this.x, y=this.y, z=this.z;
  77843. target = target || new Vec3();
  77844. target.x = (y * vz) - (z * vy);
  77845. target.y = (z * vx) - (x * vz);
  77846. target.z = (x * vy) - (y * vx);
  77847. return target;
  77848. };
  77849. /**
  77850. * Set the vectors' 3 elements
  77851. * @method set
  77852. * @param {Number} x
  77853. * @param {Number} y
  77854. * @param {Number} z
  77855. * @return Vec3
  77856. */
  77857. Vec3.prototype.set = function(x,y,z){
  77858. this.x = x;
  77859. this.y = y;
  77860. this.z = z;
  77861. return this;
  77862. };
  77863. /**
  77864. * Set all components of the vector to zero.
  77865. * @method setZero
  77866. */
  77867. Vec3.prototype.setZero = function(){
  77868. this.x = this.y = this.z = 0;
  77869. };
  77870. /**
  77871. * Vector addition
  77872. * @method vadd
  77873. * @param {Vec3} v
  77874. * @param {Vec3} target Optional.
  77875. * @return {Vec3}
  77876. */
  77877. Vec3.prototype.vadd = function(v,target){
  77878. if(target){
  77879. target.x = v.x + this.x;
  77880. target.y = v.y + this.y;
  77881. target.z = v.z + this.z;
  77882. } else {
  77883. return new Vec3(this.x + v.x,
  77884. this.y + v.y,
  77885. this.z + v.z);
  77886. }
  77887. };
  77888. /**
  77889. * Vector subtraction
  77890. * @method vsub
  77891. * @param {Vec3} v
  77892. * @param {Vec3} target Optional. Target to save in.
  77893. * @return {Vec3}
  77894. */
  77895. Vec3.prototype.vsub = function(v,target){
  77896. if(target){
  77897. target.x = this.x - v.x;
  77898. target.y = this.y - v.y;
  77899. target.z = this.z - v.z;
  77900. } else {
  77901. return new Vec3(this.x-v.x,
  77902. this.y-v.y,
  77903. this.z-v.z);
  77904. }
  77905. };
  77906. /**
  77907. * Get the cross product matrix a_cross from a vector, such that a x b = a_cross * b = c
  77908. * @method crossmat
  77909. * @see http://www8.cs.umu.se/kurser/TDBD24/VT06/lectures/Lecture6.pdf
  77910. * @return {Mat3}
  77911. */
  77912. Vec3.prototype.crossmat = function(){
  77913. return new Mat3([ 0, -this.z, this.y,
  77914. this.z, 0, -this.x,
  77915. -this.y, this.x, 0]);
  77916. };
  77917. /**
  77918. * Normalize the vector. Note that this changes the values in the vector.
  77919. * @method normalize
  77920. * @return {Number} Returns the norm of the vector
  77921. */
  77922. Vec3.prototype.normalize = function(){
  77923. var x=this.x, y=this.y, z=this.z;
  77924. var n = Math.sqrt(x*x + y*y + z*z);
  77925. if(n>0.0){
  77926. var invN = 1/n;
  77927. this.x *= invN;
  77928. this.y *= invN;
  77929. this.z *= invN;
  77930. } else {
  77931. // Make something up
  77932. this.x = 0;
  77933. this.y = 0;
  77934. this.z = 0;
  77935. }
  77936. return n;
  77937. };
  77938. /**
  77939. * Get the version of this vector that is of length 1.
  77940. * @method unit
  77941. * @param {Vec3} target Optional target to save in
  77942. * @return {Vec3} Returns the unit vector
  77943. */
  77944. Vec3.prototype.unit = function(target){
  77945. target = target || new Vec3();
  77946. var x=this.x, y=this.y, z=this.z;
  77947. var ninv = Math.sqrt(x*x + y*y + z*z);
  77948. if(ninv>0.0){
  77949. ninv = 1.0/ninv;
  77950. target.x = x * ninv;
  77951. target.y = y * ninv;
  77952. target.z = z * ninv;
  77953. } else {
  77954. target.x = 1;
  77955. target.y = 0;
  77956. target.z = 0;
  77957. }
  77958. return target;
  77959. };
  77960. /**
  77961. * Get the length of the vector
  77962. * @method norm
  77963. * @return {Number}
  77964. * @deprecated Use .length() instead
  77965. */
  77966. Vec3.prototype.norm = function(){
  77967. var x=this.x, y=this.y, z=this.z;
  77968. return Math.sqrt(x*x + y*y + z*z);
  77969. };
  77970. /**
  77971. * Get the length of the vector
  77972. * @method length
  77973. * @return {Number}
  77974. */
  77975. Vec3.prototype.length = Vec3.prototype.norm;
  77976. /**
  77977. * Get the squared length of the vector
  77978. * @method norm2
  77979. * @return {Number}
  77980. * @deprecated Use .lengthSquared() instead.
  77981. */
  77982. Vec3.prototype.norm2 = function(){
  77983. return this.dot(this);
  77984. };
  77985. /**
  77986. * Get the squared length of the vector.
  77987. * @method lengthSquared
  77988. * @return {Number}
  77989. */
  77990. Vec3.prototype.lengthSquared = Vec3.prototype.norm2;
  77991. /**
  77992. * Get distance from this point to another point
  77993. * @method distanceTo
  77994. * @param {Vec3} p
  77995. * @return {Number}
  77996. */
  77997. Vec3.prototype.distanceTo = function(p){
  77998. var x=this.x, y=this.y, z=this.z;
  77999. var px=p.x, py=p.y, pz=p.z;
  78000. return Math.sqrt((px-x)*(px-x)+
  78001. (py-y)*(py-y)+
  78002. (pz-z)*(pz-z));
  78003. };
  78004. /**
  78005. * Get squared distance from this point to another point
  78006. * @method distanceSquared
  78007. * @param {Vec3} p
  78008. * @return {Number}
  78009. */
  78010. Vec3.prototype.distanceSquared = function(p){
  78011. var x=this.x, y=this.y, z=this.z;
  78012. var px=p.x, py=p.y, pz=p.z;
  78013. return (px-x)*(px-x) + (py-y)*(py-y) + (pz-z)*(pz-z);
  78014. };
  78015. /**
  78016. * Multiply all the components of the vector with a scalar.
  78017. * @deprecated Use .scale instead
  78018. * @method mult
  78019. * @param {Number} scalar
  78020. * @param {Vec3} target The vector to save the result in.
  78021. * @return {Vec3}
  78022. * @deprecated Use .scale() instead
  78023. */
  78024. Vec3.prototype.mult = function(scalar,target){
  78025. target = target || new Vec3();
  78026. var x = this.x,
  78027. y = this.y,
  78028. z = this.z;
  78029. target.x = scalar * x;
  78030. target.y = scalar * y;
  78031. target.z = scalar * z;
  78032. return target;
  78033. };
  78034. /**
  78035. * Multiply the vector with a scalar.
  78036. * @method scale
  78037. * @param {Number} scalar
  78038. * @param {Vec3} target
  78039. * @return {Vec3}
  78040. */
  78041. Vec3.prototype.scale = Vec3.prototype.mult;
  78042. /**
  78043. * Calculate dot product
  78044. * @method dot
  78045. * @param {Vec3} v
  78046. * @return {Number}
  78047. */
  78048. Vec3.prototype.dot = function(v){
  78049. return this.x * v.x + this.y * v.y + this.z * v.z;
  78050. };
  78051. /**
  78052. * @method isZero
  78053. * @return bool
  78054. */
  78055. Vec3.prototype.isZero = function(){
  78056. return this.x===0 && this.y===0 && this.z===0;
  78057. };
  78058. /**
  78059. * Make the vector point in the opposite direction.
  78060. * @method negate
  78061. * @param {Vec3} target Optional target to save in
  78062. * @return {Vec3}
  78063. */
  78064. Vec3.prototype.negate = function(target){
  78065. target = target || new Vec3();
  78066. target.x = -this.x;
  78067. target.y = -this.y;
  78068. target.z = -this.z;
  78069. return target;
  78070. };
  78071. /**
  78072. * Compute two artificial tangents to the vector
  78073. * @method tangents
  78074. * @param {Vec3} t1 Vector object to save the first tangent in
  78075. * @param {Vec3} t2 Vector object to save the second tangent in
  78076. */
  78077. var Vec3_tangents_n = new Vec3();
  78078. var Vec3_tangents_randVec = new Vec3();
  78079. Vec3.prototype.tangents = function(t1,t2){
  78080. var norm = this.norm();
  78081. if(norm>0.0){
  78082. var n = Vec3_tangents_n;
  78083. var inorm = 1/norm;
  78084. n.set(this.x*inorm,this.y*inorm,this.z*inorm);
  78085. var randVec = Vec3_tangents_randVec;
  78086. if(Math.abs(n.x) < 0.9){
  78087. randVec.set(1,0,0);
  78088. n.cross(randVec,t1);
  78089. } else {
  78090. randVec.set(0,1,0);
  78091. n.cross(randVec,t1);
  78092. }
  78093. n.cross(t1,t2);
  78094. } else {
  78095. // The normal length is zero, make something up
  78096. t1.set(1, 0, 0);
  78097. t2.set(0, 1, 0);
  78098. }
  78099. };
  78100. /**
  78101. * Converts to a more readable format
  78102. * @method toString
  78103. * @return string
  78104. */
  78105. Vec3.prototype.toString = function(){
  78106. return this.x+","+this.y+","+this.z;
  78107. };
  78108. /**
  78109. * Converts to an array
  78110. * @method toArray
  78111. * @return Array
  78112. */
  78113. Vec3.prototype.toArray = function(){
  78114. return [this.x, this.y, this.z];
  78115. };
  78116. /**
  78117. * Copies value of source to this vector.
  78118. * @method copy
  78119. * @param {Vec3} source
  78120. * @return {Vec3} this
  78121. */
  78122. Vec3.prototype.copy = function(source){
  78123. this.x = source.x;
  78124. this.y = source.y;
  78125. this.z = source.z;
  78126. return this;
  78127. };
  78128. /**
  78129. * Do a linear interpolation between two vectors
  78130. * @method lerp
  78131. * @param {Vec3} v
  78132. * @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.
  78133. * @param {Vec3} target
  78134. */
  78135. Vec3.prototype.lerp = function(v,t,target){
  78136. var x=this.x, y=this.y, z=this.z;
  78137. target.x = x + (v.x-x)*t;
  78138. target.y = y + (v.y-y)*t;
  78139. target.z = z + (v.z-z)*t;
  78140. };
  78141. /**
  78142. * Check if a vector equals is almost equal to another one.
  78143. * @method almostEquals
  78144. * @param {Vec3} v
  78145. * @param {Number} precision
  78146. * @return bool
  78147. */
  78148. Vec3.prototype.almostEquals = function(v,precision){
  78149. if(precision===undefined){
  78150. precision = 1e-6;
  78151. }
  78152. if( Math.abs(this.x-v.x)>precision ||
  78153. Math.abs(this.y-v.y)>precision ||
  78154. Math.abs(this.z-v.z)>precision){
  78155. return false;
  78156. }
  78157. return true;
  78158. };
  78159. /**
  78160. * Check if a vector is almost zero
  78161. * @method almostZero
  78162. * @param {Number} precision
  78163. */
  78164. Vec3.prototype.almostZero = function(precision){
  78165. if(precision===undefined){
  78166. precision = 1e-6;
  78167. }
  78168. if( Math.abs(this.x)>precision ||
  78169. Math.abs(this.y)>precision ||
  78170. Math.abs(this.z)>precision){
  78171. return false;
  78172. }
  78173. return true;
  78174. };
  78175. var antip_neg = new Vec3();
  78176. /**
  78177. * Check if the vector is anti-parallel to another vector.
  78178. * @method isAntiparallelTo
  78179. * @param {Vec3} v
  78180. * @param {Number} precision Set to zero for exact comparisons
  78181. * @return {Boolean}
  78182. */
  78183. Vec3.prototype.isAntiparallelTo = function(v,precision){
  78184. this.negate(antip_neg);
  78185. return antip_neg.almostEquals(v,precision);
  78186. };
  78187. /**
  78188. * Clone the vector
  78189. * @method clone
  78190. * @return {Vec3}
  78191. */
  78192. Vec3.prototype.clone = function(){
  78193. return new Vec3(this.x, this.y, this.z);
  78194. };
  78195. },{"./Mat3":27}],31:[function(_dereq_,module,exports){
  78196. module.exports = Body;
  78197. var EventTarget = _dereq_('../utils/EventTarget');
  78198. var Shape = _dereq_('../shapes/Shape');
  78199. var Vec3 = _dereq_('../math/Vec3');
  78200. var Mat3 = _dereq_('../math/Mat3');
  78201. var Quaternion = _dereq_('../math/Quaternion');
  78202. var Material = _dereq_('../material/Material');
  78203. var AABB = _dereq_('../collision/AABB');
  78204. var Box = _dereq_('../shapes/Box');
  78205. /**
  78206. * Base class for all body types.
  78207. * @class Body
  78208. * @constructor
  78209. * @extends EventTarget
  78210. * @param {object} [options]
  78211. * @param {Vec3} [options.position]
  78212. * @param {Vec3} [options.velocity]
  78213. * @param {Vec3} [options.angularVelocity]
  78214. * @param {Quaternion} [options.quaternion]
  78215. * @param {number} [options.mass]
  78216. * @param {Material} [options.material]
  78217. * @param {number} [options.type]
  78218. * @param {number} [options.linearDamping=0.01]
  78219. * @param {number} [options.angularDamping=0.01]
  78220. * @param {boolean} [options.allowSleep=true]
  78221. * @param {number} [options.sleepSpeedLimit=0.1]
  78222. * @param {number} [options.sleepTimeLimit=1]
  78223. * @param {number} [options.collisionFilterGroup=1]
  78224. * @param {number} [options.collisionFilterMask=1]
  78225. * @param {boolean} [options.fixedRotation=false]
  78226. * @param {Body} [options.shape]
  78227. * @example
  78228. * var body = new Body({
  78229. * mass: 1
  78230. * });
  78231. * var shape = new Sphere(1);
  78232. * body.addShape(shape);
  78233. * world.add(body);
  78234. */
  78235. function Body(options){
  78236. options = options || {};
  78237. EventTarget.apply(this);
  78238. this.id = Body.idCounter++;
  78239. /**
  78240. * Reference to the world the body is living in
  78241. * @property world
  78242. * @type {World}
  78243. */
  78244. this.world = null;
  78245. /**
  78246. * 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.
  78247. * @property preStep
  78248. * @type {Function}
  78249. * @deprecated Use World events instead
  78250. */
  78251. this.preStep = null;
  78252. /**
  78253. * Callback function that is used AFTER stepping the system. Inside the function, "this" will refer to this Body object.
  78254. * @property postStep
  78255. * @type {Function}
  78256. * @deprecated Use World events instead
  78257. */
  78258. this.postStep = null;
  78259. this.vlambda = new Vec3();
  78260. /**
  78261. * @property {Number} collisionFilterGroup
  78262. */
  78263. this.collisionFilterGroup = typeof(options.collisionFilterGroup) === 'number' ? options.collisionFilterGroup : 1;
  78264. /**
  78265. * @property {Number} collisionFilterMask
  78266. */
  78267. this.collisionFilterMask = typeof(options.collisionFilterMask) === 'number' ? options.collisionFilterMask : 1;
  78268. /**
  78269. * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled.
  78270. * @property {Number} collisionResponse
  78271. */
  78272. this.collisionResponse = true;
  78273. /**
  78274. * @property position
  78275. * @type {Vec3}
  78276. */
  78277. this.position = new Vec3();
  78278. if(options.position){
  78279. this.position.copy(options.position);
  78280. }
  78281. /**
  78282. * @property {Vec3} previousPosition
  78283. */
  78284. this.previousPosition = new Vec3();
  78285. /**
  78286. * Initial position of the body
  78287. * @property initPosition
  78288. * @type {Vec3}
  78289. */
  78290. this.initPosition = new Vec3();
  78291. /**
  78292. * @property velocity
  78293. * @type {Vec3}
  78294. */
  78295. this.velocity = new Vec3();
  78296. if(options.velocity){
  78297. this.velocity.copy(options.velocity);
  78298. }
  78299. /**
  78300. * @property initVelocity
  78301. * @type {Vec3}
  78302. */
  78303. this.initVelocity = new Vec3();
  78304. /**
  78305. * Linear force on the body
  78306. * @property force
  78307. * @type {Vec3}
  78308. */
  78309. this.force = new Vec3();
  78310. var mass = typeof(options.mass) === 'number' ? options.mass : 0;
  78311. /**
  78312. * @property mass
  78313. * @type {Number}
  78314. * @default 0
  78315. */
  78316. this.mass = mass;
  78317. /**
  78318. * @property invMass
  78319. * @type {Number}
  78320. */
  78321. this.invMass = mass > 0 ? 1.0 / mass : 0;
  78322. /**
  78323. * @property material
  78324. * @type {Material}
  78325. */
  78326. this.material = options.material || null;
  78327. /**
  78328. * @property linearDamping
  78329. * @type {Number}
  78330. */
  78331. this.linearDamping = typeof(options.linearDamping) === 'number' ? options.linearDamping : 0.01;
  78332. /**
  78333. * One of: Body.DYNAMIC, Body.STATIC and Body.KINEMATIC.
  78334. * @property type
  78335. * @type {Number}
  78336. */
  78337. this.type = (mass <= 0.0 ? Body.STATIC : Body.DYNAMIC);
  78338. if(typeof(options.type) === typeof(Body.STATIC)){
  78339. this.type = options.type;
  78340. }
  78341. /**
  78342. * If true, the body will automatically fall to sleep.
  78343. * @property allowSleep
  78344. * @type {Boolean}
  78345. * @default true
  78346. */
  78347. this.allowSleep = typeof(options.allowSleep) !== 'undefined' ? options.allowSleep : true;
  78348. /**
  78349. * Current sleep state.
  78350. * @property sleepState
  78351. * @type {Number}
  78352. */
  78353. this.sleepState = 0;
  78354. /**
  78355. * If the speed (the norm of the velocity) is smaller than this value, the body is considered sleepy.
  78356. * @property sleepSpeedLimit
  78357. * @type {Number}
  78358. * @default 0.1
  78359. */
  78360. this.sleepSpeedLimit = typeof(options.sleepSpeedLimit) !== 'undefined' ? options.sleepSpeedLimit : 0.1;
  78361. /**
  78362. * If the body has been sleepy for this sleepTimeLimit seconds, it is considered sleeping.
  78363. * @property sleepTimeLimit
  78364. * @type {Number}
  78365. * @default 1
  78366. */
  78367. this.sleepTimeLimit = typeof(options.sleepTimeLimit) !== 'undefined' ? options.sleepTimeLimit : 1;
  78368. this.timeLastSleepy = 0;
  78369. this._wakeUpAfterNarrowphase = false;
  78370. /**
  78371. * Rotational force on the body, around center of mass
  78372. * @property {Vec3} torque
  78373. */
  78374. this.torque = new Vec3();
  78375. /**
  78376. * Orientation of the body
  78377. * @property quaternion
  78378. * @type {Quaternion}
  78379. */
  78380. this.quaternion = new Quaternion();
  78381. if(options.quaternion){
  78382. this.quaternion.copy(options.quaternion);
  78383. }
  78384. /**
  78385. * @property initQuaternion
  78386. * @type {Quaternion}
  78387. */
  78388. this.initQuaternion = new Quaternion();
  78389. /**
  78390. * @property angularVelocity
  78391. * @type {Vec3}
  78392. */
  78393. this.angularVelocity = new Vec3();
  78394. if(options.angularVelocity){
  78395. this.angularVelocity.copy(options.angularVelocity);
  78396. }
  78397. /**
  78398. * @property initAngularVelocity
  78399. * @type {Vec3}
  78400. */
  78401. this.initAngularVelocity = new Vec3();
  78402. this.interpolatedPosition = new Vec3();
  78403. this.interpolatedQuaternion = new Quaternion();
  78404. /**
  78405. * @property shapes
  78406. * @type {array}
  78407. */
  78408. this.shapes = [];
  78409. /**
  78410. * @property shapeOffsets
  78411. * @type {array}
  78412. */
  78413. this.shapeOffsets = [];
  78414. /**
  78415. * @property shapeOrientations
  78416. * @type {array}
  78417. */
  78418. this.shapeOrientations = [];
  78419. /**
  78420. * @property inertia
  78421. * @type {Vec3}
  78422. */
  78423. this.inertia = new Vec3();
  78424. /**
  78425. * @property {Vec3} invInertia
  78426. */
  78427. this.invInertia = new Vec3();
  78428. /**
  78429. * @property {Mat3} invInertiaWorld
  78430. */
  78431. this.invInertiaWorld = new Mat3();
  78432. this.invMassSolve = 0;
  78433. /**
  78434. * @property {Vec3} invInertiaSolve
  78435. */
  78436. this.invInertiaSolve = new Vec3();
  78437. /**
  78438. * @property {Mat3} invInertiaWorldSolve
  78439. */
  78440. this.invInertiaWorldSolve = new Mat3();
  78441. /**
  78442. * Set to true if you don't want the body to rotate. Make sure to run .updateMassProperties() after changing this.
  78443. * @property {Boolean} fixedRotation
  78444. * @default false
  78445. */
  78446. this.fixedRotation = typeof(options.fixedRotation) !== "undefined" ? options.fixedRotation : false;
  78447. /**
  78448. * @property {Number} angularDamping
  78449. */
  78450. this.angularDamping = typeof(options.angularDamping) !== 'undefined' ? options.angularDamping : 0.01;
  78451. /**
  78452. * @property aabb
  78453. * @type {AABB}
  78454. */
  78455. this.aabb = new AABB();
  78456. /**
  78457. * Indicates if the AABB needs to be updated before use.
  78458. * @property aabbNeedsUpdate
  78459. * @type {Boolean}
  78460. */
  78461. this.aabbNeedsUpdate = true;
  78462. this.wlambda = new Vec3();
  78463. if(options.shape){
  78464. this.addShape(options.shape);
  78465. }
  78466. this.updateMassProperties();
  78467. }
  78468. Body.prototype = new EventTarget();
  78469. Body.prototype.constructor = Body;
  78470. /**
  78471. * 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.
  78472. * @static
  78473. * @property DYNAMIC
  78474. * @type {Number}
  78475. */
  78476. Body.DYNAMIC = 1;
  78477. /**
  78478. * 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.
  78479. * @static
  78480. * @property STATIC
  78481. * @type {Number}
  78482. */
  78483. Body.STATIC = 2;
  78484. /**
  78485. * 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.
  78486. * @static
  78487. * @property KINEMATIC
  78488. * @type {Number}
  78489. */
  78490. Body.KINEMATIC = 4;
  78491. /**
  78492. * @static
  78493. * @property AWAKE
  78494. * @type {number}
  78495. */
  78496. Body.AWAKE = 0;
  78497. /**
  78498. * @static
  78499. * @property SLEEPY
  78500. * @type {number}
  78501. */
  78502. Body.SLEEPY = 1;
  78503. /**
  78504. * @static
  78505. * @property SLEEPING
  78506. * @type {number}
  78507. */
  78508. Body.SLEEPING = 2;
  78509. Body.idCounter = 0;
  78510. /**
  78511. * Wake the body up.
  78512. * @method wakeUp
  78513. */
  78514. Body.prototype.wakeUp = function(){
  78515. var s = this.sleepState;
  78516. this.sleepState = 0;
  78517. if(s === Body.SLEEPING){
  78518. this.dispatchEvent({type:"wakeup"});
  78519. }
  78520. };
  78521. /**
  78522. * Force body sleep
  78523. * @method sleep
  78524. */
  78525. Body.prototype.sleep = function(){
  78526. this.sleepState = Body.SLEEPING;
  78527. this.velocity.set(0,0,0);
  78528. this.angularVelocity.set(0,0,0);
  78529. };
  78530. Body.sleepyEvent = {
  78531. type: "sleepy"
  78532. };
  78533. Body.sleepEvent = {
  78534. type: "sleep"
  78535. };
  78536. /**
  78537. * Called every timestep to update internal sleep timer and change sleep state if needed.
  78538. * @method sleepTick
  78539. * @param {Number} time The world time in seconds
  78540. */
  78541. Body.prototype.sleepTick = function(time){
  78542. if(this.allowSleep){
  78543. var sleepState = this.sleepState;
  78544. var speedSquared = this.velocity.norm2() + this.angularVelocity.norm2();
  78545. var speedLimitSquared = Math.pow(this.sleepSpeedLimit,2);
  78546. if(sleepState===Body.AWAKE && speedSquared < speedLimitSquared){
  78547. this.sleepState = Body.SLEEPY; // Sleepy
  78548. this.timeLastSleepy = time;
  78549. this.dispatchEvent(Body.sleepyEvent);
  78550. } else if(sleepState===Body.SLEEPY && speedSquared > speedLimitSquared){
  78551. this.wakeUp(); // Wake up
  78552. } else if(sleepState===Body.SLEEPY && (time - this.timeLastSleepy ) > this.sleepTimeLimit){
  78553. this.sleep(); // Sleeping
  78554. this.dispatchEvent(Body.sleepEvent);
  78555. }
  78556. }
  78557. };
  78558. /**
  78559. * If the body is sleeping, it should be immovable / have infinite mass during solve. We solve it by having a separate "solve mass".
  78560. * @method updateSolveMassProperties
  78561. */
  78562. Body.prototype.updateSolveMassProperties = function(){
  78563. if(this.sleepState === Body.SLEEPING || this.type === Body.KINEMATIC){
  78564. this.invMassSolve = 0;
  78565. this.invInertiaSolve.setZero();
  78566. this.invInertiaWorldSolve.setZero();
  78567. } else {
  78568. this.invMassSolve = this.invMass;
  78569. this.invInertiaSolve.copy(this.invInertia);
  78570. this.invInertiaWorldSolve.copy(this.invInertiaWorld);
  78571. }
  78572. };
  78573. /**
  78574. * Convert a world point to local body frame.
  78575. * @method pointToLocalFrame
  78576. * @param {Vec3} worldPoint
  78577. * @param {Vec3} result
  78578. * @return {Vec3}
  78579. */
  78580. Body.prototype.pointToLocalFrame = function(worldPoint,result){
  78581. var result = result || new Vec3();
  78582. worldPoint.vsub(this.position,result);
  78583. this.quaternion.conjugate().vmult(result,result);
  78584. return result;
  78585. };
  78586. /**
  78587. * Convert a world vector to local body frame.
  78588. * @method vectorToLocalFrame
  78589. * @param {Vec3} worldPoint
  78590. * @param {Vec3} result
  78591. * @return {Vec3}
  78592. */
  78593. Body.prototype.vectorToLocalFrame = function(worldVector, result){
  78594. var result = result || new Vec3();
  78595. this.quaternion.conjugate().vmult(worldVector,result);
  78596. return result;
  78597. };
  78598. /**
  78599. * Convert a local body point to world frame.
  78600. * @method pointToWorldFrame
  78601. * @param {Vec3} localPoint
  78602. * @param {Vec3} result
  78603. * @return {Vec3}
  78604. */
  78605. Body.prototype.pointToWorldFrame = function(localPoint,result){
  78606. var result = result || new Vec3();
  78607. this.quaternion.vmult(localPoint,result);
  78608. result.vadd(this.position,result);
  78609. return result;
  78610. };
  78611. /**
  78612. * Convert a local body point to world frame.
  78613. * @method vectorToWorldFrame
  78614. * @param {Vec3} localVector
  78615. * @param {Vec3} result
  78616. * @return {Vec3}
  78617. */
  78618. Body.prototype.vectorToWorldFrame = function(localVector, result){
  78619. var result = result || new Vec3();
  78620. this.quaternion.vmult(localVector, result);
  78621. return result;
  78622. };
  78623. var tmpVec = new Vec3();
  78624. var tmpQuat = new Quaternion();
  78625. /**
  78626. * Add a shape to the body with a local offset and orientation.
  78627. * @method addShape
  78628. * @param {Shape} shape
  78629. * @param {Vec3} offset
  78630. * @param {Quaternion} quaternion
  78631. * @return {Body} The body object, for chainability.
  78632. */
  78633. Body.prototype.addShape = function(shape, _offset, _orientation){
  78634. var offset = new Vec3();
  78635. var orientation = new Quaternion();
  78636. if(_offset){
  78637. offset.copy(_offset);
  78638. }
  78639. if(_orientation){
  78640. orientation.copy(_orientation);
  78641. }
  78642. this.shapes.push(shape);
  78643. this.shapeOffsets.push(offset);
  78644. this.shapeOrientations.push(orientation);
  78645. this.updateMassProperties();
  78646. this.updateBoundingRadius();
  78647. this.aabbNeedsUpdate = true;
  78648. return this;
  78649. };
  78650. /**
  78651. * Update the bounding radius of the body. Should be done if any of the shapes are changed.
  78652. * @method updateBoundingRadius
  78653. */
  78654. Body.prototype.updateBoundingRadius = function(){
  78655. var shapes = this.shapes,
  78656. shapeOffsets = this.shapeOffsets,
  78657. N = shapes.length,
  78658. radius = 0;
  78659. for(var i=0; i!==N; i++){
  78660. var shape = shapes[i];
  78661. shape.updateBoundingSphereRadius();
  78662. var offset = shapeOffsets[i].norm(),
  78663. r = shape.boundingSphereRadius;
  78664. if(offset + r > radius){
  78665. radius = offset + r;
  78666. }
  78667. }
  78668. this.boundingRadius = radius;
  78669. };
  78670. var computeAABB_shapeAABB = new AABB();
  78671. /**
  78672. * Updates the .aabb
  78673. * @method computeAABB
  78674. * @todo rename to updateAABB()
  78675. */
  78676. Body.prototype.computeAABB = function(){
  78677. var shapes = this.shapes,
  78678. shapeOffsets = this.shapeOffsets,
  78679. shapeOrientations = this.shapeOrientations,
  78680. N = shapes.length,
  78681. offset = tmpVec,
  78682. orientation = tmpQuat,
  78683. bodyQuat = this.quaternion,
  78684. aabb = this.aabb,
  78685. shapeAABB = computeAABB_shapeAABB;
  78686. for(var i=0; i!==N; i++){
  78687. var shape = shapes[i];
  78688. // Get shape world quaternion
  78689. shapeOrientations[i].mult(bodyQuat, orientation);
  78690. // Get shape world position
  78691. orientation.vmult(shapeOffsets[i], offset);
  78692. offset.vadd(this.position, offset);
  78693. // vec2.rotate(offset, shapeOffsets[i], bodyAngle);
  78694. // vec2.add(offset, offset, this.position);
  78695. // Get shape AABB
  78696. shape.calculateWorldAABB(offset, orientation, shapeAABB.lowerBound, shapeAABB.upperBound);
  78697. if(i === 0){
  78698. aabb.copy(shapeAABB);
  78699. } else {
  78700. aabb.extend(shapeAABB);
  78701. }
  78702. }
  78703. this.aabbNeedsUpdate = false;
  78704. };
  78705. var uiw_m1 = new Mat3(),
  78706. uiw_m2 = new Mat3(),
  78707. uiw_m3 = new Mat3();
  78708. /**
  78709. * Update .inertiaWorld and .invInertiaWorld
  78710. * @method updateInertiaWorld
  78711. */
  78712. Body.prototype.updateInertiaWorld = function(force){
  78713. var I = this.invInertia;
  78714. if (I.x === I.y && I.y === I.z && !force) {
  78715. // If inertia M = s*I, where I is identity and s a scalar, then
  78716. // R*M*R' = R*(s*I)*R' = s*R*I*R' = s*R*R' = s*I = M
  78717. // where R is the rotation matrix.
  78718. // In other words, we don't have to transform the inertia if all
  78719. // inertia diagonal entries are equal.
  78720. } else {
  78721. var m1 = uiw_m1,
  78722. m2 = uiw_m2,
  78723. m3 = uiw_m3;
  78724. m1.setRotationFromQuaternion(this.quaternion);
  78725. m1.transpose(m2);
  78726. m1.scale(I,m1);
  78727. m1.mmult(m2,this.invInertiaWorld);
  78728. //m3.getTrace(this.invInertiaWorld);
  78729. }
  78730. /*
  78731. this.quaternion.vmult(this.inertia,this.inertiaWorld);
  78732. this.quaternion.vmult(this.invInertia,this.invInertiaWorld);
  78733. */
  78734. };
  78735. /**
  78736. * 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.
  78737. * @method applyForce
  78738. * @param {Vec3} force The amount of force to add.
  78739. * @param {Vec3} worldPoint A world point to apply the force on.
  78740. */
  78741. var Body_applyForce_r = new Vec3();
  78742. var Body_applyForce_rotForce = new Vec3();
  78743. Body.prototype.applyForce = function(force,worldPoint){
  78744. if(this.type !== Body.DYNAMIC){
  78745. return;
  78746. }
  78747. // Compute point position relative to the body center
  78748. var r = Body_applyForce_r;
  78749. worldPoint.vsub(this.position,r);
  78750. // Compute produced rotational force
  78751. var rotForce = Body_applyForce_rotForce;
  78752. r.cross(force,rotForce);
  78753. // Add linear force
  78754. this.force.vadd(force,this.force);
  78755. // Add rotational force
  78756. this.torque.vadd(rotForce,this.torque);
  78757. };
  78758. /**
  78759. * Apply force to a local point in the body.
  78760. * @method applyLocalForce
  78761. * @param {Vec3} force The force vector to apply, defined locally in the body frame.
  78762. * @param {Vec3} localPoint A local point in the body to apply the force on.
  78763. */
  78764. var Body_applyLocalForce_worldForce = new Vec3();
  78765. var Body_applyLocalForce_worldPoint = new Vec3();
  78766. Body.prototype.applyLocalForce = function(localForce, localPoint){
  78767. if(this.type !== Body.DYNAMIC){
  78768. return;
  78769. }
  78770. var worldForce = Body_applyLocalForce_worldForce;
  78771. var worldPoint = Body_applyLocalForce_worldPoint;
  78772. // Transform the force vector to world space
  78773. this.vectorToWorldFrame(localForce, worldForce);
  78774. this.pointToWorldFrame(localPoint, worldPoint);
  78775. this.applyForce(worldForce, worldPoint);
  78776. };
  78777. /**
  78778. * 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.
  78779. * @method applyImpulse
  78780. * @param {Vec3} impulse The amount of impulse to add.
  78781. * @param {Vec3} worldPoint A world point to apply the force on.
  78782. */
  78783. var Body_applyImpulse_r = new Vec3();
  78784. var Body_applyImpulse_velo = new Vec3();
  78785. var Body_applyImpulse_rotVelo = new Vec3();
  78786. Body.prototype.applyImpulse = function(impulse, worldPoint){
  78787. if(this.type !== Body.DYNAMIC){
  78788. return;
  78789. }
  78790. // Compute point position relative to the body center
  78791. var r = Body_applyImpulse_r;
  78792. worldPoint.vsub(this.position,r);
  78793. // Compute produced central impulse velocity
  78794. var velo = Body_applyImpulse_velo;
  78795. velo.copy(impulse);
  78796. velo.mult(this.invMass,velo);
  78797. // Add linear impulse
  78798. this.velocity.vadd(velo, this.velocity);
  78799. // Compute produced rotational impulse velocity
  78800. var rotVelo = Body_applyImpulse_rotVelo;
  78801. r.cross(impulse,rotVelo);
  78802. /*
  78803. rotVelo.x *= this.invInertia.x;
  78804. rotVelo.y *= this.invInertia.y;
  78805. rotVelo.z *= this.invInertia.z;
  78806. */
  78807. this.invInertiaWorld.vmult(rotVelo,rotVelo);
  78808. // Add rotational Impulse
  78809. this.angularVelocity.vadd(rotVelo, this.angularVelocity);
  78810. };
  78811. /**
  78812. * Apply locally-defined impulse to a local point in the body.
  78813. * @method applyLocalImpulse
  78814. * @param {Vec3} force The force vector to apply, defined locally in the body frame.
  78815. * @param {Vec3} localPoint A local point in the body to apply the force on.
  78816. */
  78817. var Body_applyLocalImpulse_worldImpulse = new Vec3();
  78818. var Body_applyLocalImpulse_worldPoint = new Vec3();
  78819. Body.prototype.applyLocalImpulse = function(localImpulse, localPoint){
  78820. if(this.type !== Body.DYNAMIC){
  78821. return;
  78822. }
  78823. var worldImpulse = Body_applyLocalImpulse_worldImpulse;
  78824. var worldPoint = Body_applyLocalImpulse_worldPoint;
  78825. // Transform the force vector to world space
  78826. this.vectorToWorldFrame(localImpulse, worldImpulse);
  78827. this.pointToWorldFrame(localPoint, worldPoint);
  78828. this.applyImpulse(worldImpulse, worldPoint);
  78829. };
  78830. var Body_updateMassProperties_halfExtents = new Vec3();
  78831. /**
  78832. * Should be called whenever you change the body shape or mass.
  78833. * @method updateMassProperties
  78834. */
  78835. Body.prototype.updateMassProperties = function(){
  78836. var halfExtents = Body_updateMassProperties_halfExtents;
  78837. this.invMass = this.mass > 0 ? 1.0 / this.mass : 0;
  78838. var I = this.inertia;
  78839. var fixed = this.fixedRotation;
  78840. // Approximate with AABB box
  78841. this.computeAABB();
  78842. halfExtents.set(
  78843. (this.aabb.upperBound.x-this.aabb.lowerBound.x) / 2,
  78844. (this.aabb.upperBound.y-this.aabb.lowerBound.y) / 2,
  78845. (this.aabb.upperBound.z-this.aabb.lowerBound.z) / 2
  78846. );
  78847. Box.calculateInertia(halfExtents, this.mass, I);
  78848. this.invInertia.set(
  78849. I.x > 0 && !fixed ? 1.0 / I.x : 0,
  78850. I.y > 0 && !fixed ? 1.0 / I.y : 0,
  78851. I.z > 0 && !fixed ? 1.0 / I.z : 0
  78852. );
  78853. this.updateInertiaWorld(true);
  78854. };
  78855. /**
  78856. * Get world velocity of a point in the body.
  78857. * @method getVelocityAtWorldPoint
  78858. * @param {Vec3} worldPoint
  78859. * @param {Vec3} result
  78860. * @return {Vec3} The result vector.
  78861. */
  78862. Body.prototype.getVelocityAtWorldPoint = function(worldPoint, result){
  78863. var r = new Vec3();
  78864. worldPoint.vsub(this.position, r);
  78865. this.angularVelocity.cross(r, result);
  78866. this.velocity.vadd(result, result);
  78867. return result;
  78868. };
  78869. },{"../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){
  78870. var Body = _dereq_('./Body');
  78871. var Vec3 = _dereq_('../math/Vec3');
  78872. var Quaternion = _dereq_('../math/Quaternion');
  78873. var RaycastResult = _dereq_('../collision/RaycastResult');
  78874. var Ray = _dereq_('../collision/Ray');
  78875. var WheelInfo = _dereq_('../objects/WheelInfo');
  78876. module.exports = RaycastVehicle;
  78877. /**
  78878. * Vehicle helper class that casts rays from the wheel positions towards the ground and applies forces.
  78879. * @class RaycastVehicle
  78880. * @constructor
  78881. * @param {object} [options]
  78882. * @param {Body} [options.chassisBody] The car chassis body.
  78883. * @param {integer} [options.indexRightAxis] Axis to use for right. x=0, y=1, z=2
  78884. * @param {integer} [options.indexLeftAxis]
  78885. * @param {integer} [options.indexUpAxis]
  78886. */
  78887. function RaycastVehicle(options){
  78888. /**
  78889. * @property {Body} chassisBody
  78890. */
  78891. this.chassisBody = options.chassisBody;
  78892. /**
  78893. * An array of WheelInfo objects.
  78894. * @property {array} wheelInfos
  78895. */
  78896. this.wheelInfos = [];
  78897. /**
  78898. * Will be set to true if the car is sliding.
  78899. * @property {boolean} sliding
  78900. */
  78901. this.sliding = false;
  78902. /**
  78903. * @property {World} world
  78904. */
  78905. this.world = null;
  78906. /**
  78907. * Index of the right axis, 0=x, 1=y, 2=z
  78908. * @property {integer} indexRightAxis
  78909. * @default 1
  78910. */
  78911. this.indexRightAxis = typeof(options.indexRightAxis) !== 'undefined' ? options.indexRightAxis : 1;
  78912. /**
  78913. * Index of the forward axis, 0=x, 1=y, 2=z
  78914. * @property {integer} indexForwardAxis
  78915. * @default 0
  78916. */
  78917. this.indexForwardAxis = typeof(options.indexForwardAxis) !== 'undefined' ? options.indexForwardAxis : 0;
  78918. /**
  78919. * Index of the up axis, 0=x, 1=y, 2=z
  78920. * @property {integer} indexUpAxis
  78921. * @default 2
  78922. */
  78923. this.indexUpAxis = typeof(options.indexUpAxis) !== 'undefined' ? options.indexUpAxis : 2;
  78924. }
  78925. var tmpVec1 = new Vec3();
  78926. var tmpVec2 = new Vec3();
  78927. var tmpVec3 = new Vec3();
  78928. var tmpVec4 = new Vec3();
  78929. var tmpVec5 = new Vec3();
  78930. var tmpVec6 = new Vec3();
  78931. var tmpRay = new Ray();
  78932. /**
  78933. * Add a wheel. For information about the options, see WheelInfo.
  78934. * @method addWheel
  78935. * @param {object} [options]
  78936. */
  78937. RaycastVehicle.prototype.addWheel = function(options){
  78938. options = options || {};
  78939. var info = new WheelInfo(options);
  78940. var index = this.wheelInfos.length;
  78941. this.wheelInfos.push(info);
  78942. return index;
  78943. };
  78944. /**
  78945. * Set the steering value of a wheel.
  78946. * @method setSteeringValue
  78947. * @param {number} value
  78948. * @param {integer} wheelIndex
  78949. */
  78950. RaycastVehicle.prototype.setSteeringValue = function(value, wheelIndex){
  78951. var wheel = this.wheelInfos[wheelIndex];
  78952. wheel.steering = value;
  78953. };
  78954. var torque = new Vec3();
  78955. /**
  78956. * Set the wheel force to apply on one of the wheels each time step
  78957. * @method applyEngineForce
  78958. * @param {number} value
  78959. * @param {integer} wheelIndex
  78960. */
  78961. RaycastVehicle.prototype.applyEngineForce = function(value, wheelIndex){
  78962. this.wheelInfos[wheelIndex].engineForce = value;
  78963. };
  78964. /**
  78965. * Set the braking force of a wheel
  78966. * @method setBrake
  78967. * @param {number} brake
  78968. * @param {integer} wheelIndex
  78969. */
  78970. RaycastVehicle.prototype.setBrake = function(brake, wheelIndex){
  78971. this.wheelInfos[wheelIndex].brake = brake;
  78972. };
  78973. /**
  78974. * Add the vehicle including its constraints to the world.
  78975. * @method addToWorld
  78976. * @param {World} world
  78977. */
  78978. RaycastVehicle.prototype.addToWorld = function(world){
  78979. var constraints = this.constraints;
  78980. world.add(this.chassisBody);
  78981. var that = this;
  78982. this.preStepCallback = function(){
  78983. that.updateVehicle(world.dt);
  78984. };
  78985. world.addEventListener('preStep', this.preStepCallback);
  78986. this.world = world;
  78987. };
  78988. /**
  78989. * Get one of the wheel axles, world-oriented.
  78990. * @private
  78991. * @method getVehicleAxisWorld
  78992. * @param {integer} axisIndex
  78993. * @param {Vec3} result
  78994. */
  78995. RaycastVehicle.prototype.getVehicleAxisWorld = function(axisIndex, result){
  78996. result.set(
  78997. axisIndex === 0 ? 1 : 0,
  78998. axisIndex === 1 ? 1 : 0,
  78999. axisIndex === 2 ? 1 : 0
  79000. );
  79001. this.chassisBody.vectorToWorldFrame(result, result);
  79002. };
  79003. RaycastVehicle.prototype.updateVehicle = function(timeStep){
  79004. var wheelInfos = this.wheelInfos;
  79005. var numWheels = wheelInfos.length;
  79006. var chassisBody = this.chassisBody;
  79007. for (var i = 0; i < numWheels; i++) {
  79008. this.updateWheelTransform(i);
  79009. }
  79010. this.currentVehicleSpeedKmHour = 3.6 * chassisBody.velocity.norm();
  79011. var forwardWorld = new Vec3();
  79012. this.getVehicleAxisWorld(this.indexForwardAxis, forwardWorld);
  79013. if (forwardWorld.dot(chassisBody.velocity) < 0){
  79014. this.currentVehicleSpeedKmHour *= -1;
  79015. }
  79016. // simulate suspension
  79017. for (var i = 0; i < numWheels; i++) {
  79018. this.castRay(wheelInfos[i]);
  79019. }
  79020. this.updateSuspension(timeStep);
  79021. var impulse = new Vec3();
  79022. var relpos = new Vec3();
  79023. for (var i = 0; i < numWheels; i++) {
  79024. //apply suspension force
  79025. var wheel = wheelInfos[i];
  79026. var suspensionForce = wheel.suspensionForce;
  79027. if (suspensionForce > wheel.maxSuspensionForce) {
  79028. suspensionForce = wheel.maxSuspensionForce;
  79029. }
  79030. wheel.raycastResult.hitNormalWorld.scale(suspensionForce * timeStep, impulse);
  79031. wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, relpos);
  79032. chassisBody.applyImpulse(impulse, wheel.raycastResult.hitPointWorld/*relpos*/);
  79033. }
  79034. this.updateFriction(timeStep);
  79035. var hitNormalWorldScaledWithProj = new Vec3();
  79036. var fwd = new Vec3();
  79037. var vel = new Vec3();
  79038. for (i = 0; i < numWheels; i++) {
  79039. var wheel = wheelInfos[i];
  79040. //var relpos = new Vec3();
  79041. //wheel.chassisConnectionPointWorld.vsub(chassisBody.position, relpos);
  79042. chassisBody.getVelocityAtWorldPoint(wheel.chassisConnectionPointWorld, vel);
  79043. // Hack to get the rotation in the correct direction
  79044. var m = 1;
  79045. switch(this.indexUpAxis){
  79046. case 1:
  79047. m = -1;
  79048. break;
  79049. }
  79050. if (wheel.isInContact) {
  79051. this.getVehicleAxisWorld(this.indexForwardAxis, fwd);
  79052. var proj = fwd.dot(wheel.raycastResult.hitNormalWorld);
  79053. wheel.raycastResult.hitNormalWorld.scale(proj, hitNormalWorldScaledWithProj);
  79054. fwd.vsub(hitNormalWorldScaledWithProj, fwd);
  79055. var proj2 = fwd.dot(vel);
  79056. wheel.deltaRotation = m * proj2 * timeStep / wheel.radius;
  79057. }
  79058. if((wheel.sliding || !wheel.isInContact) && wheel.engineForce !== 0 && wheel.useCustomSlidingRotationalSpeed){
  79059. // Apply custom rotation when accelerating and sliding
  79060. wheel.deltaRotation = (wheel.engineForce > 0 ? 1 : -1) * wheel.customSlidingRotationalSpeed * timeStep;
  79061. }
  79062. // Lock wheels
  79063. if(Math.abs(wheel.brake) > Math.abs(wheel.engineForce)){
  79064. wheel.deltaRotation = 0;
  79065. }
  79066. wheel.rotation += wheel.deltaRotation; // Use the old value
  79067. wheel.deltaRotation *= 0.99; // damping of rotation when not in contact
  79068. }
  79069. };
  79070. RaycastVehicle.prototype.updateSuspension = function(deltaTime) {
  79071. var chassisBody = this.chassisBody;
  79072. var chassisMass = chassisBody.mass;
  79073. var wheelInfos = this.wheelInfos;
  79074. var numWheels = wheelInfos.length;
  79075. for (var w_it = 0; w_it < numWheels; w_it++){
  79076. var wheel = wheelInfos[w_it];
  79077. if (wheel.isInContact){
  79078. var force;
  79079. // Spring
  79080. var susp_length = wheel.suspensionRestLength;
  79081. var current_length = wheel.suspensionLength;
  79082. var length_diff = (susp_length - current_length);
  79083. force = wheel.suspensionStiffness * length_diff * wheel.clippedInvContactDotSuspension;
  79084. // Damper
  79085. var projected_rel_vel = wheel.suspensionRelativeVelocity;
  79086. var susp_damping;
  79087. if (projected_rel_vel < 0) {
  79088. susp_damping = wheel.dampingCompression;
  79089. } else {
  79090. susp_damping = wheel.dampingRelaxation;
  79091. }
  79092. force -= susp_damping * projected_rel_vel;
  79093. wheel.suspensionForce = force * chassisMass;
  79094. if (wheel.suspensionForce < 0) {
  79095. wheel.suspensionForce = 0;
  79096. }
  79097. } else {
  79098. wheel.suspensionForce = 0;
  79099. }
  79100. }
  79101. };
  79102. /**
  79103. * Remove the vehicle including its constraints from the world.
  79104. * @method removeFromWorld
  79105. * @param {World} world
  79106. */
  79107. RaycastVehicle.prototype.removeFromWorld = function(world){
  79108. var constraints = this.constraints;
  79109. world.remove(this.chassisBody);
  79110. world.removeEventListener('preStep', this.preStepCallback);
  79111. this.world = null;
  79112. };
  79113. var castRay_rayvector = new Vec3();
  79114. var castRay_target = new Vec3();
  79115. RaycastVehicle.prototype.castRay = function(wheel) {
  79116. var rayvector = castRay_rayvector;
  79117. var target = castRay_target;
  79118. this.updateWheelTransformWorld(wheel);
  79119. var chassisBody = this.chassisBody;
  79120. var depth = -1;
  79121. var raylen = wheel.suspensionRestLength + wheel.radius;
  79122. wheel.directionWorld.scale(raylen, rayvector);
  79123. var source = wheel.chassisConnectionPointWorld;
  79124. source.vadd(rayvector, target);
  79125. var raycastResult = wheel.raycastResult;
  79126. var param = 0;
  79127. raycastResult.reset();
  79128. // Turn off ray collision with the chassis temporarily
  79129. var oldState = chassisBody.collisionResponse;
  79130. chassisBody.collisionResponse = false;
  79131. // Cast ray against world
  79132. this.world.rayTest(source, target, raycastResult);
  79133. chassisBody.collisionResponse = oldState;
  79134. var object = raycastResult.body;
  79135. wheel.raycastResult.groundObject = 0;
  79136. if (object) {
  79137. depth = raycastResult.distance;
  79138. wheel.raycastResult.hitNormalWorld = raycastResult.hitNormalWorld;
  79139. wheel.isInContact = true;
  79140. var hitDistance = raycastResult.distance;
  79141. wheel.suspensionLength = hitDistance - wheel.radius;
  79142. // clamp on max suspension travel
  79143. var minSuspensionLength = wheel.suspensionRestLength - wheel.maxSuspensionTravel;
  79144. var maxSuspensionLength = wheel.suspensionRestLength + wheel.maxSuspensionTravel;
  79145. if (wheel.suspensionLength < minSuspensionLength) {
  79146. wheel.suspensionLength = minSuspensionLength;
  79147. }
  79148. if (wheel.suspensionLength > maxSuspensionLength) {
  79149. wheel.suspensionLength = maxSuspensionLength;
  79150. wheel.raycastResult.reset();
  79151. }
  79152. var denominator = wheel.raycastResult.hitNormalWorld.dot(wheel.directionWorld);
  79153. var chassis_velocity_at_contactPoint = new Vec3();
  79154. chassisBody.getVelocityAtWorldPoint(wheel.raycastResult.hitPointWorld, chassis_velocity_at_contactPoint);
  79155. var projVel = wheel.raycastResult.hitNormalWorld.dot( chassis_velocity_at_contactPoint );
  79156. if (denominator >= -0.1) {
  79157. wheel.suspensionRelativeVelocity = 0;
  79158. wheel.clippedInvContactDotSuspension = 1 / 0.1;
  79159. } else {
  79160. var inv = -1 / denominator;
  79161. wheel.suspensionRelativeVelocity = projVel * inv;
  79162. wheel.clippedInvContactDotSuspension = inv;
  79163. }
  79164. } else {
  79165. //put wheel info as in rest position
  79166. wheel.suspensionLength = wheel.suspensionRestLength + 0 * wheel.maxSuspensionTravel;
  79167. wheel.suspensionRelativeVelocity = 0.0;
  79168. wheel.directionWorld.scale(-1, wheel.raycastResult.hitNormalWorld);
  79169. wheel.clippedInvContactDotSuspension = 1.0;
  79170. }
  79171. return depth;
  79172. };
  79173. RaycastVehicle.prototype.updateWheelTransformWorld = function(wheel){
  79174. wheel.isInContact = false;
  79175. var chassisBody = this.chassisBody;
  79176. chassisBody.pointToWorldFrame(wheel.chassisConnectionPointLocal, wheel.chassisConnectionPointWorld);
  79177. chassisBody.vectorToWorldFrame(wheel.directionLocal, wheel.directionWorld);
  79178. chassisBody.vectorToWorldFrame(wheel.axleLocal, wheel.axleWorld);
  79179. };
  79180. /**
  79181. * Update one of the wheel transform.
  79182. * 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.
  79183. * @method updateWheelTransform
  79184. * @param {integer} wheelIndex The wheel index to update.
  79185. */
  79186. RaycastVehicle.prototype.updateWheelTransform = function(wheelIndex){
  79187. var up = tmpVec4;
  79188. var right = tmpVec5;
  79189. var fwd = tmpVec6;
  79190. var wheel = this.wheelInfos[wheelIndex];
  79191. this.updateWheelTransformWorld(wheel);
  79192. wheel.directionLocal.scale(-1, up);
  79193. right.copy(wheel.axleLocal);
  79194. up.cross(right, fwd);
  79195. fwd.normalize();
  79196. right.normalize();
  79197. // Rotate around steering over the wheelAxle
  79198. var steering = wheel.steering;
  79199. var steeringOrn = new Quaternion();
  79200. steeringOrn.setFromAxisAngle(up, steering);
  79201. var rotatingOrn = new Quaternion();
  79202. rotatingOrn.setFromAxisAngle(right, wheel.rotation);
  79203. // World rotation of the wheel
  79204. var q = wheel.worldTransform.quaternion;
  79205. this.chassisBody.quaternion.mult(steeringOrn, q);
  79206. q.mult(rotatingOrn, q);
  79207. q.normalize();
  79208. // world position of the wheel
  79209. var p = wheel.worldTransform.position;
  79210. p.copy(wheel.directionWorld);
  79211. p.scale(wheel.suspensionLength, p);
  79212. p.vadd(wheel.chassisConnectionPointWorld, p);
  79213. };
  79214. var directions = [
  79215. new Vec3(1, 0, 0),
  79216. new Vec3(0, 1, 0),
  79217. new Vec3(0, 0, 1)
  79218. ];
  79219. /**
  79220. * Get the world transform of one of the wheels
  79221. * @method getWheelTransformWorld
  79222. * @param {integer} wheelIndex
  79223. * @return {Transform}
  79224. */
  79225. RaycastVehicle.prototype.getWheelTransformWorld = function(wheelIndex) {
  79226. return this.wheelInfos[wheelIndex].worldTransform;
  79227. };
  79228. var updateFriction_surfNormalWS_scaled_proj = new Vec3();
  79229. var updateFriction_axle = [];
  79230. var updateFriction_forwardWS = [];
  79231. var sideFrictionStiffness2 = 1;
  79232. RaycastVehicle.prototype.updateFriction = function(timeStep) {
  79233. var surfNormalWS_scaled_proj = updateFriction_surfNormalWS_scaled_proj;
  79234. //calculate the impulse, so that the wheels don't move sidewards
  79235. var wheelInfos = this.wheelInfos;
  79236. var numWheels = wheelInfos.length;
  79237. var chassisBody = this.chassisBody;
  79238. var forwardWS = updateFriction_forwardWS;
  79239. var axle = updateFriction_axle;
  79240. var numWheelsOnGround = 0;
  79241. for (var i = 0; i < numWheels; i++) {
  79242. var wheel = wheelInfos[i];
  79243. var groundObject = wheel.raycastResult.body;
  79244. if (groundObject){
  79245. numWheelsOnGround++;
  79246. }
  79247. wheel.sideImpulse = 0;
  79248. wheel.forwardImpulse = 0;
  79249. if(!forwardWS[i]){
  79250. forwardWS[i] = new Vec3();
  79251. }
  79252. if(!axle[i]){
  79253. axle[i] = new Vec3();
  79254. }
  79255. }
  79256. for (var i = 0; i < numWheels; i++){
  79257. var wheel = wheelInfos[i];
  79258. var groundObject = wheel.raycastResult.body;
  79259. if (groundObject) {
  79260. var axlei = axle[i];
  79261. var wheelTrans = this.getWheelTransformWorld(i);
  79262. // Get world axle
  79263. wheelTrans.vectorToWorldFrame(directions[this.indexRightAxis], axlei);
  79264. var surfNormalWS = wheel.raycastResult.hitNormalWorld;
  79265. var proj = axlei.dot(surfNormalWS);
  79266. surfNormalWS.scale(proj, surfNormalWS_scaled_proj);
  79267. axlei.vsub(surfNormalWS_scaled_proj, axlei);
  79268. axlei.normalize();
  79269. surfNormalWS.cross(axlei, forwardWS[i]);
  79270. forwardWS[i].normalize();
  79271. wheel.sideImpulse = resolveSingleBilateral(
  79272. chassisBody,
  79273. wheel.raycastResult.hitPointWorld,
  79274. groundObject,
  79275. wheel.raycastResult.hitPointWorld,
  79276. axlei
  79277. );
  79278. wheel.sideImpulse *= sideFrictionStiffness2;
  79279. }
  79280. }
  79281. var sideFactor = 1;
  79282. var fwdFactor = 0.5;
  79283. this.sliding = false;
  79284. for (var i = 0; i < numWheels; i++) {
  79285. var wheel = wheelInfos[i];
  79286. var groundObject = wheel.raycastResult.body;
  79287. var rollingFriction = 0;
  79288. wheel.slipInfo = 1;
  79289. if (groundObject) {
  79290. var defaultRollingFrictionImpulse = 0;
  79291. var maxImpulse = wheel.brake ? wheel.brake : defaultRollingFrictionImpulse;
  79292. // btWheelContactPoint contactPt(chassisBody,groundObject,wheelInfraycastInfo.hitPointWorld,forwardWS[wheel],maxImpulse);
  79293. // rollingFriction = calcRollingFriction(contactPt);
  79294. rollingFriction = calcRollingFriction(chassisBody, groundObject, wheel.raycastResult.hitPointWorld, forwardWS[i], maxImpulse);
  79295. rollingFriction += wheel.engineForce * timeStep;
  79296. // rollingFriction = 0;
  79297. var factor = maxImpulse / rollingFriction;
  79298. wheel.slipInfo *= factor;
  79299. }
  79300. //switch between active rolling (throttle), braking and non-active rolling friction (nthrottle/break)
  79301. wheel.forwardImpulse = 0;
  79302. wheel.skidInfo = 1;
  79303. if (groundObject) {
  79304. wheel.skidInfo = 1;
  79305. var maximp = wheel.suspensionForce * timeStep * wheel.frictionSlip;
  79306. var maximpSide = maximp;
  79307. var maximpSquared = maximp * maximpSide;
  79308. wheel.forwardImpulse = rollingFriction;//wheelInfo.engineForce* timeStep;
  79309. var x = wheel.forwardImpulse * fwdFactor;
  79310. var y = wheel.sideImpulse * sideFactor;
  79311. var impulseSquared = x * x + y * y;
  79312. wheel.sliding = false;
  79313. if (impulseSquared > maximpSquared) {
  79314. this.sliding = true;
  79315. wheel.sliding = true;
  79316. var factor = maximp / Math.sqrt(impulseSquared);
  79317. wheel.skidInfo *= factor;
  79318. }
  79319. }
  79320. }
  79321. if (this.sliding) {
  79322. for (var i = 0; i < numWheels; i++) {
  79323. var wheel = wheelInfos[i];
  79324. if (wheel.sideImpulse !== 0) {
  79325. if (wheel.skidInfo < 1){
  79326. wheel.forwardImpulse *= wheel.skidInfo;
  79327. wheel.sideImpulse *= wheel.skidInfo;
  79328. }
  79329. }
  79330. }
  79331. }
  79332. // apply the impulses
  79333. for (var i = 0; i < numWheels; i++) {
  79334. var wheel = wheelInfos[i];
  79335. var rel_pos = new Vec3();
  79336. //wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, rel_pos);
  79337. // cannons applyimpulse is using world coord for the position
  79338. rel_pos.copy(wheel.raycastResult.hitPointWorld);
  79339. if (wheel.forwardImpulse !== 0) {
  79340. var impulse = new Vec3();
  79341. forwardWS[i].scale(wheel.forwardImpulse, impulse);
  79342. chassisBody.applyImpulse(impulse, rel_pos);
  79343. }
  79344. if (wheel.sideImpulse !== 0){
  79345. var groundObject = wheel.raycastResult.body;
  79346. var rel_pos2 = new Vec3();
  79347. //wheel.raycastResult.hitPointWorld.vsub(groundObject.position, rel_pos2);
  79348. rel_pos2.copy(wheel.raycastResult.hitPointWorld);
  79349. var sideImp = new Vec3();
  79350. axle[i].scale(wheel.sideImpulse, sideImp);
  79351. // Scale the relative position in the up direction with rollInfluence.
  79352. // 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).
  79353. chassisBody.pointToLocalFrame(rel_pos, rel_pos);
  79354. rel_pos['xyz'[this.indexUpAxis]] *= wheel.rollInfluence;
  79355. chassisBody.pointToWorldFrame(rel_pos, rel_pos);
  79356. chassisBody.applyImpulse(sideImp, rel_pos);
  79357. //apply friction impulse on the ground
  79358. sideImp.scale(-1, sideImp);
  79359. groundObject.applyImpulse(sideImp, rel_pos2);
  79360. }
  79361. }
  79362. };
  79363. var calcRollingFriction_vel1 = new Vec3();
  79364. var calcRollingFriction_vel2 = new Vec3();
  79365. var calcRollingFriction_vel = new Vec3();
  79366. function calcRollingFriction(body0, body1, frictionPosWorld, frictionDirectionWorld, maxImpulse) {
  79367. var j1 = 0;
  79368. var contactPosWorld = frictionPosWorld;
  79369. // var rel_pos1 = new Vec3();
  79370. // var rel_pos2 = new Vec3();
  79371. var vel1 = calcRollingFriction_vel1;
  79372. var vel2 = calcRollingFriction_vel2;
  79373. var vel = calcRollingFriction_vel;
  79374. // contactPosWorld.vsub(body0.position, rel_pos1);
  79375. // contactPosWorld.vsub(body1.position, rel_pos2);
  79376. body0.getVelocityAtWorldPoint(contactPosWorld, vel1);
  79377. body1.getVelocityAtWorldPoint(contactPosWorld, vel2);
  79378. vel1.vsub(vel2, vel);
  79379. var vrel = frictionDirectionWorld.dot(vel);
  79380. var denom0 = computeImpulseDenominator(body0, frictionPosWorld, frictionDirectionWorld);
  79381. var denom1 = computeImpulseDenominator(body1, frictionPosWorld, frictionDirectionWorld);
  79382. var relaxation = 1;
  79383. var jacDiagABInv = relaxation / (denom0 + denom1);
  79384. // calculate j that moves us to zero relative velocity
  79385. j1 = -vrel * jacDiagABInv;
  79386. if (maxImpulse < j1) {
  79387. j1 = maxImpulse;
  79388. }
  79389. if (j1 < -maxImpulse) {
  79390. j1 = -maxImpulse;
  79391. }
  79392. return j1;
  79393. }
  79394. var computeImpulseDenominator_r0 = new Vec3();
  79395. var computeImpulseDenominator_c0 = new Vec3();
  79396. var computeImpulseDenominator_vec = new Vec3();
  79397. var computeImpulseDenominator_m = new Vec3();
  79398. function computeImpulseDenominator(body, pos, normal) {
  79399. var r0 = computeImpulseDenominator_r0;
  79400. var c0 = computeImpulseDenominator_c0;
  79401. var vec = computeImpulseDenominator_vec;
  79402. var m = computeImpulseDenominator_m;
  79403. pos.vsub(body.position, r0);
  79404. r0.cross(normal, c0);
  79405. body.invInertiaWorld.vmult(c0, m);
  79406. m.cross(r0, vec);
  79407. return body.invMass + normal.dot(vec);
  79408. }
  79409. var resolveSingleBilateral_vel1 = new Vec3();
  79410. var resolveSingleBilateral_vel2 = new Vec3();
  79411. var resolveSingleBilateral_vel = new Vec3();
  79412. //bilateral constraint between two dynamic objects
  79413. function resolveSingleBilateral(body1, pos1, body2, pos2, normal, impulse){
  79414. var normalLenSqr = normal.norm2();
  79415. if (normalLenSqr > 1.1){
  79416. return 0; // no impulse
  79417. }
  79418. // var rel_pos1 = new Vec3();
  79419. // var rel_pos2 = new Vec3();
  79420. // pos1.vsub(body1.position, rel_pos1);
  79421. // pos2.vsub(body2.position, rel_pos2);
  79422. var vel1 = resolveSingleBilateral_vel1;
  79423. var vel2 = resolveSingleBilateral_vel2;
  79424. var vel = resolveSingleBilateral_vel;
  79425. body1.getVelocityAtWorldPoint(pos1, vel1);
  79426. body2.getVelocityAtWorldPoint(pos2, vel2);
  79427. vel1.vsub(vel2, vel);
  79428. var rel_vel = normal.dot(vel);
  79429. var contactDamping = 0.2;
  79430. var massTerm = 1 / (body1.invMass + body2.invMass);
  79431. var impulse = - contactDamping * rel_vel * massTerm;
  79432. return impulse;
  79433. }
  79434. },{"../collision/Ray":9,"../collision/RaycastResult":10,"../math/Quaternion":28,"../math/Vec3":30,"../objects/WheelInfo":36,"./Body":31}],33:[function(_dereq_,module,exports){
  79435. var Body = _dereq_('./Body');
  79436. var Sphere = _dereq_('../shapes/Sphere');
  79437. var Box = _dereq_('../shapes/Box');
  79438. var Vec3 = _dereq_('../math/Vec3');
  79439. var HingeConstraint = _dereq_('../constraints/HingeConstraint');
  79440. module.exports = RigidVehicle;
  79441. /**
  79442. * Simple vehicle helper class with spherical rigid body wheels.
  79443. * @class RigidVehicle
  79444. * @constructor
  79445. * @param {Body} [options.chassisBody]
  79446. */
  79447. function RigidVehicle(options){
  79448. this.wheelBodies = [];
  79449. /**
  79450. * @property coordinateSystem
  79451. * @type {Vec3}
  79452. */
  79453. this.coordinateSystem = typeof(options.coordinateSystem)==='undefined' ? new Vec3(1, 2, 3) : options.coordinateSystem.clone();
  79454. /**
  79455. * @property {Body} chassisBody
  79456. */
  79457. this.chassisBody = options.chassisBody;
  79458. if(!this.chassisBody){
  79459. // No chassis body given. Create it!
  79460. var chassisShape = new Box(new Vec3(5, 2, 0.5));
  79461. this.chassisBody = new Body(1, chassisShape);
  79462. }
  79463. /**
  79464. * @property constraints
  79465. * @type {Array}
  79466. */
  79467. this.constraints = [];
  79468. this.wheelAxes = [];
  79469. this.wheelForces = [];
  79470. }
  79471. /**
  79472. * Add a wheel
  79473. * @method addWheel
  79474. * @param {object} options
  79475. * @param {boolean} [options.isFrontWheel]
  79476. * @param {Vec3} [options.position] Position of the wheel, locally in the chassis body.
  79477. * @param {Vec3} [options.direction] Slide direction of the wheel along the suspension.
  79478. * @param {Vec3} [options.axis] Axis of rotation of the wheel, locally defined in the chassis.
  79479. * @param {Body} [options.body] The wheel body.
  79480. */
  79481. RigidVehicle.prototype.addWheel = function(options){
  79482. options = options || {};
  79483. var wheelBody = options.body;
  79484. if(!wheelBody){
  79485. wheelBody = new Body(1, new Sphere(1.2));
  79486. }
  79487. this.wheelBodies.push(wheelBody);
  79488. this.wheelForces.push(0);
  79489. // Position constrain wheels
  79490. var zero = new Vec3();
  79491. var position = typeof(options.position) !== 'undefined' ? options.position.clone() : new Vec3();
  79492. // Set position locally to the chassis
  79493. var worldPosition = new Vec3();
  79494. this.chassisBody.pointToWorldFrame(position, worldPosition);
  79495. wheelBody.position.set(worldPosition.x, worldPosition.y, worldPosition.z);
  79496. // Constrain wheel
  79497. var axis = typeof(options.axis) !== 'undefined' ? options.axis.clone() : new Vec3(0, 1, 0);
  79498. this.wheelAxes.push(axis);
  79499. var hingeConstraint = new HingeConstraint(this.chassisBody, wheelBody, {
  79500. pivotA: position,
  79501. axisA: axis,
  79502. pivotB: Vec3.ZERO,
  79503. axisB: axis,
  79504. collideConnected: false
  79505. });
  79506. this.constraints.push(hingeConstraint);
  79507. return this.wheelBodies.length - 1;
  79508. };
  79509. /**
  79510. * Set the steering value of a wheel.
  79511. * @method setSteeringValue
  79512. * @param {number} value
  79513. * @param {integer} wheelIndex
  79514. * @todo check coordinateSystem
  79515. */
  79516. RigidVehicle.prototype.setSteeringValue = function(value, wheelIndex){
  79517. // Set angle of the hinge axis
  79518. var axis = this.wheelAxes[wheelIndex];
  79519. var c = Math.cos(value),
  79520. s = Math.sin(value),
  79521. x = axis.x,
  79522. y = axis.y;
  79523. this.constraints[wheelIndex].axisA.set(
  79524. c*x -s*y,
  79525. s*x +c*y,
  79526. 0
  79527. );
  79528. };
  79529. /**
  79530. * Set the target rotational speed of the hinge constraint.
  79531. * @method setMotorSpeed
  79532. * @param {number} value
  79533. * @param {integer} wheelIndex
  79534. */
  79535. RigidVehicle.prototype.setMotorSpeed = function(value, wheelIndex){
  79536. var hingeConstraint = this.constraints[wheelIndex];
  79537. hingeConstraint.enableMotor();
  79538. hingeConstraint.motorTargetVelocity = value;
  79539. };
  79540. /**
  79541. * Set the target rotational speed of the hinge constraint.
  79542. * @method disableMotor
  79543. * @param {number} value
  79544. * @param {integer} wheelIndex
  79545. */
  79546. RigidVehicle.prototype.disableMotor = function(wheelIndex){
  79547. var hingeConstraint = this.constraints[wheelIndex];
  79548. hingeConstraint.disableMotor();
  79549. };
  79550. var torque = new Vec3();
  79551. /**
  79552. * Set the wheel force to apply on one of the wheels each time step
  79553. * @method setWheelForce
  79554. * @param {number} value
  79555. * @param {integer} wheelIndex
  79556. */
  79557. RigidVehicle.prototype.setWheelForce = function(value, wheelIndex){
  79558. this.wheelForces[wheelIndex] = value;
  79559. };
  79560. /**
  79561. * Apply a torque on one of the wheels.
  79562. * @method applyWheelForce
  79563. * @param {number} value
  79564. * @param {integer} wheelIndex
  79565. */
  79566. RigidVehicle.prototype.applyWheelForce = function(value, wheelIndex){
  79567. var axis = this.wheelAxes[wheelIndex];
  79568. var wheelBody = this.wheelBodies[wheelIndex];
  79569. var bodyTorque = wheelBody.torque;
  79570. axis.scale(value, torque);
  79571. wheelBody.vectorToWorldFrame(torque, torque);
  79572. bodyTorque.vadd(torque, bodyTorque);
  79573. };
  79574. /**
  79575. * Add the vehicle including its constraints to the world.
  79576. * @method addToWorld
  79577. * @param {World} world
  79578. */
  79579. RigidVehicle.prototype.addToWorld = function(world){
  79580. var constraints = this.constraints;
  79581. var bodies = this.wheelBodies.concat([this.chassisBody]);
  79582. for (var i = 0; i < bodies.length; i++) {
  79583. world.add(bodies[i]);
  79584. }
  79585. for (var i = 0; i < constraints.length; i++) {
  79586. world.addConstraint(constraints[i]);
  79587. }
  79588. world.addEventListener('preStep', this._update.bind(this));
  79589. };
  79590. RigidVehicle.prototype._update = function(){
  79591. var wheelForces = this.wheelForces;
  79592. for (var i = 0; i < wheelForces.length; i++) {
  79593. this.applyWheelForce(wheelForces[i], i);
  79594. }
  79595. };
  79596. /**
  79597. * Remove the vehicle including its constraints from the world.
  79598. * @method removeFromWorld
  79599. * @param {World} world
  79600. */
  79601. RigidVehicle.prototype.removeFromWorld = function(world){
  79602. var constraints = this.constraints;
  79603. var bodies = this.wheelBodies.concat([this.chassisBody]);
  79604. for (var i = 0; i < bodies.length; i++) {
  79605. world.remove(bodies[i]);
  79606. }
  79607. for (var i = 0; i < constraints.length; i++) {
  79608. world.removeConstraint(constraints[i]);
  79609. }
  79610. };
  79611. var worldAxis = new Vec3();
  79612. /**
  79613. * Get current rotational velocity of a wheel
  79614. * @method getWheelSpeed
  79615. * @param {integer} wheelIndex
  79616. */
  79617. RigidVehicle.prototype.getWheelSpeed = function(wheelIndex){
  79618. var axis = this.wheelAxes[wheelIndex];
  79619. var wheelBody = this.wheelBodies[wheelIndex];
  79620. var w = wheelBody.angularVelocity;
  79621. this.chassisBody.vectorToWorldFrame(axis, worldAxis);
  79622. return w.dot(worldAxis);
  79623. };
  79624. },{"../constraints/HingeConstraint":15,"../math/Vec3":30,"../shapes/Box":37,"../shapes/Sphere":44,"./Body":31}],34:[function(_dereq_,module,exports){
  79625. module.exports = SPHSystem;
  79626. var Shape = _dereq_('../shapes/Shape');
  79627. var Vec3 = _dereq_('../math/Vec3');
  79628. var Quaternion = _dereq_('../math/Quaternion');
  79629. var Particle = _dereq_('../shapes/Particle');
  79630. var Body = _dereq_('../objects/Body');
  79631. var Material = _dereq_('../material/Material');
  79632. /**
  79633. * Smoothed-particle hydrodynamics system
  79634. * @class SPHSystem
  79635. * @constructor
  79636. */
  79637. function SPHSystem(){
  79638. this.particles = [];
  79639. /**
  79640. * Density of the system (kg/m3).
  79641. * @property {number} density
  79642. */
  79643. this.density = 1;
  79644. /**
  79645. * Distance below which two particles are considered to be neighbors.
  79646. * It should be adjusted so there are about 15-20 neighbor particles within this radius.
  79647. * @property {number} smoothingRadius
  79648. */
  79649. this.smoothingRadius = 1;
  79650. this.speedOfSound = 1;
  79651. /**
  79652. * Viscosity of the system.
  79653. * @property {number} viscosity
  79654. */
  79655. this.viscosity = 0.01;
  79656. this.eps = 0.000001;
  79657. // Stuff Computed per particle
  79658. this.pressures = [];
  79659. this.densities = [];
  79660. this.neighbors = [];
  79661. }
  79662. /**
  79663. * Add a particle to the system.
  79664. * @method add
  79665. * @param {Body} particle
  79666. */
  79667. SPHSystem.prototype.add = function(particle){
  79668. this.particles.push(particle);
  79669. if(this.neighbors.length < this.particles.length){
  79670. this.neighbors.push([]);
  79671. }
  79672. };
  79673. /**
  79674. * Remove a particle from the system.
  79675. * @method remove
  79676. * @param {Body} particle
  79677. */
  79678. SPHSystem.prototype.remove = function(particle){
  79679. var idx = this.particles.indexOf(particle);
  79680. if(idx !== -1){
  79681. this.particles.splice(idx,1);
  79682. if(this.neighbors.length > this.particles.length){
  79683. this.neighbors.pop();
  79684. }
  79685. }
  79686. };
  79687. /**
  79688. * Get neighbors within smoothing volume, save in the array neighbors
  79689. * @method getNeighbors
  79690. * @param {Body} particle
  79691. * @param {Array} neighbors
  79692. */
  79693. var SPHSystem_getNeighbors_dist = new Vec3();
  79694. SPHSystem.prototype.getNeighbors = function(particle,neighbors){
  79695. var N = this.particles.length,
  79696. id = particle.id,
  79697. R2 = this.smoothingRadius * this.smoothingRadius,
  79698. dist = SPHSystem_getNeighbors_dist;
  79699. for(var i=0; i!==N; i++){
  79700. var p = this.particles[i];
  79701. p.position.vsub(particle.position,dist);
  79702. if(id!==p.id && dist.norm2() < R2){
  79703. neighbors.push(p);
  79704. }
  79705. }
  79706. };
  79707. // Temp vectors for calculation
  79708. var SPHSystem_update_dist = new Vec3(),
  79709. SPHSystem_update_a_pressure = new Vec3(),
  79710. SPHSystem_update_a_visc = new Vec3(),
  79711. SPHSystem_update_gradW = new Vec3(),
  79712. SPHSystem_update_r_vec = new Vec3(),
  79713. SPHSystem_update_u = new Vec3(); // Relative velocity
  79714. SPHSystem.prototype.update = function(){
  79715. var N = this.particles.length,
  79716. dist = SPHSystem_update_dist,
  79717. cs = this.speedOfSound,
  79718. eps = this.eps;
  79719. for(var i=0; i!==N; i++){
  79720. var p = this.particles[i]; // Current particle
  79721. var neighbors = this.neighbors[i];
  79722. // Get neighbors
  79723. neighbors.length = 0;
  79724. this.getNeighbors(p,neighbors);
  79725. neighbors.push(this.particles[i]); // Add current too
  79726. var numNeighbors = neighbors.length;
  79727. // Accumulate density for the particle
  79728. var sum = 0.0;
  79729. for(var j=0; j!==numNeighbors; j++){
  79730. //printf("Current particle has position %f %f %f\n",objects[id].pos.x(),objects[id].pos.y(),objects[id].pos.z());
  79731. p.position.vsub(neighbors[j].position, dist);
  79732. var len = dist.norm();
  79733. var weight = this.w(len);
  79734. sum += neighbors[j].mass * weight;
  79735. }
  79736. // Save
  79737. this.densities[i] = sum;
  79738. this.pressures[i] = cs * cs * (this.densities[i] - this.density);
  79739. }
  79740. // Add forces
  79741. // Sum to these accelerations
  79742. var a_pressure= SPHSystem_update_a_pressure;
  79743. var a_visc = SPHSystem_update_a_visc;
  79744. var gradW = SPHSystem_update_gradW;
  79745. var r_vec = SPHSystem_update_r_vec;
  79746. var u = SPHSystem_update_u;
  79747. for(var i=0; i!==N; i++){
  79748. var particle = this.particles[i];
  79749. a_pressure.set(0,0,0);
  79750. a_visc.set(0,0,0);
  79751. // Init vars
  79752. var Pij;
  79753. var nabla;
  79754. var Vij;
  79755. // Sum up for all other neighbors
  79756. var neighbors = this.neighbors[i];
  79757. var numNeighbors = neighbors.length;
  79758. //printf("Neighbors: ");
  79759. for(var j=0; j!==numNeighbors; j++){
  79760. var neighbor = neighbors[j];
  79761. //printf("%d ",nj);
  79762. // Get r once for all..
  79763. particle.position.vsub(neighbor.position,r_vec);
  79764. var r = r_vec.norm();
  79765. // Pressure contribution
  79766. Pij = -neighbor.mass * (this.pressures[i] / (this.densities[i]*this.densities[i] + eps) + this.pressures[j] / (this.densities[j]*this.densities[j] + eps));
  79767. this.gradw(r_vec, gradW);
  79768. // Add to pressure acceleration
  79769. gradW.mult(Pij , gradW);
  79770. a_pressure.vadd(gradW, a_pressure);
  79771. // Viscosity contribution
  79772. neighbor.velocity.vsub(particle.velocity, u);
  79773. u.mult( 1.0 / (0.0001+this.densities[i] * this.densities[j]) * this.viscosity * neighbor.mass , u );
  79774. nabla = this.nablaw(r);
  79775. u.mult(nabla,u);
  79776. // Add to viscosity acceleration
  79777. a_visc.vadd( u, a_visc );
  79778. }
  79779. // Calculate force
  79780. a_visc.mult(particle.mass, a_visc);
  79781. a_pressure.mult(particle.mass, a_pressure);
  79782. // Add force to particles
  79783. particle.force.vadd(a_visc, particle.force);
  79784. particle.force.vadd(a_pressure, particle.force);
  79785. }
  79786. };
  79787. // Calculate the weight using the W(r) weightfunction
  79788. SPHSystem.prototype.w = function(r){
  79789. // 315
  79790. var h = this.smoothingRadius;
  79791. return 315.0/(64.0*Math.PI*Math.pow(h,9)) * Math.pow(h*h-r*r,3);
  79792. };
  79793. // calculate gradient of the weight function
  79794. SPHSystem.prototype.gradw = function(rVec,resultVec){
  79795. var r = rVec.norm(),
  79796. h = this.smoothingRadius;
  79797. rVec.mult(945.0/(32.0*Math.PI*Math.pow(h,9)) * Math.pow((h*h-r*r),2) , resultVec);
  79798. };
  79799. // Calculate nabla(W)
  79800. SPHSystem.prototype.nablaw = function(r){
  79801. var h = this.smoothingRadius;
  79802. var nabla = 945.0/(32.0*Math.PI*Math.pow(h,9)) * (h*h-r*r)*(7*r*r - 3*h*h);
  79803. return nabla;
  79804. };
  79805. },{"../material/Material":25,"../math/Quaternion":28,"../math/Vec3":30,"../objects/Body":31,"../shapes/Particle":41,"../shapes/Shape":43}],35:[function(_dereq_,module,exports){
  79806. var Vec3 = _dereq_('../math/Vec3');
  79807. module.exports = Spring;
  79808. /**
  79809. * A spring, connecting two bodies.
  79810. *
  79811. * @class Spring
  79812. * @constructor
  79813. * @param {Body} bodyA
  79814. * @param {Body} bodyB
  79815. * @param {Object} [options]
  79816. * @param {number} [options.restLength] A number > 0. Default: 1
  79817. * @param {number} [options.stiffness] A number >= 0. Default: 100
  79818. * @param {number} [options.damping] A number >= 0. Default: 1
  79819. * @param {Vec3} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates.
  79820. * @param {Vec3} [options.worldAnchorB]
  79821. * @param {Vec3} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates.
  79822. * @param {Vec3} [options.localAnchorB]
  79823. */
  79824. function Spring(bodyA,bodyB,options){
  79825. options = options || {};
  79826. /**
  79827. * Rest length of the spring.
  79828. * @property restLength
  79829. * @type {number}
  79830. */
  79831. this.restLength = typeof(options.restLength) === "number" ? options.restLength : 1;
  79832. /**
  79833. * Stiffness of the spring.
  79834. * @property stiffness
  79835. * @type {number}
  79836. */
  79837. this.stiffness = options.stiffness || 100;
  79838. /**
  79839. * Damping of the spring.
  79840. * @property damping
  79841. * @type {number}
  79842. */
  79843. this.damping = options.damping || 1;
  79844. /**
  79845. * First connected body.
  79846. * @property bodyA
  79847. * @type {Body}
  79848. */
  79849. this.bodyA = bodyA;
  79850. /**
  79851. * Second connected body.
  79852. * @property bodyB
  79853. * @type {Body}
  79854. */
  79855. this.bodyB = bodyB;
  79856. /**
  79857. * Anchor for bodyA in local bodyA coordinates.
  79858. * @property localAnchorA
  79859. * @type {Vec3}
  79860. */
  79861. this.localAnchorA = new Vec3();
  79862. /**
  79863. * Anchor for bodyB in local bodyB coordinates.
  79864. * @property localAnchorB
  79865. * @type {Vec3}
  79866. */
  79867. this.localAnchorB = new Vec3();
  79868. if(options.localAnchorA){
  79869. this.localAnchorA.copy(options.localAnchorA);
  79870. }
  79871. if(options.localAnchorB){
  79872. this.localAnchorB.copy(options.localAnchorB);
  79873. }
  79874. if(options.worldAnchorA){
  79875. this.setWorldAnchorA(options.worldAnchorA);
  79876. }
  79877. if(options.worldAnchorB){
  79878. this.setWorldAnchorB(options.worldAnchorB);
  79879. }
  79880. }
  79881. /**
  79882. * Set the anchor point on body A, using world coordinates.
  79883. * @method setWorldAnchorA
  79884. * @param {Vec3} worldAnchorA
  79885. */
  79886. Spring.prototype.setWorldAnchorA = function(worldAnchorA){
  79887. this.bodyA.pointToLocalFrame(worldAnchorA,this.localAnchorA);
  79888. };
  79889. /**
  79890. * Set the anchor point on body B, using world coordinates.
  79891. * @method setWorldAnchorB
  79892. * @param {Vec3} worldAnchorB
  79893. */
  79894. Spring.prototype.setWorldAnchorB = function(worldAnchorB){
  79895. this.bodyB.pointToLocalFrame(worldAnchorB,this.localAnchorB);
  79896. };
  79897. /**
  79898. * Get the anchor point on body A, in world coordinates.
  79899. * @method getWorldAnchorA
  79900. * @param {Vec3} result The vector to store the result in.
  79901. */
  79902. Spring.prototype.getWorldAnchorA = function(result){
  79903. this.bodyA.pointToWorldFrame(this.localAnchorA,result);
  79904. };
  79905. /**
  79906. * Get the anchor point on body B, in world coordinates.
  79907. * @method getWorldAnchorB
  79908. * @param {Vec3} result The vector to store the result in.
  79909. */
  79910. Spring.prototype.getWorldAnchorB = function(result){
  79911. this.bodyB.pointToWorldFrame(this.localAnchorB,result);
  79912. };
  79913. var applyForce_r = new Vec3(),
  79914. applyForce_r_unit = new Vec3(),
  79915. applyForce_u = new Vec3(),
  79916. applyForce_f = new Vec3(),
  79917. applyForce_worldAnchorA = new Vec3(),
  79918. applyForce_worldAnchorB = new Vec3(),
  79919. applyForce_ri = new Vec3(),
  79920. applyForce_rj = new Vec3(),
  79921. applyForce_ri_x_f = new Vec3(),
  79922. applyForce_rj_x_f = new Vec3(),
  79923. applyForce_tmp = new Vec3();
  79924. /**
  79925. * Apply the spring force to the connected bodies.
  79926. * @method applyForce
  79927. */
  79928. Spring.prototype.applyForce = function(){
  79929. var k = this.stiffness,
  79930. d = this.damping,
  79931. l = this.restLength,
  79932. bodyA = this.bodyA,
  79933. bodyB = this.bodyB,
  79934. r = applyForce_r,
  79935. r_unit = applyForce_r_unit,
  79936. u = applyForce_u,
  79937. f = applyForce_f,
  79938. tmp = applyForce_tmp;
  79939. var worldAnchorA = applyForce_worldAnchorA,
  79940. worldAnchorB = applyForce_worldAnchorB,
  79941. ri = applyForce_ri,
  79942. rj = applyForce_rj,
  79943. ri_x_f = applyForce_ri_x_f,
  79944. rj_x_f = applyForce_rj_x_f;
  79945. // Get world anchors
  79946. this.getWorldAnchorA(worldAnchorA);
  79947. this.getWorldAnchorB(worldAnchorB);
  79948. // Get offset points
  79949. worldAnchorA.vsub(bodyA.position,ri);
  79950. worldAnchorB.vsub(bodyB.position,rj);
  79951. // Compute distance vector between world anchor points
  79952. worldAnchorB.vsub(worldAnchorA,r);
  79953. var rlen = r.norm();
  79954. r_unit.copy(r);
  79955. r_unit.normalize();
  79956. // Compute relative velocity of the anchor points, u
  79957. bodyB.velocity.vsub(bodyA.velocity,u);
  79958. // Add rotational velocity
  79959. bodyB.angularVelocity.cross(rj,tmp);
  79960. u.vadd(tmp,u);
  79961. bodyA.angularVelocity.cross(ri,tmp);
  79962. u.vsub(tmp,u);
  79963. // F = - k * ( x - L ) - D * ( u )
  79964. r_unit.mult(-k*(rlen-l) - d*u.dot(r_unit), f);
  79965. // Add forces to bodies
  79966. bodyA.force.vsub(f,bodyA.force);
  79967. bodyB.force.vadd(f,bodyB.force);
  79968. // Angular force
  79969. ri.cross(f,ri_x_f);
  79970. rj.cross(f,rj_x_f);
  79971. bodyA.torque.vsub(ri_x_f,bodyA.torque);
  79972. bodyB.torque.vadd(rj_x_f,bodyB.torque);
  79973. };
  79974. },{"../math/Vec3":30}],36:[function(_dereq_,module,exports){
  79975. var Vec3 = _dereq_('../math/Vec3');
  79976. var Transform = _dereq_('../math/Transform');
  79977. var RaycastResult = _dereq_('../collision/RaycastResult');
  79978. var Utils = _dereq_('../utils/Utils');
  79979. module.exports = WheelInfo;
  79980. /**
  79981. * @class WheelInfo
  79982. * @constructor
  79983. * @param {Object} [options]
  79984. *
  79985. * @param {Vec3} [options.chassisConnectionPointLocal]
  79986. * @param {Vec3} [options.chassisConnectionPointWorld]
  79987. * @param {Vec3} [options.directionLocal]
  79988. * @param {Vec3} [options.directionWorld]
  79989. * @param {Vec3} [options.axleLocal]
  79990. * @param {Vec3} [options.axleWorld]
  79991. * @param {number} [options.suspensionRestLength=1]
  79992. * @param {number} [options.suspensionMaxLength=2]
  79993. * @param {number} [options.radius=1]
  79994. * @param {number} [options.suspensionStiffness=100]
  79995. * @param {number} [options.dampingCompression=10]
  79996. * @param {number} [options.dampingRelaxation=10]
  79997. * @param {number} [options.frictionSlip=10000]
  79998. * @param {number} [options.steering=0]
  79999. * @param {number} [options.rotation=0]
  80000. * @param {number} [options.deltaRotation=0]
  80001. * @param {number} [options.rollInfluence=0.01]
  80002. * @param {number} [options.maxSuspensionForce]
  80003. * @param {boolean} [options.isFrontWheel=true]
  80004. * @param {number} [options.clippedInvContactDotSuspension=1]
  80005. * @param {number} [options.suspensionRelativeVelocity=0]
  80006. * @param {number} [options.suspensionForce=0]
  80007. * @param {number} [options.skidInfo=0]
  80008. * @param {number} [options.suspensionLength=0]
  80009. * @param {number} [options.maxSuspensionTravel=1]
  80010. * @param {boolean} [options.useCustomSlidingRotationalSpeed=false]
  80011. * @param {number} [options.customSlidingRotationalSpeed=-0.1]
  80012. */
  80013. function WheelInfo(options){
  80014. options = Utils.defaults(options, {
  80015. chassisConnectionPointLocal: new Vec3(),
  80016. chassisConnectionPointWorld: new Vec3(),
  80017. directionLocal: new Vec3(),
  80018. directionWorld: new Vec3(),
  80019. axleLocal: new Vec3(),
  80020. axleWorld: new Vec3(),
  80021. suspensionRestLength: 1,
  80022. suspensionMaxLength: 2,
  80023. radius: 1,
  80024. suspensionStiffness: 100,
  80025. dampingCompression: 10,
  80026. dampingRelaxation: 10,
  80027. frictionSlip: 10000,
  80028. steering: 0,
  80029. rotation: 0,
  80030. deltaRotation: 0,
  80031. rollInfluence: 0.01,
  80032. maxSuspensionForce: Number.MAX_VALUE,
  80033. isFrontWheel: true,
  80034. clippedInvContactDotSuspension: 1,
  80035. suspensionRelativeVelocity: 0,
  80036. suspensionForce: 0,
  80037. skidInfo: 0,
  80038. suspensionLength: 0,
  80039. maxSuspensionTravel: 1,
  80040. useCustomSlidingRotationalSpeed: false,
  80041. customSlidingRotationalSpeed: -0.1
  80042. });
  80043. /**
  80044. * Max travel distance of the suspension, in meters.
  80045. * @property {number} maxSuspensionTravel
  80046. */
  80047. this.maxSuspensionTravel = options.maxSuspensionTravel;
  80048. /**
  80049. * Speed to apply to the wheel rotation when the wheel is sliding.
  80050. * @property {number} customSlidingRotationalSpeed
  80051. */
  80052. this.customSlidingRotationalSpeed = options.customSlidingRotationalSpeed;
  80053. /**
  80054. * If the customSlidingRotationalSpeed should be used.
  80055. * @property {Boolean} useCustomSlidingRotationalSpeed
  80056. */
  80057. this.useCustomSlidingRotationalSpeed = options.useCustomSlidingRotationalSpeed;
  80058. /**
  80059. * @property {Boolean} sliding
  80060. */
  80061. this.sliding = false;
  80062. /**
  80063. * Connection point, defined locally in the chassis body frame.
  80064. * @property {Vec3} chassisConnectionPointLocal
  80065. */
  80066. this.chassisConnectionPointLocal = options.chassisConnectionPointLocal.clone();
  80067. /**
  80068. * @property {Vec3} chassisConnectionPointWorld
  80069. */
  80070. this.chassisConnectionPointWorld = options.chassisConnectionPointWorld.clone();
  80071. /**
  80072. * @property {Vec3} directionLocal
  80073. */
  80074. this.directionLocal = options.directionLocal.clone();
  80075. /**
  80076. * @property {Vec3} directionWorld
  80077. */
  80078. this.directionWorld = options.directionWorld.clone();
  80079. /**
  80080. * @property {Vec3} axleLocal
  80081. */
  80082. this.axleLocal = options.axleLocal.clone();
  80083. /**
  80084. * @property {Vec3} axleWorld
  80085. */
  80086. this.axleWorld = options.axleWorld.clone();
  80087. /**
  80088. * @property {number} suspensionRestLength
  80089. */
  80090. this.suspensionRestLength = options.suspensionRestLength;
  80091. /**
  80092. * @property {number} suspensionMaxLength
  80093. */
  80094. this.suspensionMaxLength = options.suspensionMaxLength;
  80095. /**
  80096. * @property {number} radius
  80097. */
  80098. this.radius = options.radius;
  80099. /**
  80100. * @property {number} suspensionStiffness
  80101. */
  80102. this.suspensionStiffness = options.suspensionStiffness;
  80103. /**
  80104. * @property {number} dampingCompression
  80105. */
  80106. this.dampingCompression = options.dampingCompression;
  80107. /**
  80108. * @property {number} dampingRelaxation
  80109. */
  80110. this.dampingRelaxation = options.dampingRelaxation;
  80111. /**
  80112. * @property {number} frictionSlip
  80113. */
  80114. this.frictionSlip = options.frictionSlip;
  80115. /**
  80116. * @property {number} steering
  80117. */
  80118. this.steering = 0;
  80119. /**
  80120. * Rotation value, in radians.
  80121. * @property {number} rotation
  80122. */
  80123. this.rotation = 0;
  80124. /**
  80125. * @property {number} deltaRotation
  80126. */
  80127. this.deltaRotation = 0;
  80128. /**
  80129. * @property {number} rollInfluence
  80130. */
  80131. this.rollInfluence = options.rollInfluence;
  80132. /**
  80133. * @property {number} maxSuspensionForce
  80134. */
  80135. this.maxSuspensionForce = options.maxSuspensionForce;
  80136. /**
  80137. * @property {number} engineForce
  80138. */
  80139. this.engineForce = 0;
  80140. /**
  80141. * @property {number} brake
  80142. */
  80143. this.brake = 0;
  80144. /**
  80145. * @property {number} isFrontWheel
  80146. */
  80147. this.isFrontWheel = options.isFrontWheel;
  80148. /**
  80149. * @property {number} clippedInvContactDotSuspension
  80150. */
  80151. this.clippedInvContactDotSuspension = 1;
  80152. /**
  80153. * @property {number} suspensionRelativeVelocity
  80154. */
  80155. this.suspensionRelativeVelocity = 0;
  80156. /**
  80157. * @property {number} suspensionForce
  80158. */
  80159. this.suspensionForce = 0;
  80160. /**
  80161. * @property {number} skidInfo
  80162. */
  80163. this.skidInfo = 0;
  80164. /**
  80165. * @property {number} suspensionLength
  80166. */
  80167. this.suspensionLength = 0;
  80168. /**
  80169. * @property {number} sideImpulse
  80170. */
  80171. this.sideImpulse = 0;
  80172. /**
  80173. * @property {number} forwardImpulse
  80174. */
  80175. this.forwardImpulse = 0;
  80176. /**
  80177. * The result from raycasting
  80178. * @property {RaycastResult} raycastResult
  80179. */
  80180. this.raycastResult = new RaycastResult();
  80181. /**
  80182. * Wheel world transform
  80183. * @property {Transform} worldTransform
  80184. */
  80185. this.worldTransform = new Transform();
  80186. /**
  80187. * @property {boolean} isInContact
  80188. */
  80189. this.isInContact = false;
  80190. }
  80191. var chassis_velocity_at_contactPoint = new Vec3();
  80192. var relpos = new Vec3();
  80193. var chassis_velocity_at_contactPoint = new Vec3();
  80194. WheelInfo.prototype.updateWheel = function(chassis){
  80195. var raycastResult = this.raycastResult;
  80196. if (this.isInContact){
  80197. var project= raycastResult.hitNormalWorld.dot(raycastResult.directionWorld);
  80198. raycastResult.hitPointWorld.vsub(chassis.position, relpos);
  80199. chassis.getVelocityAtWorldPoint(relpos, chassis_velocity_at_contactPoint);
  80200. var projVel = raycastResult.hitNormalWorld.dot( chassis_velocity_at_contactPoint );
  80201. if (project >= -0.1) {
  80202. this.suspensionRelativeVelocity = 0.0;
  80203. this.clippedInvContactDotSuspension = 1.0 / 0.1;
  80204. } else {
  80205. var inv = -1 / project;
  80206. this.suspensionRelativeVelocity = projVel * inv;
  80207. this.clippedInvContactDotSuspension = inv;
  80208. }
  80209. } else {
  80210. // Not in contact : position wheel in a nice (rest length) position
  80211. raycastResult.suspensionLength = this.suspensionRestLength;
  80212. this.suspensionRelativeVelocity = 0.0;
  80213. raycastResult.directionWorld.scale(-1, raycastResult.hitNormalWorld);
  80214. this.clippedInvContactDotSuspension = 1.0;
  80215. }
  80216. };
  80217. },{"../collision/RaycastResult":10,"../math/Transform":29,"../math/Vec3":30,"../utils/Utils":53}],37:[function(_dereq_,module,exports){
  80218. module.exports = Box;
  80219. var Shape = _dereq_('./Shape');
  80220. var Vec3 = _dereq_('../math/Vec3');
  80221. var ConvexPolyhedron = _dereq_('./ConvexPolyhedron');
  80222. /**
  80223. * A 3d box shape.
  80224. * @class Box
  80225. * @constructor
  80226. * @param {Vec3} halfExtents
  80227. * @author schteppe
  80228. * @extends Shape
  80229. */
  80230. function Box(halfExtents){
  80231. Shape.call(this);
  80232. this.type = Shape.types.BOX;
  80233. /**
  80234. * @property halfExtents
  80235. * @type {Vec3}
  80236. */
  80237. this.halfExtents = halfExtents;
  80238. /**
  80239. * Used by the contact generator to make contacts with other convex polyhedra for example
  80240. * @property convexPolyhedronRepresentation
  80241. * @type {ConvexPolyhedron}
  80242. */
  80243. this.convexPolyhedronRepresentation = null;
  80244. this.updateConvexPolyhedronRepresentation();
  80245. this.updateBoundingSphereRadius();
  80246. }
  80247. Box.prototype = new Shape();
  80248. Box.prototype.constructor = Box;
  80249. /**
  80250. * Updates the local convex polyhedron representation used for some collisions.
  80251. * @method updateConvexPolyhedronRepresentation
  80252. */
  80253. Box.prototype.updateConvexPolyhedronRepresentation = function(){
  80254. var sx = this.halfExtents.x;
  80255. var sy = this.halfExtents.y;
  80256. var sz = this.halfExtents.z;
  80257. var V = Vec3;
  80258. var vertices = [
  80259. new V(-sx,-sy,-sz),
  80260. new V( sx,-sy,-sz),
  80261. new V( sx, sy,-sz),
  80262. new V(-sx, sy,-sz),
  80263. new V(-sx,-sy, sz),
  80264. new V( sx,-sy, sz),
  80265. new V( sx, sy, sz),
  80266. new V(-sx, sy, sz)
  80267. ];
  80268. var indices = [
  80269. [3,2,1,0], // -z
  80270. [4,5,6,7], // +z
  80271. [5,4,0,1], // -y
  80272. [2,3,7,6], // +y
  80273. [0,4,7,3], // -x
  80274. [1,2,6,5], // +x
  80275. ];
  80276. var axes = [
  80277. new V(0, 0, 1),
  80278. new V(0, 1, 0),
  80279. new V(1, 0, 0)
  80280. ];
  80281. var h = new ConvexPolyhedron(vertices, indices);
  80282. this.convexPolyhedronRepresentation = h;
  80283. h.material = this.material;
  80284. };
  80285. /**
  80286. * @method calculateLocalInertia
  80287. * @param {Number} mass
  80288. * @param {Vec3} target
  80289. * @return {Vec3}
  80290. */
  80291. Box.prototype.calculateLocalInertia = function(mass,target){
  80292. target = target || new Vec3();
  80293. Box.calculateInertia(this.halfExtents, mass, target);
  80294. return target;
  80295. };
  80296. Box.calculateInertia = function(halfExtents,mass,target){
  80297. var e = halfExtents;
  80298. target.x = 1.0 / 12.0 * mass * ( 2*e.y*2*e.y + 2*e.z*2*e.z );
  80299. target.y = 1.0 / 12.0 * mass * ( 2*e.x*2*e.x + 2*e.z*2*e.z );
  80300. target.z = 1.0 / 12.0 * mass * ( 2*e.y*2*e.y + 2*e.x*2*e.x );
  80301. };
  80302. /**
  80303. * Get the box 6 side normals
  80304. * @method getSideNormals
  80305. * @param {array} sixTargetVectors An array of 6 vectors, to store the resulting side normals in.
  80306. * @param {Quaternion} quat Orientation to apply to the normal vectors. If not provided, the vectors will be in respect to the local frame.
  80307. * @return {array}
  80308. */
  80309. Box.prototype.getSideNormals = function(sixTargetVectors,quat){
  80310. var sides = sixTargetVectors;
  80311. var ex = this.halfExtents;
  80312. sides[0].set( ex.x, 0, 0);
  80313. sides[1].set( 0, ex.y, 0);
  80314. sides[2].set( 0, 0, ex.z);
  80315. sides[3].set( -ex.x, 0, 0);
  80316. sides[4].set( 0, -ex.y, 0);
  80317. sides[5].set( 0, 0, -ex.z);
  80318. if(quat!==undefined){
  80319. for(var i=0; i!==sides.length; i++){
  80320. quat.vmult(sides[i],sides[i]);
  80321. }
  80322. }
  80323. return sides;
  80324. };
  80325. Box.prototype.volume = function(){
  80326. return 8.0 * this.halfExtents.x * this.halfExtents.y * this.halfExtents.z;
  80327. };
  80328. Box.prototype.updateBoundingSphereRadius = function(){
  80329. this.boundingSphereRadius = this.halfExtents.norm();
  80330. };
  80331. var worldCornerTempPos = new Vec3();
  80332. var worldCornerTempNeg = new Vec3();
  80333. Box.prototype.forEachWorldCorner = function(pos,quat,callback){
  80334. var e = this.halfExtents;
  80335. var corners = [[ e.x, e.y, e.z],
  80336. [ -e.x, e.y, e.z],
  80337. [ -e.x, -e.y, e.z],
  80338. [ -e.x, -e.y, -e.z],
  80339. [ e.x, -e.y, -e.z],
  80340. [ e.x, e.y, -e.z],
  80341. [ -e.x, e.y, -e.z],
  80342. [ e.x, -e.y, e.z]];
  80343. for(var i=0; i<corners.length; i++){
  80344. worldCornerTempPos.set(corners[i][0],corners[i][1],corners[i][2]);
  80345. quat.vmult(worldCornerTempPos,worldCornerTempPos);
  80346. pos.vadd(worldCornerTempPos,worldCornerTempPos);
  80347. callback(worldCornerTempPos.x,
  80348. worldCornerTempPos.y,
  80349. worldCornerTempPos.z);
  80350. }
  80351. };
  80352. var worldCornersTemp = [
  80353. new Vec3(),
  80354. new Vec3(),
  80355. new Vec3(),
  80356. new Vec3(),
  80357. new Vec3(),
  80358. new Vec3(),
  80359. new Vec3(),
  80360. new Vec3()
  80361. ];
  80362. Box.prototype.calculateWorldAABB = function(pos,quat,min,max){
  80363. var e = this.halfExtents;
  80364. worldCornersTemp[0].set(e.x, e.y, e.z);
  80365. worldCornersTemp[1].set(-e.x, e.y, e.z);
  80366. worldCornersTemp[2].set(-e.x, -e.y, e.z);
  80367. worldCornersTemp[3].set(-e.x, -e.y, -e.z);
  80368. worldCornersTemp[4].set(e.x, -e.y, -e.z);
  80369. worldCornersTemp[5].set(e.x, e.y, -e.z);
  80370. worldCornersTemp[6].set(-e.x, e.y, -e.z);
  80371. worldCornersTemp[7].set(e.x, -e.y, e.z);
  80372. var wc = worldCornersTemp[0];
  80373. quat.vmult(wc, wc);
  80374. pos.vadd(wc, wc);
  80375. max.copy(wc);
  80376. min.copy(wc);
  80377. for(var i=1; i<8; i++){
  80378. var wc = worldCornersTemp[i];
  80379. quat.vmult(wc, wc);
  80380. pos.vadd(wc, wc);
  80381. var x = wc.x;
  80382. var y = wc.y;
  80383. var z = wc.z;
  80384. if(x > max.x){
  80385. max.x = x;
  80386. }
  80387. if(y > max.y){
  80388. max.y = y;
  80389. }
  80390. if(z > max.z){
  80391. max.z = z;
  80392. }
  80393. if(x < min.x){
  80394. min.x = x;
  80395. }
  80396. if(y < min.y){
  80397. min.y = y;
  80398. }
  80399. if(z < min.z){
  80400. min.z = z;
  80401. }
  80402. }
  80403. // Get each axis max
  80404. // min.set(Infinity,Infinity,Infinity);
  80405. // max.set(-Infinity,-Infinity,-Infinity);
  80406. // this.forEachWorldCorner(pos,quat,function(x,y,z){
  80407. // if(x > max.x){
  80408. // max.x = x;
  80409. // }
  80410. // if(y > max.y){
  80411. // max.y = y;
  80412. // }
  80413. // if(z > max.z){
  80414. // max.z = z;
  80415. // }
  80416. // if(x < min.x){
  80417. // min.x = x;
  80418. // }
  80419. // if(y < min.y){
  80420. // min.y = y;
  80421. // }
  80422. // if(z < min.z){
  80423. // min.z = z;
  80424. // }
  80425. // });
  80426. };
  80427. },{"../math/Vec3":30,"./ConvexPolyhedron":38,"./Shape":43}],38:[function(_dereq_,module,exports){
  80428. module.exports = ConvexPolyhedron;
  80429. var Shape = _dereq_('./Shape');
  80430. var Vec3 = _dereq_('../math/Vec3');
  80431. var Quaternion = _dereq_('../math/Quaternion');
  80432. var Transform = _dereq_('../math/Transform');
  80433. /**
  80434. * A set of polygons describing a convex shape.
  80435. * @class ConvexPolyhedron
  80436. * @constructor
  80437. * @extends Shape
  80438. * @description The shape MUST be convex for the code to work properly. No polygons may be coplanar (contained
  80439. * in the same 3D plane), instead these should be merged into one polygon.
  80440. *
  80441. * @param {array} points An array of Vec3's
  80442. * @param {array} faces Array of integer arrays, describing which vertices that is included in each face.
  80443. *
  80444. * @author qiao / https://github.com/qiao (original author, see https://github.com/qiao/three.js/commit/85026f0c769e4000148a67d45a9e9b9c5108836f)
  80445. * @author schteppe / https://github.com/schteppe
  80446. * @see http://www.altdevblogaday.com/2011/05/13/contact-generation-between-3d-convex-meshes/
  80447. * @see http://bullet.googlecode.com/svn/trunk/src/BulletCollision/NarrowPhaseCollision/btPolyhedralContactClipping.cpp
  80448. *
  80449. * @todo Move the clipping functions to ContactGenerator?
  80450. * @todo Automatically merge coplanar polygons in constructor.
  80451. */
  80452. function ConvexPolyhedron(points, faces, uniqueAxes) {
  80453. var that = this;
  80454. Shape.call(this);
  80455. this.type = Shape.types.CONVEXPOLYHEDRON;
  80456. /**
  80457. * Array of Vec3
  80458. * @property vertices
  80459. * @type {Array}
  80460. */
  80461. this.vertices = points||[];
  80462. this.worldVertices = []; // World transformed version of .vertices
  80463. this.worldVerticesNeedsUpdate = true;
  80464. /**
  80465. * Array of integer arrays, indicating which vertices each face consists of
  80466. * @property faces
  80467. * @type {Array}
  80468. */
  80469. this.faces = faces||[];
  80470. /**
  80471. * Array of Vec3
  80472. * @property faceNormals
  80473. * @type {Array}
  80474. */
  80475. this.faceNormals = [];
  80476. this.computeNormals();
  80477. this.worldFaceNormalsNeedsUpdate = true;
  80478. this.worldFaceNormals = []; // World transformed version of .faceNormals
  80479. /**
  80480. * Array of Vec3
  80481. * @property uniqueEdges
  80482. * @type {Array}
  80483. */
  80484. this.uniqueEdges = [];
  80485. /**
  80486. * If given, these locally defined, normalized axes are the only ones being checked when doing separating axis check.
  80487. * @property {Array} uniqueAxes
  80488. */
  80489. this.uniqueAxes = uniqueAxes ? uniqueAxes.slice() : null;
  80490. this.computeEdges();
  80491. this.updateBoundingSphereRadius();
  80492. }
  80493. ConvexPolyhedron.prototype = new Shape();
  80494. ConvexPolyhedron.prototype.constructor = ConvexPolyhedron;
  80495. var computeEdges_tmpEdge = new Vec3();
  80496. /**
  80497. * Computes uniqueEdges
  80498. * @method computeEdges
  80499. */
  80500. ConvexPolyhedron.prototype.computeEdges = function(){
  80501. var faces = this.faces;
  80502. var vertices = this.vertices;
  80503. var nv = vertices.length;
  80504. var edges = this.uniqueEdges;
  80505. edges.length = 0;
  80506. var edge = computeEdges_tmpEdge;
  80507. for(var i=0; i !== faces.length; i++){
  80508. var face = faces[i];
  80509. var numVertices = face.length;
  80510. for(var j = 0; j !== numVertices; j++){
  80511. var k = ( j+1 ) % numVertices;
  80512. vertices[face[j]].vsub(vertices[face[k]], edge);
  80513. edge.normalize();
  80514. var found = false;
  80515. for(var p=0; p !== edges.length; p++){
  80516. if (edges[p].almostEquals(edge) || edges[p].almostEquals(edge)){
  80517. found = true;
  80518. break;
  80519. }
  80520. }
  80521. if (!found){
  80522. edges.push(edge.clone());
  80523. }
  80524. }
  80525. }
  80526. };
  80527. /**
  80528. * Compute the normals of the faces. Will reuse existing Vec3 objects in the .faceNormals array if they exist.
  80529. * @method computeNormals
  80530. */
  80531. ConvexPolyhedron.prototype.computeNormals = function(){
  80532. this.faceNormals.length = this.faces.length;
  80533. // Generate normals
  80534. for(var i=0; i<this.faces.length; i++){
  80535. // Check so all vertices exists for this face
  80536. for(var j=0; j<this.faces[i].length; j++){
  80537. if(!this.vertices[this.faces[i][j]]){
  80538. throw new Error("Vertex "+this.faces[i][j]+" not found!");
  80539. }
  80540. }
  80541. var n = this.faceNormals[i] || new Vec3();
  80542. this.getFaceNormal(i,n);
  80543. n.negate(n);
  80544. this.faceNormals[i] = n;
  80545. var vertex = this.vertices[this.faces[i][0]];
  80546. if(n.dot(vertex) < 0){
  80547. 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.");
  80548. for(var j=0; j<this.faces[i].length; j++){
  80549. console.warn(".vertices["+this.faces[i][j]+"] = Vec3("+this.vertices[this.faces[i][j]].toString()+")");
  80550. }
  80551. }
  80552. }
  80553. };
  80554. /**
  80555. * Get face normal given 3 vertices
  80556. * @static
  80557. * @method getFaceNormal
  80558. * @param {Vec3} va
  80559. * @param {Vec3} vb
  80560. * @param {Vec3} vc
  80561. * @param {Vec3} target
  80562. */
  80563. var cb = new Vec3();
  80564. var ab = new Vec3();
  80565. ConvexPolyhedron.computeNormal = function ( va, vb, vc, target ) {
  80566. vb.vsub(va,ab);
  80567. vc.vsub(vb,cb);
  80568. cb.cross(ab,target);
  80569. if ( !target.isZero() ) {
  80570. target.normalize();
  80571. }
  80572. };
  80573. /**
  80574. * Compute the normal of a face from its vertices
  80575. * @method getFaceNormal
  80576. * @param {Number} i
  80577. * @param {Vec3} target
  80578. */
  80579. ConvexPolyhedron.prototype.getFaceNormal = function(i,target){
  80580. var f = this.faces[i];
  80581. var va = this.vertices[f[0]];
  80582. var vb = this.vertices[f[1]];
  80583. var vc = this.vertices[f[2]];
  80584. return ConvexPolyhedron.computeNormal(va,vb,vc,target);
  80585. };
  80586. /**
  80587. * @method clipAgainstHull
  80588. * @param {Vec3} posA
  80589. * @param {Quaternion} quatA
  80590. * @param {ConvexPolyhedron} hullB
  80591. * @param {Vec3} posB
  80592. * @param {Quaternion} quatB
  80593. * @param {Vec3} separatingNormal
  80594. * @param {Number} minDist Clamp distance
  80595. * @param {Number} maxDist
  80596. * @param {array} result The an array of contact point objects, see clipFaceAgainstHull
  80597. * @see http://bullet.googlecode.com/svn/trunk/src/BulletCollision/NarrowPhaseCollision/btPolyhedralContactClipping.cpp
  80598. */
  80599. var cah_WorldNormal = new Vec3();
  80600. ConvexPolyhedron.prototype.clipAgainstHull = function(posA,quatA,hullB,posB,quatB,separatingNormal,minDist,maxDist,result){
  80601. var WorldNormal = cah_WorldNormal;
  80602. var hullA = this;
  80603. var curMaxDist = maxDist;
  80604. var closestFaceB = -1;
  80605. var dmax = -Number.MAX_VALUE;
  80606. for(var face=0; face < hullB.faces.length; face++){
  80607. WorldNormal.copy(hullB.faceNormals[face]);
  80608. quatB.vmult(WorldNormal,WorldNormal);
  80609. //posB.vadd(WorldNormal,WorldNormal);
  80610. var d = WorldNormal.dot(separatingNormal);
  80611. if (d > dmax){
  80612. dmax = d;
  80613. closestFaceB = face;
  80614. }
  80615. }
  80616. var worldVertsB1 = [];
  80617. var polyB = hullB.faces[closestFaceB];
  80618. var numVertices = polyB.length;
  80619. for(var e0=0; e0<numVertices; e0++){
  80620. var b = hullB.vertices[polyB[e0]];
  80621. var worldb = new Vec3();
  80622. worldb.copy(b);
  80623. quatB.vmult(worldb,worldb);
  80624. posB.vadd(worldb,worldb);
  80625. worldVertsB1.push(worldb);
  80626. }
  80627. if (closestFaceB>=0){
  80628. this.clipFaceAgainstHull(separatingNormal,
  80629. posA,
  80630. quatA,
  80631. worldVertsB1,
  80632. minDist,
  80633. maxDist,
  80634. result);
  80635. }
  80636. };
  80637. /**
  80638. * Find the separating axis between this hull and another
  80639. * @method findSeparatingAxis
  80640. * @param {ConvexPolyhedron} hullB
  80641. * @param {Vec3} posA
  80642. * @param {Quaternion} quatA
  80643. * @param {Vec3} posB
  80644. * @param {Quaternion} quatB
  80645. * @param {Vec3} target The target vector to save the axis in
  80646. * @return {bool} Returns false if a separation is found, else true
  80647. */
  80648. var fsa_faceANormalWS3 = new Vec3(),
  80649. fsa_Worldnormal1 = new Vec3(),
  80650. fsa_deltaC = new Vec3(),
  80651. fsa_worldEdge0 = new Vec3(),
  80652. fsa_worldEdge1 = new Vec3(),
  80653. fsa_Cross = new Vec3();
  80654. ConvexPolyhedron.prototype.findSeparatingAxis = function(hullB,posA,quatA,posB,quatB,target, faceListA, faceListB){
  80655. var faceANormalWS3 = fsa_faceANormalWS3,
  80656. Worldnormal1 = fsa_Worldnormal1,
  80657. deltaC = fsa_deltaC,
  80658. worldEdge0 = fsa_worldEdge0,
  80659. worldEdge1 = fsa_worldEdge1,
  80660. Cross = fsa_Cross;
  80661. var dmin = Number.MAX_VALUE;
  80662. var hullA = this;
  80663. var curPlaneTests=0;
  80664. if(!hullA.uniqueAxes){
  80665. var numFacesA = faceListA ? faceListA.length : hullA.faces.length;
  80666. // Test face normals from hullA
  80667. for(var i=0; i<numFacesA; i++){
  80668. var fi = faceListA ? faceListA[i] : i;
  80669. // Get world face normal
  80670. faceANormalWS3.copy(hullA.faceNormals[fi]);
  80671. quatA.vmult(faceANormalWS3,faceANormalWS3);
  80672. var d = hullA.testSepAxis(faceANormalWS3, hullB, posA, quatA, posB, quatB);
  80673. if(d===false){
  80674. return false;
  80675. }
  80676. if(d<dmin){
  80677. dmin = d;
  80678. target.copy(faceANormalWS3);
  80679. }
  80680. }
  80681. } else {
  80682. // Test unique axes
  80683. for(var i = 0; i !== hullA.uniqueAxes.length; i++){
  80684. // Get world axis
  80685. quatA.vmult(hullA.uniqueAxes[i],faceANormalWS3);
  80686. var d = hullA.testSepAxis(faceANormalWS3, hullB, posA, quatA, posB, quatB);
  80687. if(d===false){
  80688. return false;
  80689. }
  80690. if(d<dmin){
  80691. dmin = d;
  80692. target.copy(faceANormalWS3);
  80693. }
  80694. }
  80695. }
  80696. if(!hullB.uniqueAxes){
  80697. // Test face normals from hullB
  80698. var numFacesB = faceListB ? faceListB.length : hullB.faces.length;
  80699. for(var i=0;i<numFacesB;i++){
  80700. var fi = faceListB ? faceListB[i] : i;
  80701. Worldnormal1.copy(hullB.faceNormals[fi]);
  80702. quatB.vmult(Worldnormal1,Worldnormal1);
  80703. curPlaneTests++;
  80704. var d = hullA.testSepAxis(Worldnormal1, hullB,posA,quatA,posB,quatB);
  80705. if(d===false){
  80706. return false;
  80707. }
  80708. if(d<dmin){
  80709. dmin = d;
  80710. target.copy(Worldnormal1);
  80711. }
  80712. }
  80713. } else {
  80714. // Test unique axes in B
  80715. for(var i = 0; i !== hullB.uniqueAxes.length; i++){
  80716. quatB.vmult(hullB.uniqueAxes[i],Worldnormal1);
  80717. curPlaneTests++;
  80718. var d = hullA.testSepAxis(Worldnormal1, hullB,posA,quatA,posB,quatB);
  80719. if(d===false){
  80720. return false;
  80721. }
  80722. if(d<dmin){
  80723. dmin = d;
  80724. target.copy(Worldnormal1);
  80725. }
  80726. }
  80727. }
  80728. // Test edges
  80729. for(var e0=0; e0 !== hullA.uniqueEdges.length; e0++){
  80730. // Get world edge
  80731. quatA.vmult(hullA.uniqueEdges[e0],worldEdge0);
  80732. for(var e1=0; e1 !== hullB.uniqueEdges.length; e1++){
  80733. // Get world edge 2
  80734. quatB.vmult(hullB.uniqueEdges[e1], worldEdge1);
  80735. worldEdge0.cross(worldEdge1,Cross);
  80736. if(!Cross.almostZero()){
  80737. Cross.normalize();
  80738. var dist = hullA.testSepAxis(Cross, hullB, posA, quatA, posB, quatB);
  80739. if(dist === false){
  80740. return false;
  80741. }
  80742. if(dist < dmin){
  80743. dmin = dist;
  80744. target.copy(Cross);
  80745. }
  80746. }
  80747. }
  80748. }
  80749. posB.vsub(posA,deltaC);
  80750. if((deltaC.dot(target))>0.0){
  80751. target.negate(target);
  80752. }
  80753. return true;
  80754. };
  80755. var maxminA=[], maxminB=[];
  80756. /**
  80757. * Test separating axis against two hulls. Both hulls are projected onto the axis and the overlap size is returned if there is one.
  80758. * @method testSepAxis
  80759. * @param {Vec3} axis
  80760. * @param {ConvexPolyhedron} hullB
  80761. * @param {Vec3} posA
  80762. * @param {Quaternion} quatA
  80763. * @param {Vec3} posB
  80764. * @param {Quaternion} quatB
  80765. * @return {number} The overlap depth, or FALSE if no penetration.
  80766. */
  80767. ConvexPolyhedron.prototype.testSepAxis = function(axis, hullB, posA, quatA, posB, quatB){
  80768. var hullA=this;
  80769. ConvexPolyhedron.project(hullA, axis, posA, quatA, maxminA);
  80770. ConvexPolyhedron.project(hullB, axis, posB, quatB, maxminB);
  80771. var maxA = maxminA[0];
  80772. var minA = maxminA[1];
  80773. var maxB = maxminB[0];
  80774. var minB = maxminB[1];
  80775. if(maxA<minB || maxB<minA){
  80776. return false; // Separated
  80777. }
  80778. var d0 = maxA - minB;
  80779. var d1 = maxB - minA;
  80780. var depth = d0<d1 ? d0:d1;
  80781. return depth;
  80782. };
  80783. var cli_aabbmin = new Vec3(),
  80784. cli_aabbmax = new Vec3();
  80785. /**
  80786. * @method calculateLocalInertia
  80787. * @param {Number} mass
  80788. * @param {Vec3} target
  80789. */
  80790. ConvexPolyhedron.prototype.calculateLocalInertia = function(mass,target){
  80791. // Approximate with box inertia
  80792. // Exact inertia calculation is overkill, but see http://geometrictools.com/Documentation/PolyhedralMassProperties.pdf for the correct way to do it
  80793. this.computeLocalAABB(cli_aabbmin,cli_aabbmax);
  80794. var x = cli_aabbmax.x - cli_aabbmin.x,
  80795. y = cli_aabbmax.y - cli_aabbmin.y,
  80796. z = cli_aabbmax.z - cli_aabbmin.z;
  80797. target.x = 1.0 / 12.0 * mass * ( 2*y*2*y + 2*z*2*z );
  80798. target.y = 1.0 / 12.0 * mass * ( 2*x*2*x + 2*z*2*z );
  80799. target.z = 1.0 / 12.0 * mass * ( 2*y*2*y + 2*x*2*x );
  80800. };
  80801. /**
  80802. * @method getPlaneConstantOfFace
  80803. * @param {Number} face_i Index of the face
  80804. * @return {Number}
  80805. */
  80806. ConvexPolyhedron.prototype.getPlaneConstantOfFace = function(face_i){
  80807. var f = this.faces[face_i];
  80808. var n = this.faceNormals[face_i];
  80809. var v = this.vertices[f[0]];
  80810. var c = -n.dot(v);
  80811. return c;
  80812. };
  80813. /**
  80814. * Clip a face against a hull.
  80815. * @method clipFaceAgainstHull
  80816. * @param {Vec3} separatingNormal
  80817. * @param {Vec3} posA
  80818. * @param {Quaternion} quatA
  80819. * @param {Array} worldVertsB1 An array of Vec3 with vertices in the world frame.
  80820. * @param {Number} minDist Distance clamping
  80821. * @param {Number} maxDist
  80822. * @param Array result Array to store resulting contact points in. Will be objects with properties: point, depth, normal. These are represented in world coordinates.
  80823. */
  80824. var cfah_faceANormalWS = new Vec3(),
  80825. cfah_edge0 = new Vec3(),
  80826. cfah_WorldEdge0 = new Vec3(),
  80827. cfah_worldPlaneAnormal1 = new Vec3(),
  80828. cfah_planeNormalWS1 = new Vec3(),
  80829. cfah_worldA1 = new Vec3(),
  80830. cfah_localPlaneNormal = new Vec3(),
  80831. cfah_planeNormalWS = new Vec3();
  80832. ConvexPolyhedron.prototype.clipFaceAgainstHull = function(separatingNormal, posA, quatA, worldVertsB1, minDist, maxDist,result){
  80833. var faceANormalWS = cfah_faceANormalWS,
  80834. edge0 = cfah_edge0,
  80835. WorldEdge0 = cfah_WorldEdge0,
  80836. worldPlaneAnormal1 = cfah_worldPlaneAnormal1,
  80837. planeNormalWS1 = cfah_planeNormalWS1,
  80838. worldA1 = cfah_worldA1,
  80839. localPlaneNormal = cfah_localPlaneNormal,
  80840. planeNormalWS = cfah_planeNormalWS;
  80841. var hullA = this;
  80842. var worldVertsB2 = [];
  80843. var pVtxIn = worldVertsB1;
  80844. var pVtxOut = worldVertsB2;
  80845. // Find the face with normal closest to the separating axis
  80846. var closestFaceA = -1;
  80847. var dmin = Number.MAX_VALUE;
  80848. for(var face=0; face<hullA.faces.length; face++){
  80849. faceANormalWS.copy(hullA.faceNormals[face]);
  80850. quatA.vmult(faceANormalWS,faceANormalWS);
  80851. //posA.vadd(faceANormalWS,faceANormalWS);
  80852. var d = faceANormalWS.dot(separatingNormal);
  80853. if (d < dmin){
  80854. dmin = d;
  80855. closestFaceA = face;
  80856. }
  80857. }
  80858. if (closestFaceA < 0){
  80859. // console.log("--- did not find any closest face... ---");
  80860. return;
  80861. }
  80862. //console.log("closest A: ",closestFaceA);
  80863. // Get the face and construct connected faces
  80864. var polyA = hullA.faces[closestFaceA];
  80865. polyA.connectedFaces = [];
  80866. for(var i=0; i<hullA.faces.length; i++){
  80867. for(var j=0; j<hullA.faces[i].length; j++){
  80868. 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 */ ){
  80869. polyA.connectedFaces.push(i);
  80870. }
  80871. }
  80872. }
  80873. // Clip the polygon to the back of the planes of all faces of hull A, that are adjacent to the witness face
  80874. var numContacts = pVtxIn.length;
  80875. var numVerticesA = polyA.length;
  80876. var res = [];
  80877. for(var e0=0; e0<numVerticesA; e0++){
  80878. var a = hullA.vertices[polyA[e0]];
  80879. var b = hullA.vertices[polyA[(e0+1)%numVerticesA]];
  80880. a.vsub(b,edge0);
  80881. WorldEdge0.copy(edge0);
  80882. quatA.vmult(WorldEdge0,WorldEdge0);
  80883. posA.vadd(WorldEdge0,WorldEdge0);
  80884. worldPlaneAnormal1.copy(this.faceNormals[closestFaceA]);//transA.getBasis()* btVector3(polyA.m_plane[0],polyA.m_plane[1],polyA.m_plane[2]);
  80885. quatA.vmult(worldPlaneAnormal1,worldPlaneAnormal1);
  80886. posA.vadd(worldPlaneAnormal1,worldPlaneAnormal1);
  80887. WorldEdge0.cross(worldPlaneAnormal1,planeNormalWS1);
  80888. planeNormalWS1.negate(planeNormalWS1);
  80889. worldA1.copy(a);
  80890. quatA.vmult(worldA1,worldA1);
  80891. posA.vadd(worldA1,worldA1);
  80892. var planeEqWS1 = -worldA1.dot(planeNormalWS1);
  80893. var planeEqWS;
  80894. if(true){
  80895. var otherFace = polyA.connectedFaces[e0];
  80896. localPlaneNormal.copy(this.faceNormals[otherFace]);
  80897. var localPlaneEq = this.getPlaneConstantOfFace(otherFace);
  80898. planeNormalWS.copy(localPlaneNormal);
  80899. quatA.vmult(planeNormalWS,planeNormalWS);
  80900. //posA.vadd(planeNormalWS,planeNormalWS);
  80901. var planeEqWS = localPlaneEq - planeNormalWS.dot(posA);
  80902. } else {
  80903. planeNormalWS.copy(planeNormalWS1);
  80904. planeEqWS = planeEqWS1;
  80905. }
  80906. // Clip face against our constructed plane
  80907. this.clipFaceAgainstPlane(pVtxIn, pVtxOut, planeNormalWS, planeEqWS);
  80908. // Throw away all clipped points, but save the reamining until next clip
  80909. while(pVtxIn.length){
  80910. pVtxIn.shift();
  80911. }
  80912. while(pVtxOut.length){
  80913. pVtxIn.push(pVtxOut.shift());
  80914. }
  80915. }
  80916. //console.log("Resulting points after clip:",pVtxIn);
  80917. // only keep contact points that are behind the witness face
  80918. localPlaneNormal.copy(this.faceNormals[closestFaceA]);
  80919. var localPlaneEq = this.getPlaneConstantOfFace(closestFaceA);
  80920. planeNormalWS.copy(localPlaneNormal);
  80921. quatA.vmult(planeNormalWS,planeNormalWS);
  80922. var planeEqWS = localPlaneEq - planeNormalWS.dot(posA);
  80923. for (var i=0; i<pVtxIn.length; i++){
  80924. var depth = planeNormalWS.dot(pVtxIn[i]) + planeEqWS; //???
  80925. /*console.log("depth calc from normal=",planeNormalWS.toString()," and constant "+planeEqWS+" and vertex ",pVtxIn[i].toString()," gives "+depth);*/
  80926. if (depth <=minDist){
  80927. console.log("clamped: depth="+depth+" to minDist="+(minDist+""));
  80928. depth = minDist;
  80929. }
  80930. if (depth <=maxDist){
  80931. var point = pVtxIn[i];
  80932. if(depth<=0){
  80933. /*console.log("Got contact point ",point.toString(),
  80934. ", depth=",depth,
  80935. "contact normal=",separatingNormal.toString(),
  80936. "plane",planeNormalWS.toString(),
  80937. "planeConstant",planeEqWS);*/
  80938. var p = {
  80939. point:point,
  80940. normal:planeNormalWS,
  80941. depth: depth,
  80942. };
  80943. result.push(p);
  80944. }
  80945. }
  80946. }
  80947. };
  80948. /**
  80949. * Clip a face in a hull against the back of a plane.
  80950. * @method clipFaceAgainstPlane
  80951. * @param {Array} inVertices
  80952. * @param {Array} outVertices
  80953. * @param {Vec3} planeNormal
  80954. * @param {Number} planeConstant The constant in the mathematical plane equation
  80955. */
  80956. ConvexPolyhedron.prototype.clipFaceAgainstPlane = function(inVertices,outVertices, planeNormal, planeConstant){
  80957. var n_dot_first, n_dot_last;
  80958. var numVerts = inVertices.length;
  80959. if(numVerts < 2){
  80960. return outVertices;
  80961. }
  80962. var firstVertex = inVertices[inVertices.length-1],
  80963. lastVertex = inVertices[0];
  80964. n_dot_first = planeNormal.dot(firstVertex) + planeConstant;
  80965. for(var vi = 0; vi < numVerts; vi++){
  80966. lastVertex = inVertices[vi];
  80967. n_dot_last = planeNormal.dot(lastVertex) + planeConstant;
  80968. if(n_dot_first < 0){
  80969. if(n_dot_last < 0){
  80970. // Start < 0, end < 0, so output lastVertex
  80971. var newv = new Vec3();
  80972. newv.copy(lastVertex);
  80973. outVertices.push(newv);
  80974. } else {
  80975. // Start < 0, end >= 0, so output intersection
  80976. var newv = new Vec3();
  80977. firstVertex.lerp(lastVertex,
  80978. n_dot_first / (n_dot_first - n_dot_last),
  80979. newv);
  80980. outVertices.push(newv);
  80981. }
  80982. } else {
  80983. if(n_dot_last<0){
  80984. // Start >= 0, end < 0 so output intersection and end
  80985. var newv = new Vec3();
  80986. firstVertex.lerp(lastVertex,
  80987. n_dot_first / (n_dot_first - n_dot_last),
  80988. newv);
  80989. outVertices.push(newv);
  80990. outVertices.push(lastVertex);
  80991. }
  80992. }
  80993. firstVertex = lastVertex;
  80994. n_dot_first = n_dot_last;
  80995. }
  80996. return outVertices;
  80997. };
  80998. // Updates .worldVertices and sets .worldVerticesNeedsUpdate to false.
  80999. ConvexPolyhedron.prototype.computeWorldVertices = function(position,quat){
  81000. var N = this.vertices.length;
  81001. while(this.worldVertices.length < N){
  81002. this.worldVertices.push( new Vec3() );
  81003. }
  81004. var verts = this.vertices,
  81005. worldVerts = this.worldVertices;
  81006. for(var i=0; i!==N; i++){
  81007. quat.vmult( verts[i] , worldVerts[i] );
  81008. position.vadd( worldVerts[i] , worldVerts[i] );
  81009. }
  81010. this.worldVerticesNeedsUpdate = false;
  81011. };
  81012. var computeLocalAABB_worldVert = new Vec3();
  81013. ConvexPolyhedron.prototype.computeLocalAABB = function(aabbmin,aabbmax){
  81014. var n = this.vertices.length,
  81015. vertices = this.vertices,
  81016. worldVert = computeLocalAABB_worldVert;
  81017. aabbmin.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  81018. aabbmax.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  81019. for(var i=0; i<n; i++){
  81020. var v = vertices[i];
  81021. if (v.x < aabbmin.x){
  81022. aabbmin.x = v.x;
  81023. } else if(v.x > aabbmax.x){
  81024. aabbmax.x = v.x;
  81025. }
  81026. if (v.y < aabbmin.y){
  81027. aabbmin.y = v.y;
  81028. } else if(v.y > aabbmax.y){
  81029. aabbmax.y = v.y;
  81030. }
  81031. if (v.z < aabbmin.z){
  81032. aabbmin.z = v.z;
  81033. } else if(v.z > aabbmax.z){
  81034. aabbmax.z = v.z;
  81035. }
  81036. }
  81037. };
  81038. /**
  81039. * Updates .worldVertices and sets .worldVerticesNeedsUpdate to false.
  81040. * @method computeWorldFaceNormals
  81041. * @param {Quaternion} quat
  81042. */
  81043. ConvexPolyhedron.prototype.computeWorldFaceNormals = function(quat){
  81044. var N = this.faceNormals.length;
  81045. while(this.worldFaceNormals.length < N){
  81046. this.worldFaceNormals.push( new Vec3() );
  81047. }
  81048. var normals = this.faceNormals,
  81049. worldNormals = this.worldFaceNormals;
  81050. for(var i=0; i!==N; i++){
  81051. quat.vmult( normals[i] , worldNormals[i] );
  81052. }
  81053. this.worldFaceNormalsNeedsUpdate = false;
  81054. };
  81055. /**
  81056. * @method updateBoundingSphereRadius
  81057. */
  81058. ConvexPolyhedron.prototype.updateBoundingSphereRadius = function(){
  81059. // Assume points are distributed with local (0,0,0) as center
  81060. var max2 = 0;
  81061. var verts = this.vertices;
  81062. for(var i=0, N=verts.length; i!==N; i++) {
  81063. var norm2 = verts[i].norm2();
  81064. if(norm2 > max2){
  81065. max2 = norm2;
  81066. }
  81067. }
  81068. this.boundingSphereRadius = Math.sqrt(max2);
  81069. };
  81070. var tempWorldVertex = new Vec3();
  81071. /**
  81072. * @method calculateWorldAABB
  81073. * @param {Vec3} pos
  81074. * @param {Quaternion} quat
  81075. * @param {Vec3} min
  81076. * @param {Vec3} max
  81077. */
  81078. ConvexPolyhedron.prototype.calculateWorldAABB = function(pos,quat,min,max){
  81079. var n = this.vertices.length, verts = this.vertices;
  81080. var minx,miny,minz,maxx,maxy,maxz;
  81081. for(var i=0; i<n; i++){
  81082. tempWorldVertex.copy(verts[i]);
  81083. quat.vmult(tempWorldVertex,tempWorldVertex);
  81084. pos.vadd(tempWorldVertex,tempWorldVertex);
  81085. var v = tempWorldVertex;
  81086. if (v.x < minx || minx===undefined){
  81087. minx = v.x;
  81088. } else if(v.x > maxx || maxx===undefined){
  81089. maxx = v.x;
  81090. }
  81091. if (v.y < miny || miny===undefined){
  81092. miny = v.y;
  81093. } else if(v.y > maxy || maxy===undefined){
  81094. maxy = v.y;
  81095. }
  81096. if (v.z < minz || minz===undefined){
  81097. minz = v.z;
  81098. } else if(v.z > maxz || maxz===undefined){
  81099. maxz = v.z;
  81100. }
  81101. }
  81102. min.set(minx,miny,minz);
  81103. max.set(maxx,maxy,maxz);
  81104. };
  81105. /**
  81106. * Get approximate convex volume
  81107. * @method volume
  81108. * @return {Number}
  81109. */
  81110. ConvexPolyhedron.prototype.volume = function(){
  81111. return 4.0 * Math.PI * this.boundingSphereRadius / 3.0;
  81112. };
  81113. /**
  81114. * Get an average of all the vertices positions
  81115. * @method getAveragePointLocal
  81116. * @param {Vec3} target
  81117. * @return {Vec3}
  81118. */
  81119. ConvexPolyhedron.prototype.getAveragePointLocal = function(target){
  81120. target = target || new Vec3();
  81121. var n = this.vertices.length,
  81122. verts = this.vertices;
  81123. for(var i=0; i<n; i++){
  81124. target.vadd(verts[i],target);
  81125. }
  81126. target.mult(1/n,target);
  81127. return target;
  81128. };
  81129. /**
  81130. * Transform all local points. Will change the .vertices
  81131. * @method transformAllPoints
  81132. * @param {Vec3} offset
  81133. * @param {Quaternion} quat
  81134. */
  81135. ConvexPolyhedron.prototype.transformAllPoints = function(offset,quat){
  81136. var n = this.vertices.length,
  81137. verts = this.vertices;
  81138. // Apply rotation
  81139. if(quat){
  81140. // Rotate vertices
  81141. for(var i=0; i<n; i++){
  81142. var v = verts[i];
  81143. quat.vmult(v,v);
  81144. }
  81145. // Rotate face normals
  81146. for(var i=0; i<this.faceNormals.length; i++){
  81147. var v = this.faceNormals[i];
  81148. quat.vmult(v,v);
  81149. }
  81150. /*
  81151. // Rotate edges
  81152. for(var i=0; i<this.uniqueEdges.length; i++){
  81153. var v = this.uniqueEdges[i];
  81154. quat.vmult(v,v);
  81155. }*/
  81156. }
  81157. // Apply offset
  81158. if(offset){
  81159. for(var i=0; i<n; i++){
  81160. var v = verts[i];
  81161. v.vadd(offset,v);
  81162. }
  81163. }
  81164. };
  81165. /**
  81166. * 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.
  81167. * @method pointIsInside
  81168. * @param {Vec3} p A point given in local coordinates
  81169. * @return {Boolean}
  81170. */
  81171. var ConvexPolyhedron_pointIsInside = new Vec3();
  81172. var ConvexPolyhedron_vToP = new Vec3();
  81173. var ConvexPolyhedron_vToPointInside = new Vec3();
  81174. ConvexPolyhedron.prototype.pointIsInside = function(p){
  81175. var n = this.vertices.length,
  81176. verts = this.vertices,
  81177. faces = this.faces,
  81178. normals = this.faceNormals;
  81179. var positiveResult = null;
  81180. var N = this.faces.length;
  81181. var pointInside = ConvexPolyhedron_pointIsInside;
  81182. this.getAveragePointLocal(pointInside);
  81183. for(var i=0; i<N; i++){
  81184. var numVertices = this.faces[i].length;
  81185. var n = normals[i];
  81186. var v = verts[faces[i][0]]; // We only need one point in the face
  81187. // This dot product determines which side of the edge the point is
  81188. var vToP = ConvexPolyhedron_vToP;
  81189. p.vsub(v,vToP);
  81190. var r1 = n.dot(vToP);
  81191. var vToPointInside = ConvexPolyhedron_vToPointInside;
  81192. pointInside.vsub(v,vToPointInside);
  81193. var r2 = n.dot(vToPointInside);
  81194. if((r1<0 && r2>0) || (r1>0 && r2<0)){
  81195. return false; // Encountered some other sign. Exit.
  81196. } else {
  81197. }
  81198. }
  81199. // If we got here, all dot products were of the same sign.
  81200. return positiveResult ? 1 : -1;
  81201. };
  81202. /**
  81203. * 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.
  81204. * @static
  81205. * @method project
  81206. * @param {ConvexPolyhedron} hull
  81207. * @param {Vec3} axis
  81208. * @param {Vec3} pos
  81209. * @param {Quaternion} quat
  81210. * @param {array} result result[0] and result[1] will be set to maximum and minimum, respectively.
  81211. */
  81212. var project_worldVertex = new Vec3();
  81213. var project_localAxis = new Vec3();
  81214. var project_localOrigin = new Vec3();
  81215. ConvexPolyhedron.project = function(hull, axis, pos, quat, result){
  81216. var n = hull.vertices.length,
  81217. worldVertex = project_worldVertex,
  81218. localAxis = project_localAxis,
  81219. max = 0,
  81220. min = 0,
  81221. localOrigin = project_localOrigin,
  81222. vs = hull.vertices;
  81223. localOrigin.setZero();
  81224. // Transform the axis to local
  81225. Transform.vectorToLocalFrame(pos, quat, axis, localAxis);
  81226. Transform.pointToLocalFrame(pos, quat, localOrigin, localOrigin);
  81227. var add = localOrigin.dot(localAxis);
  81228. min = max = vs[0].dot(localAxis);
  81229. for(var i = 1; i < n; i++){
  81230. var val = vs[i].dot(localAxis);
  81231. if(val > max){
  81232. max = val;
  81233. }
  81234. if(val < min){
  81235. min = val;
  81236. }
  81237. }
  81238. min -= add;
  81239. max -= add;
  81240. if(min > max){
  81241. // Inconsistent - swap
  81242. var temp = min;
  81243. min = max;
  81244. max = temp;
  81245. }
  81246. // Output
  81247. result[0] = max;
  81248. result[1] = min;
  81249. };
  81250. },{"../math/Quaternion":28,"../math/Transform":29,"../math/Vec3":30,"./Shape":43}],39:[function(_dereq_,module,exports){
  81251. module.exports = Cylinder;
  81252. var Shape = _dereq_('./Shape');
  81253. var Vec3 = _dereq_('../math/Vec3');
  81254. var Quaternion = _dereq_('../math/Quaternion');
  81255. var ConvexPolyhedron = _dereq_('./ConvexPolyhedron');
  81256. /**
  81257. * @class Cylinder
  81258. * @constructor
  81259. * @extends ConvexPolyhedron
  81260. * @author schteppe / https://github.com/schteppe
  81261. * @param {Number} radiusTop
  81262. * @param {Number} radiusBottom
  81263. * @param {Number} height
  81264. * @param {Number} numSegments The number of segments to build the cylinder out of
  81265. */
  81266. function Cylinder( radiusTop, radiusBottom, height , numSegments ) {
  81267. var N = numSegments,
  81268. verts = [],
  81269. axes = [],
  81270. faces = [],
  81271. bottomface = [],
  81272. topface = [],
  81273. cos = Math.cos,
  81274. sin = Math.sin;
  81275. // First bottom point
  81276. verts.push(new Vec3(radiusBottom*cos(0),
  81277. radiusBottom*sin(0),
  81278. -height*0.5));
  81279. bottomface.push(0);
  81280. // First top point
  81281. verts.push(new Vec3(radiusTop*cos(0),
  81282. radiusTop*sin(0),
  81283. height*0.5));
  81284. topface.push(1);
  81285. for(var i=0; i<N; i++){
  81286. var theta = 2*Math.PI/N * (i+1);
  81287. var thetaN = 2*Math.PI/N * (i+0.5);
  81288. if(i<N-1){
  81289. // Bottom
  81290. verts.push(new Vec3(radiusBottom*cos(theta),
  81291. radiusBottom*sin(theta),
  81292. -height*0.5));
  81293. bottomface.push(2*i+2);
  81294. // Top
  81295. verts.push(new Vec3(radiusTop*cos(theta),
  81296. radiusTop*sin(theta),
  81297. height*0.5));
  81298. topface.push(2*i+3);
  81299. // Face
  81300. faces.push([2*i+2, 2*i+3, 2*i+1,2*i]);
  81301. } else {
  81302. faces.push([0,1, 2*i+1, 2*i]); // Connect
  81303. }
  81304. // Axis: we can cut off half of them if we have even number of segments
  81305. if(N % 2 === 1 || i < N / 2){
  81306. axes.push(new Vec3(cos(thetaN), sin(thetaN), 0));
  81307. }
  81308. }
  81309. faces.push(topface);
  81310. axes.push(new Vec3(0,0,1));
  81311. // Reorder bottom face
  81312. var temp = [];
  81313. for(var i=0; i<bottomface.length; i++){
  81314. temp.push(bottomface[bottomface.length - i - 1]);
  81315. }
  81316. faces.push(temp);
  81317. this.type = Shape.types.CONVEXPOLYHEDRON;
  81318. ConvexPolyhedron.call( this, verts, faces, axes );
  81319. }
  81320. Cylinder.prototype = new ConvexPolyhedron();
  81321. },{"../math/Quaternion":28,"../math/Vec3":30,"./ConvexPolyhedron":38,"./Shape":43}],40:[function(_dereq_,module,exports){
  81322. var Shape = _dereq_('./Shape');
  81323. var ConvexPolyhedron = _dereq_('./ConvexPolyhedron');
  81324. var Vec3 = _dereq_('../math/Vec3');
  81325. var Utils = _dereq_('../utils/Utils');
  81326. module.exports = Heightfield;
  81327. /**
  81328. * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a given distance.
  81329. * @class Heightfield
  81330. * @extends Shape
  81331. * @constructor
  81332. * @param {Array} data An array of Y values that will be used to construct the terrain.
  81333. * @param {object} options
  81334. * @param {Number} [options.minValue] Minimum value of the data points in the data array. Will be computed automatically if not given.
  81335. * @param {Number} [options.maxValue] Maximum value.
  81336. * @param {Number} [options.elementSize=0.1] World spacing between the data points in X direction.
  81337. * @todo Should be possible to use along all axes, not just y
  81338. *
  81339. * @example
  81340. * // Generate some height data (y-values).
  81341. * var data = [];
  81342. * for(var i = 0; i < 1000; i++){
  81343. * var y = 0.5 * Math.cos(0.2 * i);
  81344. * data.push(y);
  81345. * }
  81346. *
  81347. * // Create the heightfield shape
  81348. * var heightfieldShape = new Heightfield(data, {
  81349. * elementSize: 1 // Distance between the data points in X and Y directions
  81350. * });
  81351. * var heightfieldBody = new Body();
  81352. * heightfieldBody.addShape(heightfieldShape);
  81353. * world.addBody(heightfieldBody);
  81354. */
  81355. function Heightfield(data, options){
  81356. options = Utils.defaults(options, {
  81357. maxValue : null,
  81358. minValue : null,
  81359. elementSize : 1
  81360. });
  81361. /**
  81362. * An array of numbers, or height values, that are spread out along the x axis.
  81363. * @property {array} data
  81364. */
  81365. this.data = data;
  81366. /**
  81367. * Max value of the data
  81368. * @property {number} maxValue
  81369. */
  81370. this.maxValue = options.maxValue;
  81371. /**
  81372. * Max value of the data
  81373. * @property {number} minValue
  81374. */
  81375. this.minValue = options.minValue;
  81376. /**
  81377. * The width of each element
  81378. * @property {number} elementSize
  81379. * @todo elementSizeX and Y
  81380. */
  81381. this.elementSize = options.elementSize;
  81382. if(options.minValue === null){
  81383. this.updateMinValue();
  81384. }
  81385. if(options.maxValue === null){
  81386. this.updateMaxValue();
  81387. }
  81388. this.cacheEnabled = true;
  81389. Shape.call(this);
  81390. this.pillarConvex = new ConvexPolyhedron();
  81391. this.pillarOffset = new Vec3();
  81392. this.type = Shape.types.HEIGHTFIELD;
  81393. this.updateBoundingSphereRadius();
  81394. // "i_j_isUpper" => { convex: ..., offset: ... }
  81395. // for example:
  81396. // _cachedPillars["0_2_1"]
  81397. this._cachedPillars = {};
  81398. }
  81399. Heightfield.prototype = new Shape();
  81400. /**
  81401. * Call whenever you change the data array.
  81402. * @method update
  81403. */
  81404. Heightfield.prototype.update = function(){
  81405. this._cachedPillars = {};
  81406. };
  81407. /**
  81408. * Update the .minValue property
  81409. * @method updateMinValue
  81410. */
  81411. Heightfield.prototype.updateMinValue = function(){
  81412. var data = this.data;
  81413. var minValue = data[0][0];
  81414. for(var i=0; i !== data.length; i++){
  81415. for(var j=0; j !== data[i].length; j++){
  81416. var v = data[i][j];
  81417. if(v < minValue){
  81418. minValue = v;
  81419. }
  81420. }
  81421. }
  81422. this.minValue = minValue;
  81423. };
  81424. /**
  81425. * Update the .maxValue property
  81426. * @method updateMaxValue
  81427. */
  81428. Heightfield.prototype.updateMaxValue = function(){
  81429. var data = this.data;
  81430. var maxValue = data[0][0];
  81431. for(var i=0; i !== data.length; i++){
  81432. for(var j=0; j !== data[i].length; j++){
  81433. var v = data[i][j];
  81434. if(v > maxValue){
  81435. maxValue = v;
  81436. }
  81437. }
  81438. }
  81439. this.maxValue = maxValue;
  81440. };
  81441. /**
  81442. * Set the height value at an index. Don't forget to update maxValue and minValue after you're done.
  81443. * @method setHeightValueAtIndex
  81444. * @param {integer} xi
  81445. * @param {integer} yi
  81446. * @param {number} value
  81447. */
  81448. Heightfield.prototype.setHeightValueAtIndex = function(xi, yi, value){
  81449. var data = this.data;
  81450. data[xi][yi] = value;
  81451. // Invalidate cache
  81452. this.clearCachedConvexTrianglePillar(xi, yi, false);
  81453. if(xi > 0){
  81454. this.clearCachedConvexTrianglePillar(xi - 1, yi, true);
  81455. this.clearCachedConvexTrianglePillar(xi - 1, yi, false);
  81456. }
  81457. if(yi > 0){
  81458. this.clearCachedConvexTrianglePillar(xi, yi - 1, true);
  81459. this.clearCachedConvexTrianglePillar(xi, yi - 1, false);
  81460. }
  81461. if(yi > 0 && xi > 0){
  81462. this.clearCachedConvexTrianglePillar(xi - 1, yi - 1, true);
  81463. }
  81464. };
  81465. /**
  81466. * Get max/min in a rectangle in the matrix data
  81467. * @method getRectMinMax
  81468. * @param {integer} iMinX
  81469. * @param {integer} iMinY
  81470. * @param {integer} iMaxX
  81471. * @param {integer} iMaxY
  81472. * @param {array} [result] An array to store the results in.
  81473. * @return {array} The result array, if it was passed in. Minimum will be at position 0 and max at 1.
  81474. */
  81475. Heightfield.prototype.getRectMinMax = function (iMinX, iMinY, iMaxX, iMaxY, result) {
  81476. result = result || [];
  81477. // Get max and min of the data
  81478. var data = this.data,
  81479. max = this.minValue; // Set first value
  81480. for(var i = iMinX; i <= iMaxX; i++){
  81481. for(var j = iMinY; j <= iMaxY; j++){
  81482. var height = data[i][j];
  81483. if(height > max){
  81484. max = height;
  81485. }
  81486. }
  81487. }
  81488. result[0] = this.minValue;
  81489. result[1] = max;
  81490. };
  81491. /**
  81492. * 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.
  81493. * @method getIndexOfPosition
  81494. * @param {number} x
  81495. * @param {number} y
  81496. * @param {array} result Two-element array
  81497. * @param {boolean} clamp If the position should be clamped to the heightfield edge.
  81498. * @return {boolean}
  81499. */
  81500. Heightfield.prototype.getIndexOfPosition = function (x, y, result, clamp) {
  81501. // Get the index of the data points to test against
  81502. var w = this.elementSize;
  81503. var data = this.data;
  81504. var xi = Math.floor(x / w);
  81505. var yi = Math.floor(y / w);
  81506. result[0] = xi;
  81507. result[1] = yi;
  81508. if(clamp){
  81509. // Clamp index to edges
  81510. if(xi < 0){ xi = 0; }
  81511. if(yi < 0){ yi = 0; }
  81512. if(xi >= data.length - 1){ xi = data.length - 1; }
  81513. if(yi >= data[0].length - 1){ yi = data[0].length - 1; }
  81514. }
  81515. // Bail out if we are out of the terrain
  81516. if(xi < 0 || yi < 0 || xi >= data.length-1 || yi >= data[0].length-1){
  81517. return false;
  81518. }
  81519. return true;
  81520. };
  81521. Heightfield.prototype.getHeightAt = function(x, y, edgeClamp){
  81522. var idx = [];
  81523. this.getIndexOfPosition(x, y, idx, edgeClamp);
  81524. // TODO: get upper or lower triangle, then use barycentric interpolation to get the height in the triangle.
  81525. var minmax = [];
  81526. this.getRectMinMax(idx[0], idx[1] + 1, idx[0], idx[1] + 1, minmax);
  81527. return (minmax[0] + minmax[1]) / 2; // average
  81528. };
  81529. Heightfield.prototype.getCacheConvexTrianglePillarKey = function(xi, yi, getUpperTriangle){
  81530. return xi + '_' + yi + '_' + (getUpperTriangle ? 1 : 0);
  81531. };
  81532. Heightfield.prototype.getCachedConvexTrianglePillar = function(xi, yi, getUpperTriangle){
  81533. return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)];
  81534. };
  81535. Heightfield.prototype.setCachedConvexTrianglePillar = function(xi, yi, getUpperTriangle, convex, offset){
  81536. this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)] = {
  81537. convex: convex,
  81538. offset: offset
  81539. };
  81540. };
  81541. Heightfield.prototype.clearCachedConvexTrianglePillar = function(xi, yi, getUpperTriangle){
  81542. delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)];
  81543. };
  81544. /**
  81545. * Get a triangle in the terrain in the form of a triangular convex shape.
  81546. * @method getConvexTrianglePillar
  81547. * @param {integer} i
  81548. * @param {integer} j
  81549. * @param {boolean} getUpperTriangle
  81550. */
  81551. Heightfield.prototype.getConvexTrianglePillar = function(xi, yi, getUpperTriangle){
  81552. var result = this.pillarConvex;
  81553. var offsetResult = this.pillarOffset;
  81554. if(this.cacheEnabled){
  81555. var data = this.getCachedConvexTrianglePillar(xi, yi, getUpperTriangle);
  81556. if(data){
  81557. this.pillarConvex = data.convex;
  81558. this.pillarOffset = data.offset;
  81559. return;
  81560. }
  81561. result = new ConvexPolyhedron();
  81562. offsetResult = new Vec3();
  81563. this.pillarConvex = result;
  81564. this.pillarOffset = offsetResult;
  81565. }
  81566. var data = this.data;
  81567. var elementSize = this.elementSize;
  81568. var faces = result.faces;
  81569. // Reuse verts if possible
  81570. result.vertices.length = 6;
  81571. for (var i = 0; i < 6; i++) {
  81572. if(!result.vertices[i]){
  81573. result.vertices[i] = new Vec3();
  81574. }
  81575. }
  81576. // Reuse faces if possible
  81577. faces.length = 5;
  81578. for (var i = 0; i < 5; i++) {
  81579. if(!faces[i]){
  81580. faces[i] = [];
  81581. }
  81582. }
  81583. var verts = result.vertices;
  81584. var h = (Math.min(
  81585. data[xi][yi],
  81586. data[xi+1][yi],
  81587. data[xi][yi+1],
  81588. data[xi+1][yi+1]
  81589. ) - this.minValue ) / 2 + this.minValue;
  81590. if (!getUpperTriangle) {
  81591. // Center of the triangle pillar - all polygons are given relative to this one
  81592. offsetResult.set(
  81593. (xi + 0.25) * elementSize, // sort of center of a triangle
  81594. (yi + 0.25) * elementSize,
  81595. h // vertical center
  81596. );
  81597. // Top triangle verts
  81598. verts[0].set(
  81599. -0.25 * elementSize,
  81600. -0.25 * elementSize,
  81601. data[xi][yi] - h
  81602. );
  81603. verts[1].set(
  81604. 0.75 * elementSize,
  81605. -0.25 * elementSize,
  81606. data[xi + 1][yi] - h
  81607. );
  81608. verts[2].set(
  81609. -0.25 * elementSize,
  81610. 0.75 * elementSize,
  81611. data[xi][yi + 1] - h
  81612. );
  81613. // bottom triangle verts
  81614. verts[3].set(
  81615. -0.25 * elementSize,
  81616. -0.25 * elementSize,
  81617. -h-1
  81618. );
  81619. verts[4].set(
  81620. 0.75 * elementSize,
  81621. -0.25 * elementSize,
  81622. -h-1
  81623. );
  81624. verts[5].set(
  81625. -0.25 * elementSize,
  81626. 0.75 * elementSize,
  81627. -h-1
  81628. );
  81629. // top triangle
  81630. faces[0][0] = 0;
  81631. faces[0][1] = 1;
  81632. faces[0][2] = 2;
  81633. // bottom triangle
  81634. faces[1][0] = 5;
  81635. faces[1][1] = 4;
  81636. faces[1][2] = 3;
  81637. // -x facing quad
  81638. faces[2][0] = 0;
  81639. faces[2][1] = 2;
  81640. faces[2][2] = 5;
  81641. faces[2][3] = 3;
  81642. // -y facing quad
  81643. faces[3][0] = 1;
  81644. faces[3][1] = 0;
  81645. faces[3][2] = 3;
  81646. faces[3][3] = 4;
  81647. // +xy facing quad
  81648. faces[4][0] = 4;
  81649. faces[4][1] = 5;
  81650. faces[4][2] = 2;
  81651. faces[4][3] = 1;
  81652. } else {
  81653. // Center of the triangle pillar - all polygons are given relative to this one
  81654. offsetResult.set(
  81655. (xi + 0.75) * elementSize, // sort of center of a triangle
  81656. (yi + 0.75) * elementSize,
  81657. h // vertical center
  81658. );
  81659. // Top triangle verts
  81660. verts[0].set(
  81661. 0.25 * elementSize,
  81662. 0.25 * elementSize,
  81663. data[xi + 1][yi + 1] - h
  81664. );
  81665. verts[1].set(
  81666. -0.75 * elementSize,
  81667. 0.25 * elementSize,
  81668. data[xi][yi + 1] - h
  81669. );
  81670. verts[2].set(
  81671. 0.25 * elementSize,
  81672. -0.75 * elementSize,
  81673. data[xi + 1][yi] - h
  81674. );
  81675. // bottom triangle verts
  81676. verts[3].set(
  81677. 0.25 * elementSize,
  81678. 0.25 * elementSize,
  81679. - h-1
  81680. );
  81681. verts[4].set(
  81682. -0.75 * elementSize,
  81683. 0.25 * elementSize,
  81684. - h-1
  81685. );
  81686. verts[5].set(
  81687. 0.25 * elementSize,
  81688. -0.75 * elementSize,
  81689. - h-1
  81690. );
  81691. // Top triangle
  81692. faces[0][0] = 0;
  81693. faces[0][1] = 1;
  81694. faces[0][2] = 2;
  81695. // bottom triangle
  81696. faces[1][0] = 5;
  81697. faces[1][1] = 4;
  81698. faces[1][2] = 3;
  81699. // +x facing quad
  81700. faces[2][0] = 2;
  81701. faces[2][1] = 5;
  81702. faces[2][2] = 3;
  81703. faces[2][3] = 0;
  81704. // +y facing quad
  81705. faces[3][0] = 3;
  81706. faces[3][1] = 4;
  81707. faces[3][2] = 1;
  81708. faces[3][3] = 0;
  81709. // -xy facing quad
  81710. faces[4][0] = 1;
  81711. faces[4][1] = 4;
  81712. faces[4][2] = 5;
  81713. faces[4][3] = 2;
  81714. }
  81715. result.computeNormals();
  81716. result.computeEdges();
  81717. result.updateBoundingSphereRadius();
  81718. this.setCachedConvexTrianglePillar(xi, yi, getUpperTriangle, result, offsetResult);
  81719. };
  81720. Heightfield.prototype.calculateLocalInertia = function(mass, target){
  81721. target = target || new Vec3();
  81722. target.set(0, 0, 0);
  81723. return target;
  81724. };
  81725. Heightfield.prototype.volume = function(){
  81726. return Number.MAX_VALUE; // The terrain is infinite
  81727. };
  81728. Heightfield.prototype.calculateWorldAABB = function(pos, quat, min, max){
  81729. // TODO: do it properly
  81730. min.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  81731. max.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  81732. };
  81733. Heightfield.prototype.updateBoundingSphereRadius = function(){
  81734. // Use the bounding box of the min/max values
  81735. var data = this.data,
  81736. s = this.elementSize;
  81737. this.boundingSphereRadius = new Vec3(data.length * s, data[0].length * s, Math.max(Math.abs(this.maxValue), Math.abs(this.minValue))).norm();
  81738. };
  81739. },{"../math/Vec3":30,"../utils/Utils":53,"./ConvexPolyhedron":38,"./Shape":43}],41:[function(_dereq_,module,exports){
  81740. module.exports = Particle;
  81741. var Shape = _dereq_('./Shape');
  81742. var Vec3 = _dereq_('../math/Vec3');
  81743. /**
  81744. * Particle shape.
  81745. * @class Particle
  81746. * @constructor
  81747. * @author schteppe
  81748. * @extends Shape
  81749. */
  81750. function Particle(){
  81751. Shape.call(this);
  81752. this.type = Shape.types.PARTICLE;
  81753. }
  81754. Particle.prototype = new Shape();
  81755. Particle.prototype.constructor = Particle;
  81756. /**
  81757. * @method calculateLocalInertia
  81758. * @param {Number} mass
  81759. * @param {Vec3} target
  81760. * @return {Vec3}
  81761. */
  81762. Particle.prototype.calculateLocalInertia = function(mass,target){
  81763. target = target || new Vec3();
  81764. target.set(0, 0, 0);
  81765. return target;
  81766. };
  81767. Particle.prototype.volume = function(){
  81768. return 0;
  81769. };
  81770. Particle.prototype.updateBoundingSphereRadius = function(){
  81771. this.boundingSphereRadius = 0;
  81772. };
  81773. Particle.prototype.calculateWorldAABB = function(pos,quat,min,max){
  81774. // Get each axis max
  81775. min.copy(pos);
  81776. max.copy(pos);
  81777. };
  81778. },{"../math/Vec3":30,"./Shape":43}],42:[function(_dereq_,module,exports){
  81779. module.exports = Plane;
  81780. var Shape = _dereq_('./Shape');
  81781. var Vec3 = _dereq_('../math/Vec3');
  81782. /**
  81783. * 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.
  81784. * @class Plane
  81785. * @constructor
  81786. * @extends Shape
  81787. * @author schteppe
  81788. */
  81789. function Plane(){
  81790. Shape.call(this);
  81791. this.type = Shape.types.PLANE;
  81792. // World oriented normal
  81793. this.worldNormal = new Vec3();
  81794. this.worldNormalNeedsUpdate = true;
  81795. this.boundingSphereRadius = Number.MAX_VALUE;
  81796. }
  81797. Plane.prototype = new Shape();
  81798. Plane.prototype.constructor = Plane;
  81799. Plane.prototype.computeWorldNormal = function(quat){
  81800. var n = this.worldNormal;
  81801. n.set(0,0,1);
  81802. quat.vmult(n,n);
  81803. this.worldNormalNeedsUpdate = false;
  81804. };
  81805. Plane.prototype.calculateLocalInertia = function(mass,target){
  81806. target = target || new Vec3();
  81807. return target;
  81808. };
  81809. Plane.prototype.volume = function(){
  81810. return Number.MAX_VALUE; // The plane is infinite...
  81811. };
  81812. var tempNormal = new Vec3();
  81813. Plane.prototype.calculateWorldAABB = function(pos, quat, min, max){
  81814. // The plane AABB is infinite, except if the normal is pointing along any axis
  81815. tempNormal.set(0,0,1); // Default plane normal is z
  81816. quat.vmult(tempNormal,tempNormal);
  81817. var maxVal = Number.MAX_VALUE;
  81818. min.set(-maxVal, -maxVal, -maxVal);
  81819. max.set(maxVal, maxVal, maxVal);
  81820. if(tempNormal.x === 1){ max.x = pos.x; }
  81821. if(tempNormal.y === 1){ max.y = pos.y; }
  81822. if(tempNormal.z === 1){ max.z = pos.z; }
  81823. if(tempNormal.x === -1){ min.x = pos.x; }
  81824. if(tempNormal.y === -1){ min.y = pos.y; }
  81825. if(tempNormal.z === -1){ min.z = pos.z; }
  81826. };
  81827. Plane.prototype.updateBoundingSphereRadius = function(){
  81828. this.boundingSphereRadius = Number.MAX_VALUE;
  81829. };
  81830. },{"../math/Vec3":30,"./Shape":43}],43:[function(_dereq_,module,exports){
  81831. module.exports = Shape;
  81832. var Shape = _dereq_('./Shape');
  81833. var Vec3 = _dereq_('../math/Vec3');
  81834. var Quaternion = _dereq_('../math/Quaternion');
  81835. var Material = _dereq_('../material/Material');
  81836. /**
  81837. * Base class for shapes
  81838. * @class Shape
  81839. * @constructor
  81840. * @author schteppe
  81841. * @todo Should have a mechanism for caching bounding sphere radius instead of calculating it each time
  81842. */
  81843. function Shape(){
  81844. /**
  81845. * Identifyer of the Shape.
  81846. * @property {number} id
  81847. */
  81848. this.id = Shape.idCounter++;
  81849. /**
  81850. * The type of this shape. Must be set to an int > 0 by subclasses.
  81851. * @property type
  81852. * @type {Number}
  81853. * @see Shape.types
  81854. */
  81855. this.type = 0;
  81856. /**
  81857. * The local bounding sphere radius of this shape.
  81858. * @property {Number} boundingSphereRadius
  81859. */
  81860. this.boundingSphereRadius = 0;
  81861. /**
  81862. * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled.
  81863. * @property {boolean} collisionResponse
  81864. */
  81865. this.collisionResponse = true;
  81866. /**
  81867. * @property {Material} material
  81868. */
  81869. this.material = null;
  81870. }
  81871. Shape.prototype.constructor = Shape;
  81872. /**
  81873. * Computes the bounding sphere radius. The result is stored in the property .boundingSphereRadius
  81874. * @method updateBoundingSphereRadius
  81875. * @return {Number}
  81876. */
  81877. Shape.prototype.updateBoundingSphereRadius = function(){
  81878. throw "computeBoundingSphereRadius() not implemented for shape type "+this.type;
  81879. };
  81880. /**
  81881. * Get the volume of this shape
  81882. * @method volume
  81883. * @return {Number}
  81884. */
  81885. Shape.prototype.volume = function(){
  81886. throw "volume() not implemented for shape type "+this.type;
  81887. };
  81888. /**
  81889. * Calculates the inertia in the local frame for this shape.
  81890. * @method calculateLocalInertia
  81891. * @return {Vec3}
  81892. * @see http://en.wikipedia.org/wiki/List_of_moments_of_inertia
  81893. */
  81894. Shape.prototype.calculateLocalInertia = function(mass,target){
  81895. throw "calculateLocalInertia() not implemented for shape type "+this.type;
  81896. };
  81897. Shape.idCounter = 0;
  81898. /**
  81899. * The available shape types.
  81900. * @static
  81901. * @property types
  81902. * @type {Object}
  81903. */
  81904. Shape.types = {
  81905. SPHERE:1,
  81906. PLANE:2,
  81907. BOX:4,
  81908. COMPOUND:8,
  81909. CONVEXPOLYHEDRON:16,
  81910. HEIGHTFIELD:32,
  81911. PARTICLE:64,
  81912. CYLINDER:128,
  81913. TRIMESH:256
  81914. };
  81915. },{"../material/Material":25,"../math/Quaternion":28,"../math/Vec3":30,"./Shape":43}],44:[function(_dereq_,module,exports){
  81916. module.exports = Sphere;
  81917. var Shape = _dereq_('./Shape');
  81918. var Vec3 = _dereq_('../math/Vec3');
  81919. /**
  81920. * Spherical shape
  81921. * @class Sphere
  81922. * @constructor
  81923. * @extends Shape
  81924. * @param {Number} radius The radius of the sphere, a non-negative number.
  81925. * @author schteppe / http://github.com/schteppe
  81926. */
  81927. function Sphere(radius){
  81928. Shape.call(this);
  81929. /**
  81930. * @property {Number} radius
  81931. */
  81932. this.radius = radius!==undefined ? Number(radius) : 1.0;
  81933. this.type = Shape.types.SPHERE;
  81934. if(this.radius < 0){
  81935. throw new Error('The sphere radius cannot be negative.');
  81936. }
  81937. this.updateBoundingSphereRadius();
  81938. }
  81939. Sphere.prototype = new Shape();
  81940. Sphere.prototype.constructor = Sphere;
  81941. Sphere.prototype.calculateLocalInertia = function(mass,target){
  81942. target = target || new Vec3();
  81943. var I = 2.0*mass*this.radius*this.radius/5.0;
  81944. target.x = I;
  81945. target.y = I;
  81946. target.z = I;
  81947. return target;
  81948. };
  81949. Sphere.prototype.volume = function(){
  81950. return 4.0 * Math.PI * this.radius / 3.0;
  81951. };
  81952. Sphere.prototype.updateBoundingSphereRadius = function(){
  81953. this.boundingSphereRadius = this.radius;
  81954. };
  81955. Sphere.prototype.calculateWorldAABB = function(pos,quat,min,max){
  81956. var r = this.radius;
  81957. var axes = ['x','y','z'];
  81958. for(var i=0; i<axes.length; i++){
  81959. var ax = axes[i];
  81960. min[ax] = pos[ax] - r;
  81961. max[ax] = pos[ax] + r;
  81962. }
  81963. };
  81964. },{"../math/Vec3":30,"./Shape":43}],45:[function(_dereq_,module,exports){
  81965. module.exports = Trimesh;
  81966. var Shape = _dereq_('./Shape');
  81967. var Vec3 = _dereq_('../math/Vec3');
  81968. var Quaternion = _dereq_('../math/Quaternion');
  81969. var Transform = _dereq_('../math/Transform');
  81970. var AABB = _dereq_('../collision/AABB');
  81971. var Octree = _dereq_('../utils/Octree');
  81972. /**
  81973. * @class Trimesh
  81974. * @constructor
  81975. * @param {array} vertices
  81976. * @param {array} indices
  81977. * @extends Shape
  81978. * @example
  81979. * // How to make a mesh with a single triangle
  81980. * var vertices = [
  81981. * 0, 0, 0, // vertex 0
  81982. * 1, 0, 0, // vertex 1
  81983. * 0, 1, 0 // vertex 2
  81984. * ];
  81985. * var indices = [
  81986. * 0, 1, 2 // triangle 0
  81987. * ];
  81988. * var trimeshShape = new Trimesh(vertices, indices);
  81989. */
  81990. function Trimesh(vertices, indices) {
  81991. Shape.call(this);
  81992. this.type = Shape.types.TRIMESH;
  81993. /**
  81994. * @property vertices
  81995. * @type {Array}
  81996. */
  81997. this.vertices = new Float32Array(vertices);
  81998. /**
  81999. * Array of integers, indicating which vertices each triangle consists of. The length of this array is thus 3 times the number of triangles.
  82000. * @property indices
  82001. * @type {Array}
  82002. */
  82003. this.indices = new Int16Array(indices);
  82004. /**
  82005. * The normals data.
  82006. * @property normals
  82007. * @type {Array}
  82008. */
  82009. this.normals = new Float32Array(indices.length);
  82010. /**
  82011. * The local AABB of the mesh.
  82012. * @property aabb
  82013. * @type {Array}
  82014. */
  82015. this.aabb = new AABB();
  82016. /**
  82017. * References to vertex pairs, making up all unique edges in the trimesh.
  82018. * @property {array} edges
  82019. */
  82020. this.edges = null;
  82021. /**
  82022. * Local scaling of the mesh. Use .setScale() to set it.
  82023. * @property {Vec3} scale
  82024. */
  82025. this.scale = new Vec3(1, 1, 1);
  82026. /**
  82027. * The indexed triangles. Use .updateTree() to update it.
  82028. * @property {Octree} tree
  82029. */
  82030. this.tree = new Octree();
  82031. this.updateEdges();
  82032. this.updateNormals();
  82033. this.updateAABB();
  82034. this.updateBoundingSphereRadius();
  82035. this.updateTree();
  82036. }
  82037. Trimesh.prototype = new Shape();
  82038. Trimesh.prototype.constructor = Trimesh;
  82039. var computeNormals_n = new Vec3();
  82040. /**
  82041. * @method updateTree
  82042. */
  82043. Trimesh.prototype.updateTree = function(){
  82044. var tree = this.tree;
  82045. tree.reset();
  82046. tree.aabb.copy(this.aabb);
  82047. var scale = this.scale; // The local mesh AABB is scaled, but the octree AABB should be unscaled
  82048. tree.aabb.lowerBound.x *= 1 / scale.x;
  82049. tree.aabb.lowerBound.y *= 1 / scale.y;
  82050. tree.aabb.lowerBound.z *= 1 / scale.z;
  82051. tree.aabb.upperBound.x *= 1 / scale.x;
  82052. tree.aabb.upperBound.y *= 1 / scale.y;
  82053. tree.aabb.upperBound.z *= 1 / scale.z;
  82054. // Insert all triangles
  82055. var triangleAABB = new AABB();
  82056. var a = new Vec3();
  82057. var b = new Vec3();
  82058. var c = new Vec3();
  82059. var points = [a, b, c];
  82060. for (var i = 0; i < this.indices.length / 3; i++) {
  82061. //this.getTriangleVertices(i, a, b, c);
  82062. // Get unscaled triangle verts
  82063. var i3 = i * 3;
  82064. this._getUnscaledVertex(this.indices[i3], a);
  82065. this._getUnscaledVertex(this.indices[i3 + 1], b);
  82066. this._getUnscaledVertex(this.indices[i3 + 2], c);
  82067. triangleAABB.setFromPoints(points);
  82068. tree.insert(triangleAABB, i);
  82069. }
  82070. tree.removeEmptyNodes();
  82071. };
  82072. var unscaledAABB = new AABB();
  82073. /**
  82074. * Get triangles in a local AABB from the trimesh.
  82075. * @method getTrianglesInAABB
  82076. * @param {AABB} aabb
  82077. * @param {array} result An array of integers, referencing the queried triangles.
  82078. */
  82079. Trimesh.prototype.getTrianglesInAABB = function(aabb, result){
  82080. unscaledAABB.copy(aabb);
  82081. // Scale it to local
  82082. var scale = this.scale;
  82083. var isx = scale.x;
  82084. var isy = scale.y;
  82085. var isz = scale.z;
  82086. var l = unscaledAABB.lowerBound;
  82087. var u = unscaledAABB.upperBound;
  82088. l.x /= isx;
  82089. l.y /= isy;
  82090. l.z /= isz;
  82091. u.x /= isx;
  82092. u.y /= isy;
  82093. u.z /= isz;
  82094. return this.tree.aabbQuery(unscaledAABB, result);
  82095. };
  82096. /**
  82097. * @method setScale
  82098. * @param {Vec3} scale
  82099. */
  82100. Trimesh.prototype.setScale = function(scale){
  82101. var wasUniform = this.scale.x === this.scale.y === this.scale.z;
  82102. var isUniform = scale.x === scale.y === scale.z;
  82103. if(!(wasUniform && isUniform)){
  82104. // Non-uniform scaling. Need to update normals.
  82105. this.updateNormals();
  82106. }
  82107. this.scale.copy(scale);
  82108. this.updateAABB();
  82109. this.updateBoundingSphereRadius();
  82110. };
  82111. /**
  82112. * Compute the normals of the faces. Will save in the .normals array.
  82113. * @method updateNormals
  82114. */
  82115. Trimesh.prototype.updateNormals = function(){
  82116. var n = computeNormals_n;
  82117. // Generate normals
  82118. var normals = this.normals;
  82119. for(var i=0; i < this.indices.length / 3; i++){
  82120. var i3 = i * 3;
  82121. var a = this.indices[i3],
  82122. b = this.indices[i3 + 1],
  82123. c = this.indices[i3 + 2];
  82124. this.getVertex(a, va);
  82125. this.getVertex(b, vb);
  82126. this.getVertex(c, vc);
  82127. Trimesh.computeNormal(vb, va, vc, n);
  82128. normals[i3] = n.x;
  82129. normals[i3 + 1] = n.y;
  82130. normals[i3 + 2] = n.z;
  82131. }
  82132. };
  82133. /**
  82134. * Update the .edges property
  82135. * @method updateEdges
  82136. */
  82137. Trimesh.prototype.updateEdges = function(){
  82138. var edges = {};
  82139. var add = function(indexA, indexB){
  82140. var key = a < b ? a + '_' + b : b + '_' + a;
  82141. edges[key] = true;
  82142. };
  82143. for(var i=0; i < this.indices.length / 3; i++){
  82144. var i3 = i * 3;
  82145. var a = this.indices[i3],
  82146. b = this.indices[i3 + 1],
  82147. c = this.indices[i3 + 2];
  82148. add(a,b);
  82149. add(b,c);
  82150. add(c,a);
  82151. }
  82152. var keys = Object.keys(edges);
  82153. this.edges = new Int16Array(keys.length * 2);
  82154. for (var i = 0; i < keys.length; i++) {
  82155. var indices = keys[i].split('_');
  82156. this.edges[2 * i] = parseInt(indices[0], 10);
  82157. this.edges[2 * i + 1] = parseInt(indices[1], 10);
  82158. }
  82159. };
  82160. /**
  82161. * Get an edge vertex
  82162. * @method getEdgeVertex
  82163. * @param {number} edgeIndex
  82164. * @param {number} firstOrSecond 0 or 1, depending on which one of the vertices you need.
  82165. * @param {Vec3} vertexStore Where to store the result
  82166. */
  82167. Trimesh.prototype.getEdgeVertex = function(edgeIndex, firstOrSecond, vertexStore){
  82168. var vertexIndex = this.edges[edgeIndex * 2 + (firstOrSecond ? 1 : 0)];
  82169. this.getVertex(vertexIndex, vertexStore);
  82170. };
  82171. var getEdgeVector_va = new Vec3();
  82172. var getEdgeVector_vb = new Vec3();
  82173. /**
  82174. * Get a vector along an edge.
  82175. * @method getEdgeVector
  82176. * @param {number} edgeIndex
  82177. * @param {Vec3} vectorStore
  82178. */
  82179. Trimesh.prototype.getEdgeVector = function(edgeIndex, vectorStore){
  82180. var va = getEdgeVector_va;
  82181. var vb = getEdgeVector_vb;
  82182. this.getEdgeVertex(edgeIndex, 0, va);
  82183. this.getEdgeVertex(edgeIndex, 1, vb);
  82184. vb.vsub(va, vectorStore);
  82185. };
  82186. /**
  82187. * Get face normal given 3 vertices
  82188. * @static
  82189. * @method computeNormal
  82190. * @param {Vec3} va
  82191. * @param {Vec3} vb
  82192. * @param {Vec3} vc
  82193. * @param {Vec3} target
  82194. */
  82195. var cb = new Vec3();
  82196. var ab = new Vec3();
  82197. Trimesh.computeNormal = function ( va, vb, vc, target ) {
  82198. vb.vsub(va,ab);
  82199. vc.vsub(vb,cb);
  82200. cb.cross(ab,target);
  82201. if ( !target.isZero() ) {
  82202. target.normalize();
  82203. }
  82204. };
  82205. var va = new Vec3();
  82206. var vb = new Vec3();
  82207. var vc = new Vec3();
  82208. /**
  82209. * Get vertex i.
  82210. * @method getVertex
  82211. * @param {number} i
  82212. * @param {Vec3} out
  82213. * @return {Vec3} The "out" vector object
  82214. */
  82215. Trimesh.prototype.getVertex = function(i, out){
  82216. var scale = this.scale;
  82217. this._getUnscaledVertex(i, out);
  82218. out.x *= scale.x;
  82219. out.y *= scale.y;
  82220. out.z *= scale.z;
  82221. return out;
  82222. };
  82223. /**
  82224. * Get raw vertex i
  82225. * @private
  82226. * @method _getUnscaledVertex
  82227. * @param {number} i
  82228. * @param {Vec3} out
  82229. * @return {Vec3} The "out" vector object
  82230. */
  82231. Trimesh.prototype._getUnscaledVertex = function(i, out){
  82232. var i3 = i * 3;
  82233. var vertices = this.vertices;
  82234. return out.set(
  82235. vertices[i3],
  82236. vertices[i3 + 1],
  82237. vertices[i3 + 2]
  82238. );
  82239. };
  82240. /**
  82241. * Get a vertex from the trimesh,transformed by the given position and quaternion.
  82242. * @method getWorldVertex
  82243. * @param {number} i
  82244. * @param {Vec3} pos
  82245. * @param {Quaternion} quat
  82246. * @param {Vec3} out
  82247. * @return {Vec3} The "out" vector object
  82248. */
  82249. Trimesh.prototype.getWorldVertex = function(i, pos, quat, out){
  82250. this.getVertex(i, out);
  82251. Transform.pointToWorldFrame(pos, quat, out, out);
  82252. return out;
  82253. };
  82254. /**
  82255. * Get the three vertices for triangle i.
  82256. * @method getTriangleVertices
  82257. * @param {number} i
  82258. * @param {Vec3} a
  82259. * @param {Vec3} b
  82260. * @param {Vec3} c
  82261. */
  82262. Trimesh.prototype.getTriangleVertices = function(i, a, b, c){
  82263. var i3 = i * 3;
  82264. this.getVertex(this.indices[i3], a);
  82265. this.getVertex(this.indices[i3 + 1], b);
  82266. this.getVertex(this.indices[i3 + 2], c);
  82267. };
  82268. /**
  82269. * Compute the normal of triangle i.
  82270. * @method getNormal
  82271. * @param {Number} i
  82272. * @param {Vec3} target
  82273. * @return {Vec3} The "target" vector object
  82274. */
  82275. Trimesh.prototype.getNormal = function(i, target){
  82276. var i3 = i * 3;
  82277. return target.set(
  82278. this.normals[i3],
  82279. this.normals[i3 + 1],
  82280. this.normals[i3 + 2]
  82281. );
  82282. };
  82283. var cli_aabb = new AABB();
  82284. /**
  82285. * @method calculateLocalInertia
  82286. * @param {Number} mass
  82287. * @param {Vec3} target
  82288. * @return {Vec3} The "target" vector object
  82289. */
  82290. Trimesh.prototype.calculateLocalInertia = function(mass,target){
  82291. // Approximate with box inertia
  82292. // Exact inertia calculation is overkill, but see http://geometrictools.com/Documentation/PolyhedralMassProperties.pdf for the correct way to do it
  82293. this.computeLocalAABB(cli_aabb);
  82294. var x = cli_aabb.upperBound.x - cli_aabb.lowerBound.x,
  82295. y = cli_aabb.upperBound.y - cli_aabb.lowerBound.y,
  82296. z = cli_aabb.upperBound.z - cli_aabb.lowerBound.z;
  82297. return target.set(
  82298. 1.0 / 12.0 * mass * ( 2*y*2*y + 2*z*2*z ),
  82299. 1.0 / 12.0 * mass * ( 2*x*2*x + 2*z*2*z ),
  82300. 1.0 / 12.0 * mass * ( 2*y*2*y + 2*x*2*x )
  82301. );
  82302. };
  82303. var computeLocalAABB_worldVert = new Vec3();
  82304. /**
  82305. * Compute the local AABB for the trimesh
  82306. * @method computeLocalAABB
  82307. * @param {AABB} aabb
  82308. */
  82309. Trimesh.prototype.computeLocalAABB = function(aabb){
  82310. var l = aabb.lowerBound,
  82311. u = aabb.upperBound,
  82312. n = this.vertices.length,
  82313. vertices = this.vertices,
  82314. v = computeLocalAABB_worldVert;
  82315. this.getVertex(0, v);
  82316. l.copy(v);
  82317. u.copy(v);
  82318. for(var i=0; i !== n; i++){
  82319. this.getVertex(i, v);
  82320. if(v.x < l.x){
  82321. l.x = v.x;
  82322. } else if(v.x > u.x){
  82323. u.x = v.x;
  82324. }
  82325. if(v.y < l.y){
  82326. l.y = v.y;
  82327. } else if(v.y > u.y){
  82328. u.y = v.y;
  82329. }
  82330. if(v.z < l.z){
  82331. l.z = v.z;
  82332. } else if(v.z > u.z){
  82333. u.z = v.z;
  82334. }
  82335. }
  82336. };
  82337. /**
  82338. * Update the .aabb property
  82339. * @method updateAABB
  82340. */
  82341. Trimesh.prototype.updateAABB = function(){
  82342. this.computeLocalAABB(this.aabb);
  82343. };
  82344. /**
  82345. * Will update the .boundingSphereRadius property
  82346. * @method updateBoundingSphereRadius
  82347. */
  82348. Trimesh.prototype.updateBoundingSphereRadius = function(){
  82349. // Assume points are distributed with local (0,0,0) as center
  82350. var max2 = 0;
  82351. var vertices = this.vertices;
  82352. var v = new Vec3();
  82353. for(var i=0, N=vertices.length / 3; i !== N; i++) {
  82354. this.getVertex(i, v);
  82355. var norm2 = v.norm2();
  82356. if(norm2 > max2){
  82357. max2 = norm2;
  82358. }
  82359. }
  82360. this.boundingSphereRadius = Math.sqrt(max2);
  82361. };
  82362. var tempWorldVertex = new Vec3();
  82363. var calculateWorldAABB_frame = new Transform();
  82364. var calculateWorldAABB_aabb = new AABB();
  82365. /**
  82366. * @method calculateWorldAABB
  82367. * @param {Vec3} pos
  82368. * @param {Quaternion} quat
  82369. * @param {Vec3} min
  82370. * @param {Vec3} max
  82371. */
  82372. Trimesh.prototype.calculateWorldAABB = function(pos,quat,min,max){
  82373. /*
  82374. var n = this.vertices.length / 3,
  82375. verts = this.vertices;
  82376. var minx,miny,minz,maxx,maxy,maxz;
  82377. var v = tempWorldVertex;
  82378. for(var i=0; i<n; i++){
  82379. this.getVertex(i, v);
  82380. quat.vmult(v, v);
  82381. pos.vadd(v, v);
  82382. if (v.x < minx || minx===undefined){
  82383. minx = v.x;
  82384. } else if(v.x > maxx || maxx===undefined){
  82385. maxx = v.x;
  82386. }
  82387. if (v.y < miny || miny===undefined){
  82388. miny = v.y;
  82389. } else if(v.y > maxy || maxy===undefined){
  82390. maxy = v.y;
  82391. }
  82392. if (v.z < minz || minz===undefined){
  82393. minz = v.z;
  82394. } else if(v.z > maxz || maxz===undefined){
  82395. maxz = v.z;
  82396. }
  82397. }
  82398. min.set(minx,miny,minz);
  82399. max.set(maxx,maxy,maxz);
  82400. */
  82401. // Faster approximation using local AABB
  82402. var frame = calculateWorldAABB_frame;
  82403. var result = calculateWorldAABB_aabb;
  82404. frame.position = pos;
  82405. frame.quaternion = quat;
  82406. this.aabb.toWorldFrame(frame, result);
  82407. min.copy(result.lowerBound);
  82408. max.copy(result.upperBound);
  82409. };
  82410. /**
  82411. * Get approximate volume
  82412. * @method volume
  82413. * @return {Number}
  82414. */
  82415. Trimesh.prototype.volume = function(){
  82416. return 4.0 * Math.PI * this.boundingSphereRadius / 3.0;
  82417. };
  82418. /**
  82419. * Create a Trimesh instance, shaped as a torus.
  82420. * @static
  82421. * @method createTorus
  82422. * @param {number} [radius=1]
  82423. * @param {number} [tube=0.5]
  82424. * @param {number} [radialSegments=8]
  82425. * @param {number} [tubularSegments=6]
  82426. * @param {number} [arc=6.283185307179586]
  82427. * @return {Trimesh} A torus
  82428. */
  82429. Trimesh.createTorus = function (radius, tube, radialSegments, tubularSegments, arc) {
  82430. radius = radius || 1;
  82431. tube = tube || 0.5;
  82432. radialSegments = radialSegments || 8;
  82433. tubularSegments = tubularSegments || 6;
  82434. arc = arc || Math.PI * 2;
  82435. var vertices = [];
  82436. var indices = [];
  82437. for ( var j = 0; j <= radialSegments; j ++ ) {
  82438. for ( var i = 0; i <= tubularSegments; i ++ ) {
  82439. var u = i / tubularSegments * arc;
  82440. var v = j / radialSegments * Math.PI * 2;
  82441. var x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  82442. var y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  82443. var z = tube * Math.sin( v );
  82444. vertices.push( x, y, z );
  82445. }
  82446. }
  82447. for ( var j = 1; j <= radialSegments; j ++ ) {
  82448. for ( var i = 1; i <= tubularSegments; i ++ ) {
  82449. var a = ( tubularSegments + 1 ) * j + i - 1;
  82450. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  82451. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  82452. var d = ( tubularSegments + 1 ) * j + i;
  82453. indices.push(a, b, d);
  82454. indices.push(b, c, d);
  82455. }
  82456. }
  82457. return new Trimesh(vertices, indices);
  82458. };
  82459. },{"../collision/AABB":3,"../math/Quaternion":28,"../math/Transform":29,"../math/Vec3":30,"../utils/Octree":50,"./Shape":43}],46:[function(_dereq_,module,exports){
  82460. module.exports = GSSolver;
  82461. var Vec3 = _dereq_('../math/Vec3');
  82462. var Quaternion = _dereq_('../math/Quaternion');
  82463. var Solver = _dereq_('./Solver');
  82464. /**
  82465. * Constraint equation Gauss-Seidel solver.
  82466. * @class GSSolver
  82467. * @constructor
  82468. * @todo The spook parameters should be specified for each constraint, not globally.
  82469. * @author schteppe / https://github.com/schteppe
  82470. * @see https://www8.cs.umu.se/kurser/5DV058/VT09/lectures/spooknotes.pdf
  82471. * @extends Solver
  82472. */
  82473. function GSSolver(){
  82474. Solver.call(this);
  82475. /**
  82476. * 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.
  82477. * @property iterations
  82478. * @type {Number}
  82479. * @todo write more about solver and iterations in the wiki
  82480. */
  82481. this.iterations = 10;
  82482. /**
  82483. * When tolerance is reached, the system is assumed to be converged.
  82484. * @property tolerance
  82485. * @type {Number}
  82486. */
  82487. this.tolerance = 1e-7;
  82488. }
  82489. GSSolver.prototype = new Solver();
  82490. var GSSolver_solve_lambda = []; // Just temporary number holders that we want to reuse each solve.
  82491. var GSSolver_solve_invCs = [];
  82492. var GSSolver_solve_Bs = [];
  82493. GSSolver.prototype.solve = function(dt,world){
  82494. var iter = 0,
  82495. maxIter = this.iterations,
  82496. tolSquared = this.tolerance*this.tolerance,
  82497. equations = this.equations,
  82498. Neq = equations.length,
  82499. bodies = world.bodies,
  82500. Nbodies = bodies.length,
  82501. h = dt,
  82502. q, B, invC, deltalambda, deltalambdaTot, GWlambda, lambdaj;
  82503. // Update solve mass
  82504. if(Neq !== 0){
  82505. for(var i=0; i!==Nbodies; i++){
  82506. bodies[i].updateSolveMassProperties();
  82507. }
  82508. }
  82509. // Things that does not change during iteration can be computed once
  82510. var invCs = GSSolver_solve_invCs,
  82511. Bs = GSSolver_solve_Bs,
  82512. lambda = GSSolver_solve_lambda;
  82513. invCs.length = Neq;
  82514. Bs.length = Neq;
  82515. lambda.length = Neq;
  82516. for(var i=0; i!==Neq; i++){
  82517. var c = equations[i];
  82518. lambda[i] = 0.0;
  82519. Bs[i] = c.computeB(h);
  82520. invCs[i] = 1.0 / c.computeC();
  82521. }
  82522. if(Neq !== 0){
  82523. // Reset vlambda
  82524. for(var i=0; i!==Nbodies; i++){
  82525. var b=bodies[i],
  82526. vlambda=b.vlambda,
  82527. wlambda=b.wlambda;
  82528. vlambda.set(0,0,0);
  82529. if(wlambda){
  82530. wlambda.set(0,0,0);
  82531. }
  82532. }
  82533. // Iterate over equations
  82534. for(iter=0; iter!==maxIter; iter++){
  82535. // Accumulate the total error for each iteration.
  82536. deltalambdaTot = 0.0;
  82537. for(var j=0; j!==Neq; j++){
  82538. var c = equations[j];
  82539. // Compute iteration
  82540. B = Bs[j];
  82541. invC = invCs[j];
  82542. lambdaj = lambda[j];
  82543. GWlambda = c.computeGWlambda();
  82544. deltalambda = invC * ( B - GWlambda - c.eps * lambdaj );
  82545. // Clamp if we are not within the min/max interval
  82546. if(lambdaj + deltalambda < c.minForce){
  82547. deltalambda = c.minForce - lambdaj;
  82548. } else if(lambdaj + deltalambda > c.maxForce){
  82549. deltalambda = c.maxForce - lambdaj;
  82550. }
  82551. lambda[j] += deltalambda;
  82552. deltalambdaTot += deltalambda > 0.0 ? deltalambda : -deltalambda; // abs(deltalambda)
  82553. c.addToWlambda(deltalambda);
  82554. }
  82555. // If the total error is small enough - stop iterate
  82556. if(deltalambdaTot*deltalambdaTot < tolSquared){
  82557. break;
  82558. }
  82559. }
  82560. // Add result to velocity
  82561. for(var i=0; i!==Nbodies; i++){
  82562. var b=bodies[i],
  82563. v=b.velocity,
  82564. w=b.angularVelocity;
  82565. v.vadd(b.vlambda, v);
  82566. if(w){
  82567. w.vadd(b.wlambda, w);
  82568. }
  82569. }
  82570. }
  82571. return iter;
  82572. };
  82573. },{"../math/Quaternion":28,"../math/Vec3":30,"./Solver":47}],47:[function(_dereq_,module,exports){
  82574. module.exports = Solver;
  82575. /**
  82576. * Constraint equation solver base class.
  82577. * @class Solver
  82578. * @constructor
  82579. * @author schteppe / https://github.com/schteppe
  82580. */
  82581. function Solver(){
  82582. /**
  82583. * All equations to be solved
  82584. * @property {Array} equations
  82585. */
  82586. this.equations = [];
  82587. }
  82588. /**
  82589. * Should be implemented in subclasses!
  82590. * @method solve
  82591. * @param {Number} dt
  82592. * @param {World} world
  82593. */
  82594. Solver.prototype.solve = function(dt,world){
  82595. // Should return the number of iterations done!
  82596. return 0;
  82597. };
  82598. /**
  82599. * Add an equation
  82600. * @method addEquation
  82601. * @param {Equation} eq
  82602. */
  82603. Solver.prototype.addEquation = function(eq){
  82604. if (eq.enabled) {
  82605. this.equations.push(eq);
  82606. }
  82607. };
  82608. /**
  82609. * Remove an equation
  82610. * @method removeEquation
  82611. * @param {Equation} eq
  82612. */
  82613. Solver.prototype.removeEquation = function(eq){
  82614. var eqs = this.equations;
  82615. var i = eqs.indexOf(eq);
  82616. if(i !== -1){
  82617. eqs.splice(i,1);
  82618. }
  82619. };
  82620. /**
  82621. * Add all equations
  82622. * @method removeAllEquations
  82623. */
  82624. Solver.prototype.removeAllEquations = function(){
  82625. this.equations.length = 0;
  82626. };
  82627. },{}],48:[function(_dereq_,module,exports){
  82628. module.exports = SplitSolver;
  82629. var Vec3 = _dereq_('../math/Vec3');
  82630. var Quaternion = _dereq_('../math/Quaternion');
  82631. var Solver = _dereq_('./Solver');
  82632. var Body = _dereq_('../objects/Body');
  82633. /**
  82634. * Splits the equations into islands and solves them independently. Can improve performance.
  82635. * @class SplitSolver
  82636. * @constructor
  82637. * @extends Solver
  82638. * @param {Solver} subsolver
  82639. */
  82640. function SplitSolver(subsolver){
  82641. Solver.call(this);
  82642. this.iterations = 10;
  82643. this.tolerance = 1e-7;
  82644. this.subsolver = subsolver;
  82645. this.nodes = [];
  82646. this.nodePool = [];
  82647. // Create needed nodes, reuse if possible
  82648. while(this.nodePool.length < 128){
  82649. this.nodePool.push(this.createNode());
  82650. }
  82651. }
  82652. SplitSolver.prototype = new Solver();
  82653. // Returns the number of subsystems
  82654. var SplitSolver_solve_nodes = []; // All allocated node objects
  82655. var SplitSolver_solve_nodePool = []; // All allocated node objects
  82656. var SplitSolver_solve_eqs = []; // Temp array
  82657. var SplitSolver_solve_bds = []; // Temp array
  82658. var SplitSolver_solve_dummyWorld = {bodies:[]}; // Temp object
  82659. var STATIC = Body.STATIC;
  82660. function getUnvisitedNode(nodes){
  82661. var Nnodes = nodes.length;
  82662. for(var i=0; i!==Nnodes; i++){
  82663. var node = nodes[i];
  82664. if(!node.visited && !(node.body.type & STATIC)){
  82665. return node;
  82666. }
  82667. }
  82668. return false;
  82669. }
  82670. var queue = [];
  82671. function bfs(root,visitFunc,bds,eqs){
  82672. queue.push(root);
  82673. root.visited = true;
  82674. visitFunc(root,bds,eqs);
  82675. while(queue.length) {
  82676. var node = queue.pop();
  82677. // Loop over unvisited child nodes
  82678. var child;
  82679. while((child = getUnvisitedNode(node.children))) {
  82680. child.visited = true;
  82681. visitFunc(child,bds,eqs);
  82682. queue.push(child);
  82683. }
  82684. }
  82685. }
  82686. function visitFunc(node,bds,eqs){
  82687. bds.push(node.body);
  82688. var Neqs = node.eqs.length;
  82689. for(var i=0; i!==Neqs; i++){
  82690. var eq = node.eqs[i];
  82691. if(eqs.indexOf(eq) === -1){
  82692. eqs.push(eq);
  82693. }
  82694. }
  82695. }
  82696. SplitSolver.prototype.createNode = function(){
  82697. return { body:null, children:[], eqs:[], visited:false };
  82698. };
  82699. /**
  82700. * Solve the subsystems
  82701. * @method solve
  82702. * @param {Number} dt
  82703. * @param {World} world
  82704. */
  82705. SplitSolver.prototype.solve = function(dt,world){
  82706. var nodes=SplitSolver_solve_nodes,
  82707. nodePool=this.nodePool,
  82708. bodies=world.bodies,
  82709. equations=this.equations,
  82710. Neq=equations.length,
  82711. Nbodies=bodies.length,
  82712. subsolver=this.subsolver;
  82713. // Create needed nodes, reuse if possible
  82714. while(nodePool.length < Nbodies){
  82715. nodePool.push(this.createNode());
  82716. }
  82717. nodes.length = Nbodies;
  82718. for (var i = 0; i < Nbodies; i++) {
  82719. nodes[i] = nodePool[i];
  82720. }
  82721. // Reset node values
  82722. for(var i=0; i!==Nbodies; i++){
  82723. var node = nodes[i];
  82724. node.body = bodies[i];
  82725. node.children.length = 0;
  82726. node.eqs.length = 0;
  82727. node.visited = false;
  82728. }
  82729. for(var k=0; k!==Neq; k++){
  82730. var eq=equations[k],
  82731. i=bodies.indexOf(eq.bi),
  82732. j=bodies.indexOf(eq.bj),
  82733. ni=nodes[i],
  82734. nj=nodes[j];
  82735. ni.children.push(nj);
  82736. ni.eqs.push(eq);
  82737. nj.children.push(ni);
  82738. nj.eqs.push(eq);
  82739. }
  82740. var child, n=0, eqs=SplitSolver_solve_eqs;
  82741. subsolver.tolerance = this.tolerance;
  82742. subsolver.iterations = this.iterations;
  82743. var dummyWorld = SplitSolver_solve_dummyWorld;
  82744. while((child = getUnvisitedNode(nodes))){
  82745. eqs.length = 0;
  82746. dummyWorld.bodies.length = 0;
  82747. bfs(child, visitFunc, dummyWorld.bodies, eqs);
  82748. var Neqs = eqs.length;
  82749. eqs = eqs.sort(sortById);
  82750. for(var i=0; i!==Neqs; i++){
  82751. subsolver.addEquation(eqs[i]);
  82752. }
  82753. var iter = subsolver.solve(dt,dummyWorld);
  82754. subsolver.removeAllEquations();
  82755. n++;
  82756. }
  82757. return n;
  82758. };
  82759. function sortById(a, b){
  82760. return b.id - a.id;
  82761. }
  82762. },{"../math/Quaternion":28,"../math/Vec3":30,"../objects/Body":31,"./Solver":47}],49:[function(_dereq_,module,exports){
  82763. /**
  82764. * Base class for objects that dispatches events.
  82765. * @class EventTarget
  82766. * @constructor
  82767. */
  82768. var EventTarget = function () {
  82769. };
  82770. module.exports = EventTarget;
  82771. EventTarget.prototype = {
  82772. constructor: EventTarget,
  82773. /**
  82774. * Add an event listener
  82775. * @method addEventListener
  82776. * @param {String} type
  82777. * @param {Function} listener
  82778. * @return {EventTarget} The self object, for chainability.
  82779. */
  82780. addEventListener: function ( type, listener ) {
  82781. if ( this._listeners === undefined ){ this._listeners = {}; }
  82782. var listeners = this._listeners;
  82783. if ( listeners[ type ] === undefined ) {
  82784. listeners[ type ] = [];
  82785. }
  82786. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  82787. listeners[ type ].push( listener );
  82788. }
  82789. return this;
  82790. },
  82791. /**
  82792. * Check if an event listener is added
  82793. * @method hasEventListener
  82794. * @param {String} type
  82795. * @param {Function} listener
  82796. * @return {Boolean}
  82797. */
  82798. hasEventListener: function ( type, listener ) {
  82799. if ( this._listeners === undefined ){ return false; }
  82800. var listeners = this._listeners;
  82801. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  82802. return true;
  82803. }
  82804. return false;
  82805. },
  82806. /**
  82807. * Remove an event listener
  82808. * @method removeEventListener
  82809. * @param {String} type
  82810. * @param {Function} listener
  82811. * @return {EventTarget} The self object, for chainability.
  82812. */
  82813. removeEventListener: function ( type, listener ) {
  82814. if ( this._listeners === undefined ){ return this; }
  82815. var listeners = this._listeners;
  82816. if ( listeners[type] === undefined ){ return this; }
  82817. var index = listeners[ type ].indexOf( listener );
  82818. if ( index !== - 1 ) {
  82819. listeners[ type ].splice( index, 1 );
  82820. }
  82821. return this;
  82822. },
  82823. /**
  82824. * Emit an event.
  82825. * @method dispatchEvent
  82826. * @param {Object} event
  82827. * @param {String} event.type
  82828. * @return {EventTarget} The self object, for chainability.
  82829. */
  82830. dispatchEvent: function ( event ) {
  82831. if ( this._listeners === undefined ){ return this; }
  82832. var listeners = this._listeners;
  82833. var listenerArray = listeners[ event.type ];
  82834. if ( listenerArray !== undefined ) {
  82835. event.target = this;
  82836. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  82837. listenerArray[ i ].call( this, event );
  82838. }
  82839. }
  82840. return this;
  82841. }
  82842. };
  82843. },{}],50:[function(_dereq_,module,exports){
  82844. var AABB = _dereq_('../collision/AABB');
  82845. var Vec3 = _dereq_('../math/Vec3');
  82846. module.exports = Octree;
  82847. /**
  82848. * @class OctreeNode
  82849. * @param {object} [options]
  82850. * @param {Octree} [options.root]
  82851. * @param {AABB} [options.aabb]
  82852. */
  82853. function OctreeNode(options){
  82854. options = options || {};
  82855. /**
  82856. * The root node
  82857. * @property {OctreeNode} root
  82858. */
  82859. this.root = options.root || null;
  82860. /**
  82861. * Boundary of this node
  82862. * @property {AABB} aabb
  82863. */
  82864. this.aabb = options.aabb ? options.aabb.clone() : new AABB();
  82865. /**
  82866. * Contained data at the current node level.
  82867. * @property {Array} data
  82868. */
  82869. this.data = [];
  82870. /**
  82871. * Children to this node
  82872. * @property {Array} children
  82873. */
  82874. this.children = [];
  82875. }
  82876. /**
  82877. * @class Octree
  82878. * @param {AABB} aabb The total AABB of the tree
  82879. * @param {object} [options]
  82880. * @param {number} [options.maxDepth=8]
  82881. * @extends OctreeNode
  82882. */
  82883. function Octree(aabb, options){
  82884. options = options || {};
  82885. options.root = null;
  82886. options.aabb = aabb;
  82887. OctreeNode.call(this, options);
  82888. /**
  82889. * Maximum subdivision depth
  82890. * @property {number} maxDepth
  82891. */
  82892. this.maxDepth = typeof(options.maxDepth) !== 'undefined' ? options.maxDepth : 8;
  82893. }
  82894. Octree.prototype = new OctreeNode();
  82895. OctreeNode.prototype.reset = function(aabb, options){
  82896. this.children.length = this.data.length = 0;
  82897. };
  82898. /**
  82899. * Insert data into this node
  82900. * @method insert
  82901. * @param {AABB} aabb
  82902. * @param {object} elementData
  82903. * @return {boolean} True if successful, otherwise false
  82904. */
  82905. OctreeNode.prototype.insert = function(aabb, elementData, level){
  82906. var nodeData = this.data;
  82907. level = level || 0;
  82908. // Ignore objects that do not belong in this node
  82909. if (!this.aabb.contains(aabb)){
  82910. return false; // object cannot be added
  82911. }
  82912. var children = this.children;
  82913. if(level < (this.maxDepth || this.root.maxDepth)){
  82914. // Subdivide if there are no children yet
  82915. var subdivided = false;
  82916. if (!children.length){
  82917. this.subdivide();
  82918. subdivided = true;
  82919. }
  82920. // add to whichever node will accept it
  82921. for (var i = 0; i !== 8; i++) {
  82922. if (children[i].insert(aabb, elementData, level + 1)){
  82923. return true;
  82924. }
  82925. }
  82926. if(subdivided){
  82927. // No children accepted! Might as well just remove em since they contain none
  82928. children.length = 0;
  82929. }
  82930. }
  82931. // Too deep, or children didnt want it. add it in current node
  82932. nodeData.push(elementData);
  82933. return true;
  82934. };
  82935. var halfDiagonal = new Vec3();
  82936. /**
  82937. * Create 8 equally sized children nodes and put them in the .children array.
  82938. * @method subdivide
  82939. */
  82940. OctreeNode.prototype.subdivide = function() {
  82941. var aabb = this.aabb;
  82942. var l = aabb.lowerBound;
  82943. var u = aabb.upperBound;
  82944. var children = this.children;
  82945. children.push(
  82946. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(0,0,0) }) }),
  82947. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(1,0,0) }) }),
  82948. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(1,1,0) }) }),
  82949. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(1,1,1) }) }),
  82950. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(0,1,1) }) }),
  82951. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(0,0,1) }) }),
  82952. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(1,0,1) }) }),
  82953. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(0,1,0) }) })
  82954. );
  82955. u.vsub(l, halfDiagonal);
  82956. halfDiagonal.scale(0.5, halfDiagonal);
  82957. var root = this.root || this;
  82958. for (var i = 0; i !== 8; i++) {
  82959. var child = children[i];
  82960. // Set current node as root
  82961. child.root = root;
  82962. // Compute bounds
  82963. var lowerBound = child.aabb.lowerBound;
  82964. lowerBound.x *= halfDiagonal.x;
  82965. lowerBound.y *= halfDiagonal.y;
  82966. lowerBound.z *= halfDiagonal.z;
  82967. lowerBound.vadd(l, lowerBound);
  82968. // Upper bound is always lower bound + halfDiagonal
  82969. lowerBound.vadd(halfDiagonal, child.aabb.upperBound);
  82970. }
  82971. };
  82972. /**
  82973. * Get all data, potentially within an AABB
  82974. * @method aabbQuery
  82975. * @param {AABB} aabb
  82976. * @param {array} result
  82977. * @return {array} The "result" object
  82978. */
  82979. OctreeNode.prototype.aabbQuery = function(aabb, result) {
  82980. var nodeData = this.data;
  82981. // abort if the range does not intersect this node
  82982. // if (!this.aabb.overlaps(aabb)){
  82983. // return result;
  82984. // }
  82985. // Add objects at this level
  82986. // Array.prototype.push.apply(result, nodeData);
  82987. // Add child data
  82988. // @todo unwrap recursion into a queue / loop, that's faster in JS
  82989. var children = this.children;
  82990. // for (var i = 0, N = this.children.length; i !== N; i++) {
  82991. // children[i].aabbQuery(aabb, result);
  82992. // }
  82993. var queue = [this];
  82994. while (queue.length) {
  82995. var node = queue.pop();
  82996. if (node.aabb.overlaps(aabb)){
  82997. Array.prototype.push.apply(result, node.data);
  82998. }
  82999. Array.prototype.push.apply(queue, node.children);
  83000. }
  83001. return result;
  83002. };
  83003. var tmpAABB = new AABB();
  83004. /**
  83005. * Get all data, potentially intersected by a ray.
  83006. * @method rayQuery
  83007. * @param {Ray} ray
  83008. * @param {Transform} treeTransform
  83009. * @param {array} result
  83010. * @return {array} The "result" object
  83011. */
  83012. OctreeNode.prototype.rayQuery = function(ray, treeTransform, result) {
  83013. // Use aabb query for now.
  83014. // @todo implement real ray query which needs less lookups
  83015. ray.getAABB(tmpAABB);
  83016. tmpAABB.toLocalFrame(treeTransform, tmpAABB);
  83017. this.aabbQuery(tmpAABB, result);
  83018. return result;
  83019. };
  83020. /**
  83021. * @method removeEmptyNodes
  83022. */
  83023. OctreeNode.prototype.removeEmptyNodes = function() {
  83024. var queue = [this];
  83025. while (queue.length) {
  83026. var node = queue.pop();
  83027. for (var i = node.children.length - 1; i >= 0; i--) {
  83028. if(!node.children[i].data.length){
  83029. node.children.splice(i, 1);
  83030. }
  83031. }
  83032. Array.prototype.push.apply(queue, node.children);
  83033. }
  83034. };
  83035. },{"../collision/AABB":3,"../math/Vec3":30}],51:[function(_dereq_,module,exports){
  83036. module.exports = Pool;
  83037. /**
  83038. * For pooling objects that can be reused.
  83039. * @class Pool
  83040. * @constructor
  83041. */
  83042. function Pool(){
  83043. /**
  83044. * The pooled objects
  83045. * @property {Array} objects
  83046. */
  83047. this.objects = [];
  83048. /**
  83049. * Constructor of the objects
  83050. * @property {mixed} type
  83051. */
  83052. this.type = Object;
  83053. }
  83054. /**
  83055. * Release an object after use
  83056. * @method release
  83057. * @param {Object} obj
  83058. */
  83059. Pool.prototype.release = function(){
  83060. var Nargs = arguments.length;
  83061. for(var i=0; i!==Nargs; i++){
  83062. this.objects.push(arguments[i]);
  83063. }
  83064. };
  83065. /**
  83066. * Get an object
  83067. * @method get
  83068. * @return {mixed}
  83069. */
  83070. Pool.prototype.get = function(){
  83071. if(this.objects.length===0){
  83072. return this.constructObject();
  83073. } else {
  83074. return this.objects.pop();
  83075. }
  83076. };
  83077. /**
  83078. * Construct an object. Should be implmented in each subclass.
  83079. * @method constructObject
  83080. * @return {mixed}
  83081. */
  83082. Pool.prototype.constructObject = function(){
  83083. throw new Error("constructObject() not implemented in this Pool subclass yet!");
  83084. };
  83085. },{}],52:[function(_dereq_,module,exports){
  83086. module.exports = TupleDictionary;
  83087. /**
  83088. * @class TupleDictionary
  83089. * @constructor
  83090. */
  83091. function TupleDictionary() {
  83092. /**
  83093. * The data storage
  83094. * @property data
  83095. * @type {Object}
  83096. */
  83097. this.data = { keys:[] };
  83098. }
  83099. /**
  83100. * @method get
  83101. * @param {Number} i
  83102. * @param {Number} j
  83103. * @return {Number}
  83104. */
  83105. TupleDictionary.prototype.get = function(i, j) {
  83106. if (i > j) {
  83107. // swap
  83108. var temp = j;
  83109. j = i;
  83110. i = temp;
  83111. }
  83112. return this.data[i+'-'+j];
  83113. };
  83114. /**
  83115. * @method set
  83116. * @param {Number} i
  83117. * @param {Number} j
  83118. * @param {Number} value
  83119. */
  83120. TupleDictionary.prototype.set = function(i, j, value) {
  83121. if (i > j) {
  83122. var temp = j;
  83123. j = i;
  83124. i = temp;
  83125. }
  83126. var key = i+'-'+j;
  83127. // Check if key already exists
  83128. if(!this.get(i,j)){
  83129. this.data.keys.push(key);
  83130. }
  83131. this.data[key] = value;
  83132. };
  83133. /**
  83134. * @method reset
  83135. */
  83136. TupleDictionary.prototype.reset = function() {
  83137. var data = this.data,
  83138. keys = data.keys;
  83139. while(keys.length > 0){
  83140. var key = keys.pop();
  83141. delete data[key];
  83142. }
  83143. };
  83144. },{}],53:[function(_dereq_,module,exports){
  83145. function Utils(){}
  83146. module.exports = Utils;
  83147. /**
  83148. * Extend an options object with default values.
  83149. * @static
  83150. * @method defaults
  83151. * @param {object} options The options object. May be falsy: in this case, a new object is created and returned.
  83152. * @param {object} defaults An object containing default values.
  83153. * @return {object} The modified options object.
  83154. */
  83155. Utils.defaults = function(options, defaults){
  83156. options = options || {};
  83157. for(var key in defaults){
  83158. if(!(key in options)){
  83159. options[key] = defaults[key];
  83160. }
  83161. }
  83162. return options;
  83163. };
  83164. },{}],54:[function(_dereq_,module,exports){
  83165. module.exports = Vec3Pool;
  83166. var Vec3 = _dereq_('../math/Vec3');
  83167. var Pool = _dereq_('./Pool');
  83168. /**
  83169. * @class Vec3Pool
  83170. * @constructor
  83171. * @extends Pool
  83172. */
  83173. function Vec3Pool(){
  83174. Pool.call(this);
  83175. this.type = Vec3;
  83176. }
  83177. Vec3Pool.prototype = new Pool();
  83178. /**
  83179. * Construct a vector
  83180. * @method constructObject
  83181. * @return {Vec3}
  83182. */
  83183. Vec3Pool.prototype.constructObject = function(){
  83184. return new Vec3();
  83185. };
  83186. },{"../math/Vec3":30,"./Pool":51}],55:[function(_dereq_,module,exports){
  83187. module.exports = Narrowphase;
  83188. var AABB = _dereq_('../collision/AABB');
  83189. var Shape = _dereq_('../shapes/Shape');
  83190. var Ray = _dereq_('../collision/Ray');
  83191. var Vec3 = _dereq_('../math/Vec3');
  83192. var Transform = _dereq_('../math/Transform');
  83193. var ConvexPolyhedron = _dereq_('../shapes/ConvexPolyhedron');
  83194. var Quaternion = _dereq_('../math/Quaternion');
  83195. var Solver = _dereq_('../solver/Solver');
  83196. var Vec3Pool = _dereq_('../utils/Vec3Pool');
  83197. var ContactEquation = _dereq_('../equations/ContactEquation');
  83198. var FrictionEquation = _dereq_('../equations/FrictionEquation');
  83199. /**
  83200. * Helper class for the World. Generates ContactEquations.
  83201. * @class Narrowphase
  83202. * @constructor
  83203. * @todo Sphere-ConvexPolyhedron contacts
  83204. * @todo Contact reduction
  83205. * @todo should move methods to prototype
  83206. */
  83207. function Narrowphase(world){
  83208. /**
  83209. * Internal storage of pooled contact points.
  83210. * @property {Array} contactPointPool
  83211. */
  83212. this.contactPointPool = [];
  83213. this.frictionEquationPool = [];
  83214. this.result = [];
  83215. this.frictionResult = [];
  83216. /**
  83217. * Pooled vectors.
  83218. * @property {Vec3Pool} v3pool
  83219. */
  83220. this.v3pool = new Vec3Pool();
  83221. this.world = world;
  83222. this.currentContactMaterial = null;
  83223. /**
  83224. * @property {Boolean} enableFrictionReduction
  83225. */
  83226. this.enableFrictionReduction = false;
  83227. }
  83228. /**
  83229. * Make a contact object, by using the internal pool or creating a new one.
  83230. * @method createContactEquation
  83231. * @return {ContactEquation}
  83232. */
  83233. Narrowphase.prototype.createContactEquation = function(bi, bj, si, sj, rsi, rsj){
  83234. var c;
  83235. if(this.contactPointPool.length){
  83236. c = this.contactPointPool.pop();
  83237. c.bi = bi;
  83238. c.bj = bj;
  83239. } else {
  83240. c = new ContactEquation(bi, bj);
  83241. }
  83242. c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;
  83243. var cm = this.currentContactMaterial;
  83244. c.restitution = cm.restitution;
  83245. c.setSpookParams(
  83246. cm.contactEquationStiffness,
  83247. cm.contactEquationRelaxation,
  83248. this.world.dt
  83249. );
  83250. var matA = si.material || bi.material;
  83251. var matB = sj.material || bj.material;
  83252. if(matA && matB && matA.restitution >= 0 && matB.restitution >= 0){
  83253. c.restitution = matA.restitution * matB.restitution;
  83254. }
  83255. c.si = rsi || si;
  83256. c.sj = rsj || sj;
  83257. return c;
  83258. };
  83259. Narrowphase.prototype.createFrictionEquationsFromContact = function(contactEquation, outArray){
  83260. var bodyA = contactEquation.bi;
  83261. var bodyB = contactEquation.bj;
  83262. var shapeA = contactEquation.si;
  83263. var shapeB = contactEquation.sj;
  83264. var world = this.world;
  83265. var cm = this.currentContactMaterial;
  83266. // If friction or restitution were specified in the material, use them
  83267. var friction = cm.friction;
  83268. var matA = shapeA.material || bodyA.material;
  83269. var matB = shapeB.material || bodyB.material;
  83270. if(matA && matB && matA.friction >= 0 && matB.friction >= 0){
  83271. friction = matA.friction * matB.friction;
  83272. }
  83273. if(friction > 0){
  83274. // Create 2 tangent equations
  83275. var mug = friction * world.gravity.length();
  83276. var reducedMass = (bodyA.invMass + bodyB.invMass);
  83277. if(reducedMass > 0){
  83278. reducedMass = 1/reducedMass;
  83279. }
  83280. var pool = this.frictionEquationPool;
  83281. var c1 = pool.length ? pool.pop() : new FrictionEquation(bodyA,bodyB,mug*reducedMass);
  83282. var c2 = pool.length ? pool.pop() : new FrictionEquation(bodyA,bodyB,mug*reducedMass);
  83283. c1.bi = c2.bi = bodyA;
  83284. c1.bj = c2.bj = bodyB;
  83285. c1.minForce = c2.minForce = -mug*reducedMass;
  83286. c1.maxForce = c2.maxForce = mug*reducedMass;
  83287. // Copy over the relative vectors
  83288. c1.ri.copy(contactEquation.ri);
  83289. c1.rj.copy(contactEquation.rj);
  83290. c2.ri.copy(contactEquation.ri);
  83291. c2.rj.copy(contactEquation.rj);
  83292. // Construct tangents
  83293. contactEquation.ni.tangents(c1.t, c2.t);
  83294. // Set spook params
  83295. c1.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, world.dt);
  83296. c2.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, world.dt);
  83297. c1.enabled = c2.enabled = contactEquation.enabled;
  83298. outArray.push(c1, c2);
  83299. return true;
  83300. }
  83301. return false;
  83302. };
  83303. var averageNormal = new Vec3();
  83304. var averageContactPointA = new Vec3();
  83305. var averageContactPointB = new Vec3();
  83306. // Take the average N latest contact point on the plane.
  83307. Narrowphase.prototype.createFrictionFromAverage = function(numContacts){
  83308. // The last contactEquation
  83309. var c = this.result[this.result.length - 1];
  83310. // Create the result: two "average" friction equations
  83311. if (!this.createFrictionEquationsFromContact(c, this.frictionResult) || numContacts === 1) {
  83312. return;
  83313. }
  83314. var f1 = this.frictionResult[this.frictionResult.length - 2];
  83315. var f2 = this.frictionResult[this.frictionResult.length - 1];
  83316. averageNormal.setZero();
  83317. averageContactPointA.setZero();
  83318. averageContactPointB.setZero();
  83319. var bodyA = c.bi;
  83320. var bodyB = c.bj;
  83321. for(var i=0; i!==numContacts; i++){
  83322. c = this.result[this.result.length - 1 - i];
  83323. if(c.bodyA !== bodyA){
  83324. averageNormal.vadd(c.ni, averageNormal); // vec2.add(eq.t, eq.t, c.normalA);
  83325. averageContactPointA.vadd(c.ri, averageContactPointA); // vec2.add(eq.contactPointA, eq.contactPointA, c.contactPointA);
  83326. averageContactPointB.vadd(c.rj, averageContactPointB);
  83327. } else {
  83328. averageNormal.vsub(c.ni, averageNormal); // vec2.sub(eq.t, eq.t, c.normalA);
  83329. averageContactPointA.vadd(c.rj, averageContactPointA); // vec2.add(eq.contactPointA, eq.contactPointA, c.contactPointA);
  83330. averageContactPointB.vadd(c.ri, averageContactPointB);
  83331. }
  83332. }
  83333. var invNumContacts = 1 / numContacts;
  83334. averageContactPointA.scale(invNumContacts, f1.ri); // vec2.scale(eq.contactPointA, eq.contactPointA, invNumContacts);
  83335. averageContactPointB.scale(invNumContacts, f1.rj); // vec2.scale(eq.contactPointB, eq.contactPointB, invNumContacts);
  83336. f2.ri.copy(f1.ri); // Should be the same
  83337. f2.rj.copy(f1.rj);
  83338. averageNormal.normalize();
  83339. averageNormal.tangents(f1.t, f2.t);
  83340. // return eq;
  83341. };
  83342. var tmpVec1 = new Vec3();
  83343. var tmpVec2 = new Vec3();
  83344. var tmpQuat1 = new Quaternion();
  83345. var tmpQuat2 = new Quaternion();
  83346. /**
  83347. * Generate all contacts between a list of body pairs
  83348. * @method getContacts
  83349. * @param {array} p1 Array of body indices
  83350. * @param {array} p2 Array of body indices
  83351. * @param {World} world
  83352. * @param {array} result Array to store generated contacts
  83353. * @param {array} oldcontacts Optional. Array of reusable contact objects
  83354. */
  83355. Narrowphase.prototype.getContacts = function(p1, p2, world, result, oldcontacts, frictionResult, frictionPool){
  83356. // Save old contact objects
  83357. this.contactPointPool = oldcontacts;
  83358. this.frictionEquationPool = frictionPool;
  83359. this.result = result;
  83360. this.frictionResult = frictionResult;
  83361. var qi = tmpQuat1;
  83362. var qj = tmpQuat2;
  83363. var xi = tmpVec1;
  83364. var xj = tmpVec2;
  83365. for(var k=0, N=p1.length; k!==N; k++){
  83366. // Get current collision bodies
  83367. var bi = p1[k],
  83368. bj = p2[k];
  83369. // Get contact material
  83370. var bodyContactMaterial = null;
  83371. if(bi.material && bj.material){
  83372. bodyContactMaterial = world.getContactMaterial(bi.material,bj.material) || null;
  83373. }
  83374. for (var i = 0; i < bi.shapes.length; i++) {
  83375. bi.quaternion.mult(bi.shapeOrientations[i], qi);
  83376. bi.quaternion.vmult(bi.shapeOffsets[i], xi);
  83377. xi.vadd(bi.position, xi);
  83378. var si = bi.shapes[i];
  83379. for (var j = 0; j < bj.shapes.length; j++) {
  83380. // Compute world transform of shapes
  83381. bj.quaternion.mult(bj.shapeOrientations[j], qj);
  83382. bj.quaternion.vmult(bj.shapeOffsets[j], xj);
  83383. xj.vadd(bj.position, xj);
  83384. var sj = bj.shapes[j];
  83385. if(xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius){
  83386. continue;
  83387. }
  83388. // Get collision material
  83389. var shapeContactMaterial = null;
  83390. if(si.material && sj.material){
  83391. shapeContactMaterial = world.getContactMaterial(si.material,sj.material) || null;
  83392. }
  83393. this.currentContactMaterial = shapeContactMaterial || bodyContactMaterial || world.defaultContactMaterial;
  83394. // Get contacts
  83395. var resolver = this[si.type | sj.type];
  83396. if(resolver){
  83397. if (si.type < sj.type) {
  83398. resolver.call(this, si, sj, xi, xj, qi, qj, bi, bj, si, sj);
  83399. } else {
  83400. resolver.call(this, sj, si, xj, xi, qj, qi, bj, bi, si, sj);
  83401. }
  83402. }
  83403. }
  83404. }
  83405. }
  83406. };
  83407. var numWarnings = 0;
  83408. var maxWarnings = 10;
  83409. function warn(msg){
  83410. if(numWarnings > maxWarnings){
  83411. return;
  83412. }
  83413. numWarnings++;
  83414. console.warn(msg);
  83415. }
  83416. Narrowphase.prototype[Shape.types.BOX | Shape.types.BOX] =
  83417. Narrowphase.prototype.boxBox = function(si,sj,xi,xj,qi,qj,bi,bj){
  83418. si.convexPolyhedronRepresentation.material = si.material;
  83419. sj.convexPolyhedronRepresentation.material = sj.material;
  83420. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  83421. sj.convexPolyhedronRepresentation.collisionResponse = sj.collisionResponse;
  83422. this.convexConvex(si.convexPolyhedronRepresentation,sj.convexPolyhedronRepresentation,xi,xj,qi,qj,bi,bj,si,sj);
  83423. };
  83424. Narrowphase.prototype[Shape.types.BOX | Shape.types.CONVEXPOLYHEDRON] =
  83425. Narrowphase.prototype.boxConvex = function(si,sj,xi,xj,qi,qj,bi,bj){
  83426. si.convexPolyhedronRepresentation.material = si.material;
  83427. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  83428. this.convexConvex(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj);
  83429. };
  83430. Narrowphase.prototype[Shape.types.BOX | Shape.types.PARTICLE] =
  83431. Narrowphase.prototype.boxParticle = function(si,sj,xi,xj,qi,qj,bi,bj){
  83432. si.convexPolyhedronRepresentation.material = si.material;
  83433. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  83434. this.convexParticle(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj);
  83435. };
  83436. /**
  83437. * @method sphereSphere
  83438. * @param {Shape} si
  83439. * @param {Shape} sj
  83440. * @param {Vec3} xi
  83441. * @param {Vec3} xj
  83442. * @param {Quaternion} qi
  83443. * @param {Quaternion} qj
  83444. * @param {Body} bi
  83445. * @param {Body} bj
  83446. */
  83447. Narrowphase.prototype[Shape.types.SPHERE] =
  83448. Narrowphase.prototype.sphereSphere = function(si,sj,xi,xj,qi,qj,bi,bj){
  83449. // We will have only one contact in this case
  83450. var r = this.createContactEquation(bi,bj,si,sj);
  83451. // Contact normal
  83452. xj.vsub(xi, r.ni);
  83453. r.ni.normalize();
  83454. // Contact point locations
  83455. r.ri.copy(r.ni);
  83456. r.rj.copy(r.ni);
  83457. r.ri.mult(si.radius, r.ri);
  83458. r.rj.mult(-sj.radius, r.rj);
  83459. r.ri.vadd(xi, r.ri);
  83460. r.ri.vsub(bi.position, r.ri);
  83461. r.rj.vadd(xj, r.rj);
  83462. r.rj.vsub(bj.position, r.rj);
  83463. this.result.push(r);
  83464. this.createFrictionEquationsFromContact(r, this.frictionResult);
  83465. };
  83466. /**
  83467. * @method planeTrimesh
  83468. * @param {Shape} si
  83469. * @param {Shape} sj
  83470. * @param {Vec3} xi
  83471. * @param {Vec3} xj
  83472. * @param {Quaternion} qi
  83473. * @param {Quaternion} qj
  83474. * @param {Body} bi
  83475. * @param {Body} bj
  83476. */
  83477. var planeTrimesh_normal = new Vec3();
  83478. var planeTrimesh_relpos = new Vec3();
  83479. var planeTrimesh_projected = new Vec3();
  83480. Narrowphase.prototype[Shape.types.PLANE | Shape.types.TRIMESH] =
  83481. Narrowphase.prototype.planeTrimesh = function(
  83482. planeShape,
  83483. trimeshShape,
  83484. planePos,
  83485. trimeshPos,
  83486. planeQuat,
  83487. trimeshQuat,
  83488. planeBody,
  83489. trimeshBody
  83490. ){
  83491. // Make contacts!
  83492. var v = new Vec3();
  83493. var normal = planeTrimesh_normal;
  83494. normal.set(0,0,1);
  83495. planeQuat.vmult(normal,normal); // Turn normal according to plane
  83496. for(var i=0; i<trimeshShape.vertices.length / 3; i++){
  83497. // Get world vertex from trimesh
  83498. trimeshShape.getVertex(i, v);
  83499. // Safe up
  83500. var v2 = new Vec3();
  83501. v2.copy(v);
  83502. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, v2, v);
  83503. // Check plane side
  83504. var relpos = planeTrimesh_relpos;
  83505. v.vsub(planePos, relpos);
  83506. var dot = normal.dot(relpos);
  83507. if(dot <= 0.0){
  83508. var r = this.createContactEquation(planeBody,trimeshBody,planeShape,trimeshShape);
  83509. r.ni.copy(normal); // Contact normal is the plane normal
  83510. // Get vertex position projected on plane
  83511. var projected = planeTrimesh_projected;
  83512. normal.scale(relpos.dot(normal), projected);
  83513. v.vsub(projected,projected);
  83514. // ri is the projected world position minus plane position
  83515. r.ri.copy(projected);
  83516. r.ri.vsub(planeBody.position, r.ri);
  83517. r.rj.copy(v);
  83518. r.rj.vsub(trimeshBody.position, r.rj);
  83519. // Store result
  83520. this.result.push(r);
  83521. this.createFrictionEquationsFromContact(r, this.frictionResult);
  83522. }
  83523. }
  83524. };
  83525. /**
  83526. * @method sphereTrimesh
  83527. * @param {Shape} sphereShape
  83528. * @param {Shape} trimeshShape
  83529. * @param {Vec3} spherePos
  83530. * @param {Vec3} trimeshPos
  83531. * @param {Quaternion} sphereQuat
  83532. * @param {Quaternion} trimeshQuat
  83533. * @param {Body} sphereBody
  83534. * @param {Body} trimeshBody
  83535. */
  83536. var sphereTrimesh_normal = new Vec3();
  83537. var sphereTrimesh_relpos = new Vec3();
  83538. var sphereTrimesh_projected = new Vec3();
  83539. var sphereTrimesh_v = new Vec3();
  83540. var sphereTrimesh_v2 = new Vec3();
  83541. var sphereTrimesh_edgeVertexA = new Vec3();
  83542. var sphereTrimesh_edgeVertexB = new Vec3();
  83543. var sphereTrimesh_edgeVector = new Vec3();
  83544. var sphereTrimesh_edgeVectorUnit = new Vec3();
  83545. var sphereTrimesh_localSpherePos = new Vec3();
  83546. var sphereTrimesh_tmp = new Vec3();
  83547. var sphereTrimesh_va = new Vec3();
  83548. var sphereTrimesh_vb = new Vec3();
  83549. var sphereTrimesh_vc = new Vec3();
  83550. var sphereTrimesh_localSphereAABB = new AABB();
  83551. var sphereTrimesh_triangles = [];
  83552. Narrowphase.prototype[Shape.types.SPHERE | Shape.types.TRIMESH] =
  83553. Narrowphase.prototype.sphereTrimesh = function (
  83554. sphereShape,
  83555. trimeshShape,
  83556. spherePos,
  83557. trimeshPos,
  83558. sphereQuat,
  83559. trimeshQuat,
  83560. sphereBody,
  83561. trimeshBody
  83562. ) {
  83563. var edgeVertexA = sphereTrimesh_edgeVertexA;
  83564. var edgeVertexB = sphereTrimesh_edgeVertexB;
  83565. var edgeVector = sphereTrimesh_edgeVector;
  83566. var edgeVectorUnit = sphereTrimesh_edgeVectorUnit;
  83567. var localSpherePos = sphereTrimesh_localSpherePos;
  83568. var tmp = sphereTrimesh_tmp;
  83569. var localSphereAABB = sphereTrimesh_localSphereAABB;
  83570. var v2 = sphereTrimesh_v2;
  83571. var relpos = sphereTrimesh_relpos;
  83572. var triangles = sphereTrimesh_triangles;
  83573. // Convert sphere position to local in the trimesh
  83574. Transform.pointToLocalFrame(trimeshPos, trimeshQuat, spherePos, localSpherePos);
  83575. // Get the aabb of the sphere locally in the trimesh
  83576. var sphereRadius = sphereShape.radius;
  83577. localSphereAABB.lowerBound.set(
  83578. localSpherePos.x - sphereRadius,
  83579. localSpherePos.y - sphereRadius,
  83580. localSpherePos.z - sphereRadius
  83581. );
  83582. localSphereAABB.upperBound.set(
  83583. localSpherePos.x + sphereRadius,
  83584. localSpherePos.y + sphereRadius,
  83585. localSpherePos.z + sphereRadius
  83586. );
  83587. trimeshShape.getTrianglesInAABB(localSphereAABB, triangles);
  83588. //for (var i = 0; i < trimeshShape.indices.length / 3; i++) triangles.push(i); // All
  83589. // Vertices
  83590. var v = sphereTrimesh_v;
  83591. var radiusSquared = sphereShape.radius * sphereShape.radius;
  83592. for(var i=0; i<triangles.length; i++){
  83593. for (var j = 0; j < 3; j++) {
  83594. trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + j], v);
  83595. // Check vertex overlap in sphere
  83596. v.vsub(localSpherePos, relpos);
  83597. if(relpos.norm2() <= radiusSquared){
  83598. // Safe up
  83599. v2.copy(v);
  83600. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, v2, v);
  83601. v.vsub(spherePos, relpos);
  83602. var r = this.createContactEquation(sphereBody,trimeshBody,sphereShape,trimeshShape);
  83603. r.ni.copy(relpos);
  83604. r.ni.normalize();
  83605. // ri is the vector from sphere center to the sphere surface
  83606. r.ri.copy(r.ni);
  83607. r.ri.scale(sphereShape.radius, r.ri);
  83608. r.ri.vadd(spherePos, r.ri);
  83609. r.ri.vsub(sphereBody.position, r.ri);
  83610. r.rj.copy(v);
  83611. r.rj.vsub(trimeshBody.position, r.rj);
  83612. // Store result
  83613. this.result.push(r);
  83614. this.createFrictionEquationsFromContact(r, this.frictionResult);
  83615. }
  83616. }
  83617. }
  83618. // Check all edges
  83619. for(var i=0; i<triangles.length; i++){
  83620. for (var j = 0; j < 3; j++) {
  83621. trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + j], edgeVertexA);
  83622. trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + ((j+1)%3)], edgeVertexB);
  83623. edgeVertexB.vsub(edgeVertexA, edgeVector);
  83624. // Project sphere position to the edge
  83625. localSpherePos.vsub(edgeVertexB, tmp);
  83626. var positionAlongEdgeB = tmp.dot(edgeVector);
  83627. localSpherePos.vsub(edgeVertexA, tmp);
  83628. var positionAlongEdgeA = tmp.dot(edgeVector);
  83629. if(positionAlongEdgeA > 0 && positionAlongEdgeB < 0){
  83630. // Now check the orthogonal distance from edge to sphere center
  83631. localSpherePos.vsub(edgeVertexA, tmp);
  83632. edgeVectorUnit.copy(edgeVector);
  83633. edgeVectorUnit.normalize();
  83634. positionAlongEdgeA = tmp.dot(edgeVectorUnit);
  83635. edgeVectorUnit.scale(positionAlongEdgeA, tmp);
  83636. tmp.vadd(edgeVertexA, tmp);
  83637. // tmp is now the sphere center position projected to the edge, defined locally in the trimesh frame
  83638. var dist = tmp.distanceTo(localSpherePos);
  83639. if(dist < sphereShape.radius){
  83640. var r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape);
  83641. tmp.vsub(localSpherePos, r.ni);
  83642. r.ni.normalize();
  83643. r.ni.scale(sphereShape.radius, r.ri);
  83644. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, tmp, tmp);
  83645. tmp.vsub(trimeshBody.position, r.rj);
  83646. Transform.vectorToWorldFrame(trimeshQuat, r.ni, r.ni);
  83647. Transform.vectorToWorldFrame(trimeshQuat, r.ri, r.ri);
  83648. this.result.push(r);
  83649. this.createFrictionEquationsFromContact(r, this.frictionResult);
  83650. }
  83651. }
  83652. }
  83653. }
  83654. // Triangle faces
  83655. var va = sphereTrimesh_va;
  83656. var vb = sphereTrimesh_vb;
  83657. var vc = sphereTrimesh_vc;
  83658. var normal = sphereTrimesh_normal;
  83659. for(var i=0, N = triangles.length; i !== N; i++){
  83660. trimeshShape.getTriangleVertices(triangles[i], va, vb, vc);
  83661. trimeshShape.getNormal(triangles[i], normal);
  83662. localSpherePos.vsub(va, tmp);
  83663. var dist = tmp.dot(normal);
  83664. normal.scale(dist, tmp);
  83665. localSpherePos.vsub(tmp, tmp);
  83666. // tmp is now the sphere position projected to the triangle plane
  83667. dist = tmp.distanceTo(localSpherePos);
  83668. if(Ray.pointInTriangle(tmp, va, vb, vc) && dist < sphereShape.radius){
  83669. var r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape);
  83670. tmp.vsub(localSpherePos, r.ni);
  83671. r.ni.normalize();
  83672. r.ni.scale(sphereShape.radius, r.ri);
  83673. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, tmp, tmp);
  83674. tmp.vsub(trimeshBody.position, r.rj);
  83675. Transform.vectorToWorldFrame(trimeshQuat, r.ni, r.ni);
  83676. Transform.vectorToWorldFrame(trimeshQuat, r.ri, r.ri);
  83677. this.result.push(r);
  83678. this.createFrictionEquationsFromContact(r, this.frictionResult);
  83679. }
  83680. }
  83681. triangles.length = 0;
  83682. };
  83683. var point_on_plane_to_sphere = new Vec3();
  83684. var plane_to_sphere_ortho = new Vec3();
  83685. /**
  83686. * @method spherePlane
  83687. * @param {Shape} si
  83688. * @param {Shape} sj
  83689. * @param {Vec3} xi
  83690. * @param {Vec3} xj
  83691. * @param {Quaternion} qi
  83692. * @param {Quaternion} qj
  83693. * @param {Body} bi
  83694. * @param {Body} bj
  83695. */
  83696. Narrowphase.prototype[Shape.types.SPHERE | Shape.types.PLANE] =
  83697. Narrowphase.prototype.spherePlane = function(si,sj,xi,xj,qi,qj,bi,bj){
  83698. // We will have one contact in this case
  83699. var r = this.createContactEquation(bi,bj,si,sj);
  83700. // Contact normal
  83701. r.ni.set(0,0,1);
  83702. qj.vmult(r.ni, r.ni);
  83703. r.ni.negate(r.ni); // body i is the sphere, flip normal
  83704. r.ni.normalize(); // Needed?
  83705. // Vector from sphere center to contact point
  83706. r.ni.mult(si.radius, r.ri);
  83707. // Project down sphere on plane
  83708. xi.vsub(xj, point_on_plane_to_sphere);
  83709. r.ni.mult(r.ni.dot(point_on_plane_to_sphere), plane_to_sphere_ortho);
  83710. point_on_plane_to_sphere.vsub(plane_to_sphere_ortho,r.rj); // The sphere position projected to plane
  83711. if(-point_on_plane_to_sphere.dot(r.ni) <= si.radius){
  83712. // Make it relative to the body
  83713. var ri = r.ri;
  83714. var rj = r.rj;
  83715. ri.vadd(xi, ri);
  83716. ri.vsub(bi.position, ri);
  83717. rj.vadd(xj, rj);
  83718. rj.vsub(bj.position, rj);
  83719. this.result.push(r);
  83720. this.createFrictionEquationsFromContact(r, this.frictionResult);
  83721. }
  83722. };
  83723. // See http://bulletphysics.com/Bullet/BulletFull/SphereTriangleDetector_8cpp_source.html
  83724. var pointInPolygon_edge = new Vec3();
  83725. var pointInPolygon_edge_x_normal = new Vec3();
  83726. var pointInPolygon_vtp = new Vec3();
  83727. function pointInPolygon(verts, normal, p){
  83728. var positiveResult = null;
  83729. var N = verts.length;
  83730. for(var i=0; i!==N; i++){
  83731. var v = verts[i];
  83732. // Get edge to the next vertex
  83733. var edge = pointInPolygon_edge;
  83734. verts[(i+1) % (N)].vsub(v,edge);
  83735. // Get cross product between polygon normal and the edge
  83736. var edge_x_normal = pointInPolygon_edge_x_normal;
  83737. //var edge_x_normal = new Vec3();
  83738. edge.cross(normal,edge_x_normal);
  83739. // Get vector between point and current vertex
  83740. var vertex_to_p = pointInPolygon_vtp;
  83741. p.vsub(v,vertex_to_p);
  83742. // This dot product determines which side of the edge the point is
  83743. var r = edge_x_normal.dot(vertex_to_p);
  83744. // If all such dot products have same sign, we are inside the polygon.
  83745. if(positiveResult===null || (r>0 && positiveResult===true) || (r<=0 && positiveResult===false)){
  83746. if(positiveResult===null){
  83747. positiveResult = r>0;
  83748. }
  83749. continue;
  83750. } else {
  83751. return false; // Encountered some other sign. Exit.
  83752. }
  83753. }
  83754. // If we got here, all dot products were of the same sign.
  83755. return true;
  83756. }
  83757. var box_to_sphere = new Vec3();
  83758. var sphereBox_ns = new Vec3();
  83759. var sphereBox_ns1 = new Vec3();
  83760. var sphereBox_ns2 = new Vec3();
  83761. var sphereBox_sides = [new Vec3(),new Vec3(),new Vec3(),new Vec3(),new Vec3(),new Vec3()];
  83762. var sphereBox_sphere_to_corner = new Vec3();
  83763. var sphereBox_side_ns = new Vec3();
  83764. var sphereBox_side_ns1 = new Vec3();
  83765. var sphereBox_side_ns2 = new Vec3();
  83766. /**
  83767. * @method sphereBox
  83768. * @param {Shape} si
  83769. * @param {Shape} sj
  83770. * @param {Vec3} xi
  83771. * @param {Vec3} xj
  83772. * @param {Quaternion} qi
  83773. * @param {Quaternion} qj
  83774. * @param {Body} bi
  83775. * @param {Body} bj
  83776. */
  83777. Narrowphase.prototype[Shape.types.SPHERE | Shape.types.BOX] =
  83778. Narrowphase.prototype.sphereBox = function(si,sj,xi,xj,qi,qj,bi,bj){
  83779. var v3pool = this.v3pool;
  83780. // we refer to the box as body j
  83781. var sides = sphereBox_sides;
  83782. xi.vsub(xj,box_to_sphere);
  83783. sj.getSideNormals(sides,qj);
  83784. var R = si.radius;
  83785. var penetrating_sides = [];
  83786. // Check side (plane) intersections
  83787. var found = false;
  83788. // Store the resulting side penetration info
  83789. var side_ns = sphereBox_side_ns;
  83790. var side_ns1 = sphereBox_side_ns1;
  83791. var side_ns2 = sphereBox_side_ns2;
  83792. var side_h = null;
  83793. var side_penetrations = 0;
  83794. var side_dot1 = 0;
  83795. var side_dot2 = 0;
  83796. var side_distance = null;
  83797. for(var idx=0,nsides=sides.length; idx!==nsides && found===false; idx++){
  83798. // Get the plane side normal (ns)
  83799. var ns = sphereBox_ns;
  83800. ns.copy(sides[idx]);
  83801. var h = ns.norm();
  83802. ns.normalize();
  83803. // The normal/distance dot product tells which side of the plane we are
  83804. var dot = box_to_sphere.dot(ns);
  83805. if(dot<h+R && dot>0){
  83806. // Intersects plane. Now check the other two dimensions
  83807. var ns1 = sphereBox_ns1;
  83808. var ns2 = sphereBox_ns2;
  83809. ns1.copy(sides[(idx+1)%3]);
  83810. ns2.copy(sides[(idx+2)%3]);
  83811. var h1 = ns1.norm();
  83812. var h2 = ns2.norm();
  83813. ns1.normalize();
  83814. ns2.normalize();
  83815. var dot1 = box_to_sphere.dot(ns1);
  83816. var dot2 = box_to_sphere.dot(ns2);
  83817. if(dot1<h1 && dot1>-h1 && dot2<h2 && dot2>-h2){
  83818. var dist = Math.abs(dot-h-R);
  83819. if(side_distance===null || dist < side_distance){
  83820. side_distance = dist;
  83821. side_dot1 = dot1;
  83822. side_dot2 = dot2;
  83823. side_h = h;
  83824. side_ns.copy(ns);
  83825. side_ns1.copy(ns1);
  83826. side_ns2.copy(ns2);
  83827. side_penetrations++;
  83828. }
  83829. }
  83830. }
  83831. }
  83832. if(side_penetrations){
  83833. found = true;
  83834. var r = this.createContactEquation(bi,bj,si,sj);
  83835. side_ns.mult(-R,r.ri); // Sphere r
  83836. r.ni.copy(side_ns);
  83837. r.ni.negate(r.ni); // Normal should be out of sphere
  83838. side_ns.mult(side_h,side_ns);
  83839. side_ns1.mult(side_dot1,side_ns1);
  83840. side_ns.vadd(side_ns1,side_ns);
  83841. side_ns2.mult(side_dot2,side_ns2);
  83842. side_ns.vadd(side_ns2,r.rj);
  83843. // Make relative to bodies
  83844. r.ri.vadd(xi, r.ri);
  83845. r.ri.vsub(bi.position, r.ri);
  83846. r.rj.vadd(xj, r.rj);
  83847. r.rj.vsub(bj.position, r.rj);
  83848. this.result.push(r);
  83849. this.createFrictionEquationsFromContact(r, this.frictionResult);
  83850. }
  83851. // Check corners
  83852. var rj = v3pool.get();
  83853. var sphere_to_corner = sphereBox_sphere_to_corner;
  83854. for(var j=0; j!==2 && !found; j++){
  83855. for(var k=0; k!==2 && !found; k++){
  83856. for(var l=0; l!==2 && !found; l++){
  83857. rj.set(0,0,0);
  83858. if(j){
  83859. rj.vadd(sides[0],rj);
  83860. } else {
  83861. rj.vsub(sides[0],rj);
  83862. }
  83863. if(k){
  83864. rj.vadd(sides[1],rj);
  83865. } else {
  83866. rj.vsub(sides[1],rj);
  83867. }
  83868. if(l){
  83869. rj.vadd(sides[2],rj);
  83870. } else {
  83871. rj.vsub(sides[2],rj);
  83872. }
  83873. // World position of corner
  83874. xj.vadd(rj,sphere_to_corner);
  83875. sphere_to_corner.vsub(xi,sphere_to_corner);
  83876. if(sphere_to_corner.norm2() < R*R){
  83877. found = true;
  83878. var r = this.createContactEquation(bi,bj,si,sj);
  83879. r.ri.copy(sphere_to_corner);
  83880. r.ri.normalize();
  83881. r.ni.copy(r.ri);
  83882. r.ri.mult(R,r.ri);
  83883. r.rj.copy(rj);
  83884. // Make relative to bodies
  83885. r.ri.vadd(xi, r.ri);
  83886. r.ri.vsub(bi.position, r.ri);
  83887. r.rj.vadd(xj, r.rj);
  83888. r.rj.vsub(bj.position, r.rj);
  83889. this.result.push(r);
  83890. this.createFrictionEquationsFromContact(r, this.frictionResult);
  83891. }
  83892. }
  83893. }
  83894. }
  83895. v3pool.release(rj);
  83896. rj = null;
  83897. // Check edges
  83898. var edgeTangent = v3pool.get();
  83899. var edgeCenter = v3pool.get();
  83900. var r = v3pool.get(); // r = edge center to sphere center
  83901. var orthogonal = v3pool.get();
  83902. var dist = v3pool.get();
  83903. var Nsides = sides.length;
  83904. for(var j=0; j!==Nsides && !found; j++){
  83905. for(var k=0; k!==Nsides && !found; k++){
  83906. if(j%3 !== k%3){
  83907. // Get edge tangent
  83908. sides[k].cross(sides[j],edgeTangent);
  83909. edgeTangent.normalize();
  83910. sides[j].vadd(sides[k], edgeCenter);
  83911. r.copy(xi);
  83912. r.vsub(edgeCenter,r);
  83913. r.vsub(xj,r);
  83914. var orthonorm = r.dot(edgeTangent); // distance from edge center to sphere center in the tangent direction
  83915. edgeTangent.mult(orthonorm,orthogonal); // Vector from edge center to sphere center in the tangent direction
  83916. // Find the third side orthogonal to this one
  83917. var l = 0;
  83918. while(l===j%3 || l===k%3){
  83919. l++;
  83920. }
  83921. // vec from edge center to sphere projected to the plane orthogonal to the edge tangent
  83922. dist.copy(xi);
  83923. dist.vsub(orthogonal,dist);
  83924. dist.vsub(edgeCenter,dist);
  83925. dist.vsub(xj,dist);
  83926. // Distances in tangent direction and distance in the plane orthogonal to it
  83927. var tdist = Math.abs(orthonorm);
  83928. var ndist = dist.norm();
  83929. if(tdist < sides[l].norm() && ndist<R){
  83930. found = true;
  83931. var res = this.createContactEquation(bi,bj,si,sj);
  83932. edgeCenter.vadd(orthogonal,res.rj); // box rj
  83933. res.rj.copy(res.rj);
  83934. dist.negate(res.ni);
  83935. res.ni.normalize();
  83936. res.ri.copy(res.rj);
  83937. res.ri.vadd(xj,res.ri);
  83938. res.ri.vsub(xi,res.ri);
  83939. res.ri.normalize();
  83940. res.ri.mult(R,res.ri);
  83941. // Make relative to bodies
  83942. res.ri.vadd(xi, res.ri);
  83943. res.ri.vsub(bi.position, res.ri);
  83944. res.rj.vadd(xj, res.rj);
  83945. res.rj.vsub(bj.position, res.rj);
  83946. this.result.push(res);
  83947. this.createFrictionEquationsFromContact(res, this.frictionResult);
  83948. }
  83949. }
  83950. }
  83951. }
  83952. v3pool.release(edgeTangent,edgeCenter,r,orthogonal,dist);
  83953. };
  83954. var convex_to_sphere = new Vec3();
  83955. var sphereConvex_edge = new Vec3();
  83956. var sphereConvex_edgeUnit = new Vec3();
  83957. var sphereConvex_sphereToCorner = new Vec3();
  83958. var sphereConvex_worldCorner = new Vec3();
  83959. var sphereConvex_worldNormal = new Vec3();
  83960. var sphereConvex_worldPoint = new Vec3();
  83961. var sphereConvex_worldSpherePointClosestToPlane = new Vec3();
  83962. var sphereConvex_penetrationVec = new Vec3();
  83963. var sphereConvex_sphereToWorldPoint = new Vec3();
  83964. /**
  83965. * @method sphereConvex
  83966. * @param {Shape} si
  83967. * @param {Shape} sj
  83968. * @param {Vec3} xi
  83969. * @param {Vec3} xj
  83970. * @param {Quaternion} qi
  83971. * @param {Quaternion} qj
  83972. * @param {Body} bi
  83973. * @param {Body} bj
  83974. */
  83975. Narrowphase.prototype[Shape.types.SPHERE | Shape.types.CONVEXPOLYHEDRON] =
  83976. Narrowphase.prototype.sphereConvex = function(si,sj,xi,xj,qi,qj,bi,bj){
  83977. var v3pool = this.v3pool;
  83978. xi.vsub(xj,convex_to_sphere);
  83979. var normals = sj.faceNormals;
  83980. var faces = sj.faces;
  83981. var verts = sj.vertices;
  83982. var R = si.radius;
  83983. var penetrating_sides = [];
  83984. // if(convex_to_sphere.norm2() > si.boundingSphereRadius + sj.boundingSphereRadius){
  83985. // return;
  83986. // }
  83987. // Check corners
  83988. for(var i=0; i!==verts.length; i++){
  83989. var v = verts[i];
  83990. // World position of corner
  83991. var worldCorner = sphereConvex_worldCorner;
  83992. qj.vmult(v,worldCorner);
  83993. xj.vadd(worldCorner,worldCorner);
  83994. var sphere_to_corner = sphereConvex_sphereToCorner;
  83995. worldCorner.vsub(xi, sphere_to_corner);
  83996. if(sphere_to_corner.norm2() < R * R){
  83997. found = true;
  83998. var r = this.createContactEquation(bi,bj,si,sj);
  83999. r.ri.copy(sphere_to_corner);
  84000. r.ri.normalize();
  84001. r.ni.copy(r.ri);
  84002. r.ri.mult(R,r.ri);
  84003. worldCorner.vsub(xj,r.rj);
  84004. // Should be relative to the body.
  84005. r.ri.vadd(xi, r.ri);
  84006. r.ri.vsub(bi.position, r.ri);
  84007. // Should be relative to the body.
  84008. r.rj.vadd(xj, r.rj);
  84009. r.rj.vsub(bj.position, r.rj);
  84010. this.result.push(r);
  84011. this.createFrictionEquationsFromContact(r, this.frictionResult);
  84012. return;
  84013. }
  84014. }
  84015. // Check side (plane) intersections
  84016. var found = false;
  84017. for(var i=0, nfaces=faces.length; i!==nfaces && found===false; i++){
  84018. var normal = normals[i];
  84019. var face = faces[i];
  84020. // Get world-transformed normal of the face
  84021. var worldNormal = sphereConvex_worldNormal;
  84022. qj.vmult(normal,worldNormal);
  84023. // Get a world vertex from the face
  84024. var worldPoint = sphereConvex_worldPoint;
  84025. qj.vmult(verts[face[0]],worldPoint);
  84026. worldPoint.vadd(xj,worldPoint);
  84027. // Get a point on the sphere, closest to the face normal
  84028. var worldSpherePointClosestToPlane = sphereConvex_worldSpherePointClosestToPlane;
  84029. worldNormal.mult(-R, worldSpherePointClosestToPlane);
  84030. xi.vadd(worldSpherePointClosestToPlane, worldSpherePointClosestToPlane);
  84031. // Vector from a face point to the closest point on the sphere
  84032. var penetrationVec = sphereConvex_penetrationVec;
  84033. worldSpherePointClosestToPlane.vsub(worldPoint,penetrationVec);
  84034. // The penetration. Negative value means overlap.
  84035. var penetration = penetrationVec.dot(worldNormal);
  84036. var worldPointToSphere = sphereConvex_sphereToWorldPoint;
  84037. xi.vsub(worldPoint, worldPointToSphere);
  84038. if(penetration < 0 && worldPointToSphere.dot(worldNormal)>0){
  84039. // Intersects plane. Now check if the sphere is inside the face polygon
  84040. var faceVerts = []; // Face vertices, in world coords
  84041. for(var j=0, Nverts=face.length; j!==Nverts; j++){
  84042. var worldVertex = v3pool.get();
  84043. qj.vmult(verts[face[j]], worldVertex);
  84044. xj.vadd(worldVertex,worldVertex);
  84045. faceVerts.push(worldVertex);
  84046. }
  84047. if(pointInPolygon(faceVerts,worldNormal,xi)){ // Is the sphere center in the face polygon?
  84048. found = true;
  84049. var r = this.createContactEquation(bi,bj,si,sj);
  84050. worldNormal.mult(-R, r.ri); // Contact offset, from sphere center to contact
  84051. worldNormal.negate(r.ni); // Normal pointing out of sphere
  84052. var penetrationVec2 = v3pool.get();
  84053. worldNormal.mult(-penetration, penetrationVec2);
  84054. var penetrationSpherePoint = v3pool.get();
  84055. worldNormal.mult(-R, penetrationSpherePoint);
  84056. //xi.vsub(xj).vadd(penetrationSpherePoint).vadd(penetrationVec2 , r.rj);
  84057. xi.vsub(xj,r.rj);
  84058. r.rj.vadd(penetrationSpherePoint,r.rj);
  84059. r.rj.vadd(penetrationVec2 , r.rj);
  84060. // Should be relative to the body.
  84061. r.rj.vadd(xj, r.rj);
  84062. r.rj.vsub(bj.position, r.rj);
  84063. // Should be relative to the body.
  84064. r.ri.vadd(xi, r.ri);
  84065. r.ri.vsub(bi.position, r.ri);
  84066. v3pool.release(penetrationVec2);
  84067. v3pool.release(penetrationSpherePoint);
  84068. this.result.push(r);
  84069. this.createFrictionEquationsFromContact(r, this.frictionResult);
  84070. // Release world vertices
  84071. for(var j=0, Nfaceverts=faceVerts.length; j!==Nfaceverts; j++){
  84072. v3pool.release(faceVerts[j]);
  84073. }
  84074. return; // We only expect *one* face contact
  84075. } else {
  84076. // Edge?
  84077. for(var j=0; j!==face.length; j++){
  84078. // Get two world transformed vertices
  84079. var v1 = v3pool.get();
  84080. var v2 = v3pool.get();
  84081. qj.vmult(verts[face[(j+1)%face.length]], v1);
  84082. qj.vmult(verts[face[(j+2)%face.length]], v2);
  84083. xj.vadd(v1, v1);
  84084. xj.vadd(v2, v2);
  84085. // Construct edge vector
  84086. var edge = sphereConvex_edge;
  84087. v2.vsub(v1,edge);
  84088. // Construct the same vector, but normalized
  84089. var edgeUnit = sphereConvex_edgeUnit;
  84090. edge.unit(edgeUnit);
  84091. // p is xi projected onto the edge
  84092. var p = v3pool.get();
  84093. var v1_to_xi = v3pool.get();
  84094. xi.vsub(v1, v1_to_xi);
  84095. var dot = v1_to_xi.dot(edgeUnit);
  84096. edgeUnit.mult(dot, p);
  84097. p.vadd(v1, p);
  84098. // Compute a vector from p to the center of the sphere
  84099. var xi_to_p = v3pool.get();
  84100. p.vsub(xi, xi_to_p);
  84101. // Collision if the edge-sphere distance is less than the radius
  84102. // AND if p is in between v1 and v2
  84103. if(dot > 0 && dot*dot<edge.norm2() && xi_to_p.norm2() < R*R){ // Collision if the edge-sphere distance is less than the radius
  84104. // Edge contact!
  84105. var r = this.createContactEquation(bi,bj,si,sj);
  84106. p.vsub(xj,r.rj);
  84107. p.vsub(xi,r.ni);
  84108. r.ni.normalize();
  84109. r.ni.mult(R,r.ri);
  84110. // Should be relative to the body.
  84111. r.rj.vadd(xj, r.rj);
  84112. r.rj.vsub(bj.position, r.rj);
  84113. // Should be relative to the body.
  84114. r.ri.vadd(xi, r.ri);
  84115. r.ri.vsub(bi.position, r.ri);
  84116. this.result.push(r);
  84117. this.createFrictionEquationsFromContact(r, this.frictionResult);
  84118. // Release world vertices
  84119. for(var j=0, Nfaceverts=faceVerts.length; j!==Nfaceverts; j++){
  84120. v3pool.release(faceVerts[j]);
  84121. }
  84122. v3pool.release(v1);
  84123. v3pool.release(v2);
  84124. v3pool.release(p);
  84125. v3pool.release(xi_to_p);
  84126. v3pool.release(v1_to_xi);
  84127. return;
  84128. }
  84129. v3pool.release(v1);
  84130. v3pool.release(v2);
  84131. v3pool.release(p);
  84132. v3pool.release(xi_to_p);
  84133. v3pool.release(v1_to_xi);
  84134. }
  84135. }
  84136. // Release world vertices
  84137. for(var j=0, Nfaceverts=faceVerts.length; j!==Nfaceverts; j++){
  84138. v3pool.release(faceVerts[j]);
  84139. }
  84140. }
  84141. }
  84142. };
  84143. var planeBox_normal = new Vec3();
  84144. var plane_to_corner = new Vec3();
  84145. /**
  84146. * @method planeBox
  84147. * @param {Array} result
  84148. * @param {Shape} si
  84149. * @param {Shape} sj
  84150. * @param {Vec3} xi
  84151. * @param {Vec3} xj
  84152. * @param {Quaternion} qi
  84153. * @param {Quaternion} qj
  84154. * @param {Body} bi
  84155. * @param {Body} bj
  84156. */
  84157. Narrowphase.prototype[Shape.types.PLANE | Shape.types.BOX] =
  84158. Narrowphase.prototype.planeBox = function(si,sj,xi,xj,qi,qj,bi,bj){
  84159. sj.convexPolyhedronRepresentation.material = sj.material;
  84160. sj.convexPolyhedronRepresentation.collisionResponse = sj.collisionResponse;
  84161. this.planeConvex(si,sj.convexPolyhedronRepresentation,xi,xj,qi,qj,bi,bj);
  84162. };
  84163. var planeConvex_v = new Vec3();
  84164. var planeConvex_normal = new Vec3();
  84165. var planeConvex_relpos = new Vec3();
  84166. var planeConvex_projected = new Vec3();
  84167. /**
  84168. * @method planeConvex
  84169. * @param {Shape} si
  84170. * @param {Shape} sj
  84171. * @param {Vec3} xi
  84172. * @param {Vec3} xj
  84173. * @param {Quaternion} qi
  84174. * @param {Quaternion} qj
  84175. * @param {Body} bi
  84176. * @param {Body} bj
  84177. */
  84178. Narrowphase.prototype[Shape.types.PLANE | Shape.types.CONVEXPOLYHEDRON] =
  84179. Narrowphase.prototype.planeConvex = function(
  84180. planeShape,
  84181. convexShape,
  84182. planePosition,
  84183. convexPosition,
  84184. planeQuat,
  84185. convexQuat,
  84186. planeBody,
  84187. convexBody
  84188. ){
  84189. // Simply return the points behind the plane.
  84190. var worldVertex = planeConvex_v,
  84191. worldNormal = planeConvex_normal;
  84192. worldNormal.set(0,0,1);
  84193. planeQuat.vmult(worldNormal,worldNormal); // Turn normal according to plane orientation
  84194. var numContacts = 0;
  84195. var relpos = planeConvex_relpos;
  84196. for(var i = 0; i !== convexShape.vertices.length; i++){
  84197. // Get world convex vertex
  84198. worldVertex.copy(convexShape.vertices[i]);
  84199. convexQuat.vmult(worldVertex, worldVertex);
  84200. convexPosition.vadd(worldVertex, worldVertex);
  84201. worldVertex.vsub(planePosition, relpos);
  84202. var dot = worldNormal.dot(relpos);
  84203. if(dot <= 0.0){
  84204. var r = this.createContactEquation(planeBody, convexBody, planeShape, convexShape);
  84205. // Get vertex position projected on plane
  84206. var projected = planeConvex_projected;
  84207. worldNormal.mult(worldNormal.dot(relpos),projected);
  84208. worldVertex.vsub(projected, projected);
  84209. projected.vsub(planePosition, r.ri); // From plane to vertex projected on plane
  84210. r.ni.copy(worldNormal); // Contact normal is the plane normal out from plane
  84211. // rj is now just the vector from the convex center to the vertex
  84212. worldVertex.vsub(convexPosition, r.rj);
  84213. // Make it relative to the body
  84214. r.ri.vadd(planePosition, r.ri);
  84215. r.ri.vsub(planeBody.position, r.ri);
  84216. r.rj.vadd(convexPosition, r.rj);
  84217. r.rj.vsub(convexBody.position, r.rj);
  84218. this.result.push(r);
  84219. numContacts++;
  84220. if(!this.enableFrictionReduction){
  84221. this.createFrictionEquationsFromContact(r, this.frictionResult);
  84222. }
  84223. }
  84224. }
  84225. if(this.enableFrictionReduction && numContacts){
  84226. this.createFrictionFromAverage(numContacts);
  84227. }
  84228. };
  84229. var convexConvex_sepAxis = new Vec3();
  84230. var convexConvex_q = new Vec3();
  84231. /**
  84232. * @method convexConvex
  84233. * @param {Shape} si
  84234. * @param {Shape} sj
  84235. * @param {Vec3} xi
  84236. * @param {Vec3} xj
  84237. * @param {Quaternion} qi
  84238. * @param {Quaternion} qj
  84239. * @param {Body} bi
  84240. * @param {Body} bj
  84241. */
  84242. Narrowphase.prototype[Shape.types.CONVEXPOLYHEDRON] =
  84243. Narrowphase.prototype.convexConvex = function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,faceListA,faceListB){
  84244. var sepAxis = convexConvex_sepAxis;
  84245. if(xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius){
  84246. return;
  84247. }
  84248. if(si.findSeparatingAxis(sj,xi,qi,xj,qj,sepAxis,faceListA,faceListB)){
  84249. var res = [];
  84250. var q = convexConvex_q;
  84251. si.clipAgainstHull(xi,qi,sj,xj,qj,sepAxis,-100,100,res);
  84252. var numContacts = 0;
  84253. for(var j = 0; j !== res.length; j++){
  84254. var r = this.createContactEquation(bi,bj,si,sj,rsi,rsj),
  84255. ri = r.ri,
  84256. rj = r.rj;
  84257. sepAxis.negate(r.ni);
  84258. res[j].normal.negate(q);
  84259. q.mult(res[j].depth, q);
  84260. res[j].point.vadd(q, ri);
  84261. rj.copy(res[j].point);
  84262. // Contact points are in world coordinates. Transform back to relative
  84263. ri.vsub(xi,ri);
  84264. rj.vsub(xj,rj);
  84265. // Make relative to bodies
  84266. ri.vadd(xi, ri);
  84267. ri.vsub(bi.position, ri);
  84268. rj.vadd(xj, rj);
  84269. rj.vsub(bj.position, rj);
  84270. this.result.push(r);
  84271. numContacts++;
  84272. if(!this.enableFrictionReduction){
  84273. this.createFrictionEquationsFromContact(r, this.frictionResult);
  84274. }
  84275. }
  84276. if(this.enableFrictionReduction && numContacts){
  84277. this.createFrictionFromAverage(numContacts);
  84278. }
  84279. }
  84280. };
  84281. /**
  84282. * @method convexTrimesh
  84283. * @param {Array} result
  84284. * @param {Shape} si
  84285. * @param {Shape} sj
  84286. * @param {Vec3} xi
  84287. * @param {Vec3} xj
  84288. * @param {Quaternion} qi
  84289. * @param {Quaternion} qj
  84290. * @param {Body} bi
  84291. * @param {Body} bj
  84292. */
  84293. // Narrowphase.prototype[Shape.types.CONVEXPOLYHEDRON | Shape.types.TRIMESH] =
  84294. // Narrowphase.prototype.convexTrimesh = function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,faceListA,faceListB){
  84295. // var sepAxis = convexConvex_sepAxis;
  84296. // if(xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius){
  84297. // return;
  84298. // }
  84299. // // Construct a temp hull for each triangle
  84300. // var hullB = new ConvexPolyhedron();
  84301. // hullB.faces = [[0,1,2]];
  84302. // var va = new Vec3();
  84303. // var vb = new Vec3();
  84304. // var vc = new Vec3();
  84305. // hullB.vertices = [
  84306. // va,
  84307. // vb,
  84308. // vc
  84309. // ];
  84310. // for (var i = 0; i < sj.indices.length / 3; i++) {
  84311. // var triangleNormal = new Vec3();
  84312. // sj.getNormal(i, triangleNormal);
  84313. // hullB.faceNormals = [triangleNormal];
  84314. // sj.getTriangleVertices(i, va, vb, vc);
  84315. // var d = si.testSepAxis(triangleNormal, hullB, xi, qi, xj, qj);
  84316. // if(!d){
  84317. // triangleNormal.scale(-1, triangleNormal);
  84318. // d = si.testSepAxis(triangleNormal, hullB, xi, qi, xj, qj);
  84319. // if(!d){
  84320. // continue;
  84321. // }
  84322. // }
  84323. // var res = [];
  84324. // var q = convexConvex_q;
  84325. // si.clipAgainstHull(xi,qi,hullB,xj,qj,triangleNormal,-100,100,res);
  84326. // for(var j = 0; j !== res.length; j++){
  84327. // var r = this.createContactEquation(bi,bj,si,sj,rsi,rsj),
  84328. // ri = r.ri,
  84329. // rj = r.rj;
  84330. // r.ni.copy(triangleNormal);
  84331. // r.ni.negate(r.ni);
  84332. // res[j].normal.negate(q);
  84333. // q.mult(res[j].depth, q);
  84334. // res[j].point.vadd(q, ri);
  84335. // rj.copy(res[j].point);
  84336. // // Contact points are in world coordinates. Transform back to relative
  84337. // ri.vsub(xi,ri);
  84338. // rj.vsub(xj,rj);
  84339. // // Make relative to bodies
  84340. // ri.vadd(xi, ri);
  84341. // ri.vsub(bi.position, ri);
  84342. // rj.vadd(xj, rj);
  84343. // rj.vsub(bj.position, rj);
  84344. // result.push(r);
  84345. // }
  84346. // }
  84347. // };
  84348. var particlePlane_normal = new Vec3();
  84349. var particlePlane_relpos = new Vec3();
  84350. var particlePlane_projected = new Vec3();
  84351. /**
  84352. * @method particlePlane
  84353. * @param {Array} result
  84354. * @param {Shape} si
  84355. * @param {Shape} sj
  84356. * @param {Vec3} xi
  84357. * @param {Vec3} xj
  84358. * @param {Quaternion} qi
  84359. * @param {Quaternion} qj
  84360. * @param {Body} bi
  84361. * @param {Body} bj
  84362. */
  84363. Narrowphase.prototype[Shape.types.PLANE | Shape.types.PARTICLE] =
  84364. Narrowphase.prototype.planeParticle = function(sj,si,xj,xi,qj,qi,bj,bi){
  84365. var normal = particlePlane_normal;
  84366. normal.set(0,0,1);
  84367. bj.quaternion.vmult(normal,normal); // Turn normal according to plane orientation
  84368. var relpos = particlePlane_relpos;
  84369. xi.vsub(bj.position,relpos);
  84370. var dot = normal.dot(relpos);
  84371. if(dot <= 0.0){
  84372. var r = this.createContactEquation(bi,bj,si,sj);
  84373. r.ni.copy(normal); // Contact normal is the plane normal
  84374. r.ni.negate(r.ni);
  84375. r.ri.set(0,0,0); // Center of particle
  84376. // Get particle position projected on plane
  84377. var projected = particlePlane_projected;
  84378. normal.mult(normal.dot(xi),projected);
  84379. xi.vsub(projected,projected);
  84380. //projected.vadd(bj.position,projected);
  84381. // rj is now the projected world position minus plane position
  84382. r.rj.copy(projected);
  84383. this.result.push(r);
  84384. this.createFrictionEquationsFromContact(r, this.frictionResult);
  84385. }
  84386. };
  84387. var particleSphere_normal = new Vec3();
  84388. /**
  84389. * @method particleSphere
  84390. * @param {Array} result
  84391. * @param {Shape} si
  84392. * @param {Shape} sj
  84393. * @param {Vec3} xi
  84394. * @param {Vec3} xj
  84395. * @param {Quaternion} qi
  84396. * @param {Quaternion} qj
  84397. * @param {Body} bi
  84398. * @param {Body} bj
  84399. */
  84400. Narrowphase.prototype[Shape.types.PARTICLE | Shape.types.SPHERE] =
  84401. Narrowphase.prototype.sphereParticle = function(sj,si,xj,xi,qj,qi,bj,bi){
  84402. // The normal is the unit vector from sphere center to particle center
  84403. var normal = particleSphere_normal;
  84404. normal.set(0,0,1);
  84405. xi.vsub(xj,normal);
  84406. var lengthSquared = normal.norm2();
  84407. if(lengthSquared <= sj.radius * sj.radius){
  84408. var r = this.createContactEquation(bi,bj,si,sj);
  84409. normal.normalize();
  84410. r.rj.copy(normal);
  84411. r.rj.mult(sj.radius,r.rj);
  84412. r.ni.copy(normal); // Contact normal
  84413. r.ni.negate(r.ni);
  84414. r.ri.set(0,0,0); // Center of particle
  84415. this.result.push(r);
  84416. this.createFrictionEquationsFromContact(r, this.frictionResult);
  84417. }
  84418. };
  84419. // WIP
  84420. var cqj = new Quaternion();
  84421. var convexParticle_local = new Vec3();
  84422. var convexParticle_normal = new Vec3();
  84423. var convexParticle_penetratedFaceNormal = new Vec3();
  84424. var convexParticle_vertexToParticle = new Vec3();
  84425. var convexParticle_worldPenetrationVec = new Vec3();
  84426. /**
  84427. * @method convexParticle
  84428. * @param {Array} result
  84429. * @param {Shape} si
  84430. * @param {Shape} sj
  84431. * @param {Vec3} xi
  84432. * @param {Vec3} xj
  84433. * @param {Quaternion} qi
  84434. * @param {Quaternion} qj
  84435. * @param {Body} bi
  84436. * @param {Body} bj
  84437. */
  84438. Narrowphase.prototype[Shape.types.PARTICLE | Shape.types.CONVEXPOLYHEDRON] =
  84439. Narrowphase.prototype.convexParticle = function(sj,si,xj,xi,qj,qi,bj,bi){
  84440. var penetratedFaceIndex = -1;
  84441. var penetratedFaceNormal = convexParticle_penetratedFaceNormal;
  84442. var worldPenetrationVec = convexParticle_worldPenetrationVec;
  84443. var minPenetration = null;
  84444. var numDetectedFaces = 0;
  84445. // Convert particle position xi to local coords in the convex
  84446. var local = convexParticle_local;
  84447. local.copy(xi);
  84448. local.vsub(xj,local); // Convert position to relative the convex origin
  84449. qj.conjugate(cqj);
  84450. cqj.vmult(local,local);
  84451. if(sj.pointIsInside(local)){
  84452. if(sj.worldVerticesNeedsUpdate){
  84453. sj.computeWorldVertices(xj,qj);
  84454. }
  84455. if(sj.worldFaceNormalsNeedsUpdate){
  84456. sj.computeWorldFaceNormals(qj);
  84457. }
  84458. // For each world polygon in the polyhedra
  84459. for(var i=0,nfaces=sj.faces.length; i!==nfaces; i++){
  84460. // Construct world face vertices
  84461. var verts = [ sj.worldVertices[ sj.faces[i][0] ] ];
  84462. var normal = sj.worldFaceNormals[i];
  84463. // Check how much the particle penetrates the polygon plane.
  84464. xi.vsub(verts[0],convexParticle_vertexToParticle);
  84465. var penetration = -normal.dot(convexParticle_vertexToParticle);
  84466. if(minPenetration===null || Math.abs(penetration)<Math.abs(minPenetration)){
  84467. minPenetration = penetration;
  84468. penetratedFaceIndex = i;
  84469. penetratedFaceNormal.copy(normal);
  84470. numDetectedFaces++;
  84471. }
  84472. }
  84473. if(penetratedFaceIndex!==-1){
  84474. // Setup contact
  84475. var r = this.createContactEquation(bi,bj,si,sj);
  84476. penetratedFaceNormal.mult(minPenetration, worldPenetrationVec);
  84477. // rj is the particle position projected to the face
  84478. worldPenetrationVec.vadd(xi,worldPenetrationVec);
  84479. worldPenetrationVec.vsub(xj,worldPenetrationVec);
  84480. r.rj.copy(worldPenetrationVec);
  84481. //var projectedToFace = xi.vsub(xj).vadd(worldPenetrationVec);
  84482. //projectedToFace.copy(r.rj);
  84483. //qj.vmult(r.rj,r.rj);
  84484. penetratedFaceNormal.negate( r.ni ); // Contact normal
  84485. r.ri.set(0,0,0); // Center of particle
  84486. var ri = r.ri,
  84487. rj = r.rj;
  84488. // Make relative to bodies
  84489. ri.vadd(xi, ri);
  84490. ri.vsub(bi.position, ri);
  84491. rj.vadd(xj, rj);
  84492. rj.vsub(bj.position, rj);
  84493. this.result.push(r);
  84494. this.createFrictionEquationsFromContact(r, this.frictionResult);
  84495. } else {
  84496. console.warn("Point found inside convex, but did not find penetrating face!");
  84497. }
  84498. }
  84499. };
  84500. Narrowphase.prototype[Shape.types.BOX | Shape.types.HEIGHTFIELD] =
  84501. Narrowphase.prototype.boxHeightfield = function (si,sj,xi,xj,qi,qj,bi,bj){
  84502. si.convexPolyhedronRepresentation.material = si.material;
  84503. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  84504. this.convexHeightfield(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj);
  84505. };
  84506. var convexHeightfield_tmp1 = new Vec3();
  84507. var convexHeightfield_tmp2 = new Vec3();
  84508. var convexHeightfield_faceList = [0];
  84509. /**
  84510. * @method convexHeightfield
  84511. */
  84512. Narrowphase.prototype[Shape.types.CONVEXPOLYHEDRON | Shape.types.HEIGHTFIELD] =
  84513. Narrowphase.prototype.convexHeightfield = function (
  84514. convexShape,
  84515. hfShape,
  84516. convexPos,
  84517. hfPos,
  84518. convexQuat,
  84519. hfQuat,
  84520. convexBody,
  84521. hfBody
  84522. ){
  84523. var data = hfShape.data,
  84524. w = hfShape.elementSize,
  84525. radius = convexShape.boundingSphereRadius,
  84526. worldPillarOffset = convexHeightfield_tmp2,
  84527. faceList = convexHeightfield_faceList;
  84528. // Get sphere position to heightfield local!
  84529. var localConvexPos = convexHeightfield_tmp1;
  84530. Transform.pointToLocalFrame(hfPos, hfQuat, convexPos, localConvexPos);
  84531. // Get the index of the data points to test against
  84532. var iMinX = Math.floor((localConvexPos.x - radius) / w) - 1,
  84533. iMaxX = Math.ceil((localConvexPos.x + radius) / w) + 1,
  84534. iMinY = Math.floor((localConvexPos.y - radius) / w) - 1,
  84535. iMaxY = Math.ceil((localConvexPos.y + radius) / w) + 1;
  84536. // Bail out if we are out of the terrain
  84537. if(iMaxX < 0 || iMaxY < 0 || iMinX > data.length || iMinY > data[0].length){
  84538. return;
  84539. }
  84540. // Clamp index to edges
  84541. if(iMinX < 0){ iMinX = 0; }
  84542. if(iMaxX < 0){ iMaxX = 0; }
  84543. if(iMinY < 0){ iMinY = 0; }
  84544. if(iMaxY < 0){ iMaxY = 0; }
  84545. if(iMinX >= data.length){ iMinX = data.length - 1; }
  84546. if(iMaxX >= data.length){ iMaxX = data.length - 1; }
  84547. if(iMaxY >= data[0].length){ iMaxY = data[0].length - 1; }
  84548. if(iMinY >= data[0].length){ iMinY = data[0].length - 1; }
  84549. var minMax = [];
  84550. hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);
  84551. var min = minMax[0];
  84552. var max = minMax[1];
  84553. // Bail out if we're cant touch the bounding height box
  84554. if(localConvexPos.z - radius > max || localConvexPos.z + radius < min){
  84555. return;
  84556. }
  84557. for(var i = iMinX; i < iMaxX; i++){
  84558. for(var j = iMinY; j < iMaxY; j++){
  84559. // Lower triangle
  84560. hfShape.getConvexTrianglePillar(i, j, false);
  84561. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  84562. if (convexPos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + convexShape.boundingSphereRadius) {
  84563. this.convexConvex(convexShape, hfShape.pillarConvex, convexPos, worldPillarOffset, convexQuat, hfQuat, convexBody, hfBody, null, null, faceList, null);
  84564. }
  84565. // Upper triangle
  84566. hfShape.getConvexTrianglePillar(i, j, true);
  84567. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  84568. if (convexPos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + convexShape.boundingSphereRadius) {
  84569. this.convexConvex(convexShape, hfShape.pillarConvex, convexPos, worldPillarOffset, convexQuat, hfQuat, convexBody, hfBody, null, null, faceList, null);
  84570. }
  84571. }
  84572. }
  84573. };
  84574. var sphereHeightfield_tmp1 = new Vec3();
  84575. var sphereHeightfield_tmp2 = new Vec3();
  84576. /**
  84577. * @method sphereHeightfield
  84578. */
  84579. Narrowphase.prototype[Shape.types.SPHERE | Shape.types.HEIGHTFIELD] =
  84580. Narrowphase.prototype.sphereHeightfield = function (
  84581. sphereShape,
  84582. hfShape,
  84583. spherePos,
  84584. hfPos,
  84585. sphereQuat,
  84586. hfQuat,
  84587. sphereBody,
  84588. hfBody
  84589. ){
  84590. var data = hfShape.data,
  84591. radius = sphereShape.radius,
  84592. w = hfShape.elementSize,
  84593. worldPillarOffset = sphereHeightfield_tmp2;
  84594. // Get sphere position to heightfield local!
  84595. var localSpherePos = sphereHeightfield_tmp1;
  84596. Transform.pointToLocalFrame(hfPos, hfQuat, spherePos, localSpherePos);
  84597. // Get the index of the data points to test against
  84598. var iMinX = Math.floor((localSpherePos.x - radius) / w) - 1,
  84599. iMaxX = Math.ceil((localSpherePos.x + radius) / w) + 1,
  84600. iMinY = Math.floor((localSpherePos.y - radius) / w) - 1,
  84601. iMaxY = Math.ceil((localSpherePos.y + radius) / w) + 1;
  84602. // Bail out if we are out of the terrain
  84603. if(iMaxX < 0 || iMaxY < 0 || iMinX > data.length || iMaxY > data[0].length){
  84604. return;
  84605. }
  84606. // Clamp index to edges
  84607. if(iMinX < 0){ iMinX = 0; }
  84608. if(iMaxX < 0){ iMaxX = 0; }
  84609. if(iMinY < 0){ iMinY = 0; }
  84610. if(iMaxY < 0){ iMaxY = 0; }
  84611. if(iMinX >= data.length){ iMinX = data.length - 1; }
  84612. if(iMaxX >= data.length){ iMaxX = data.length - 1; }
  84613. if(iMaxY >= data[0].length){ iMaxY = data[0].length - 1; }
  84614. if(iMinY >= data[0].length){ iMinY = data[0].length - 1; }
  84615. var minMax = [];
  84616. hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);
  84617. var min = minMax[0];
  84618. var max = minMax[1];
  84619. // Bail out if we're cant touch the bounding height box
  84620. if(localSpherePos.z - radius > max || localSpherePos.z + radius < min){
  84621. return;
  84622. }
  84623. var result = this.result;
  84624. for(var i = iMinX; i < iMaxX; i++){
  84625. for(var j = iMinY; j < iMaxY; j++){
  84626. var numContactsBefore = result.length;
  84627. // Lower triangle
  84628. hfShape.getConvexTrianglePillar(i, j, false);
  84629. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  84630. if (spherePos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + sphereShape.boundingSphereRadius) {
  84631. this.sphereConvex(sphereShape, hfShape.pillarConvex, spherePos, worldPillarOffset, sphereQuat, hfQuat, sphereBody, hfBody);
  84632. }
  84633. // Upper triangle
  84634. hfShape.getConvexTrianglePillar(i, j, true);
  84635. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  84636. if (spherePos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + sphereShape.boundingSphereRadius) {
  84637. this.sphereConvex(sphereShape, hfShape.pillarConvex, spherePos, worldPillarOffset, sphereQuat, hfQuat, sphereBody, hfBody);
  84638. }
  84639. var numContacts = result.length - numContactsBefore;
  84640. if(numContacts > 2){
  84641. return;
  84642. }
  84643. /*
  84644. // Skip all but 1
  84645. for (var k = 0; k < numContacts - 1; k++) {
  84646. result.pop();
  84647. }
  84648. */
  84649. }
  84650. }
  84651. };
  84652. },{"../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){
  84653. /* global performance */
  84654. module.exports = World;
  84655. var Shape = _dereq_('../shapes/Shape');
  84656. var Vec3 = _dereq_('../math/Vec3');
  84657. var Quaternion = _dereq_('../math/Quaternion');
  84658. var GSSolver = _dereq_('../solver/GSSolver');
  84659. var Vec3Pool = _dereq_('../utils/Vec3Pool');
  84660. var ContactEquation = _dereq_('../equations/ContactEquation');
  84661. var FrictionEquation = _dereq_('../equations/FrictionEquation');
  84662. var Narrowphase = _dereq_('./Narrowphase');
  84663. var EventTarget = _dereq_('../utils/EventTarget');
  84664. var ArrayCollisionMatrix = _dereq_('../collision/ArrayCollisionMatrix');
  84665. var Material = _dereq_('../material/Material');
  84666. var ContactMaterial = _dereq_('../material/ContactMaterial');
  84667. var Body = _dereq_('../objects/Body');
  84668. var TupleDictionary = _dereq_('../utils/TupleDictionary');
  84669. var RaycastResult = _dereq_('../collision/RaycastResult');
  84670. var AABB = _dereq_('../collision/AABB');
  84671. var Ray = _dereq_('../collision/Ray');
  84672. var NaiveBroadphase = _dereq_('../collision/NaiveBroadphase');
  84673. /**
  84674. * The physics world
  84675. * @class World
  84676. * @constructor
  84677. * @extends EventTarget
  84678. */
  84679. function World(){
  84680. EventTarget.apply(this);
  84681. /**
  84682. * 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.
  84683. * @property {Number} dt
  84684. */
  84685. this.dt = -1;
  84686. /**
  84687. * Makes bodies go to sleep when they've been inactive
  84688. * @property allowSleep
  84689. * @type {Boolean}
  84690. */
  84691. this.allowSleep = false;
  84692. /**
  84693. * All the current contacts (instances of ContactEquation) in the world.
  84694. * @property contacts
  84695. * @type {Array}
  84696. */
  84697. this.contacts = [];
  84698. this.frictionEquations = [];
  84699. /**
  84700. * 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).
  84701. * @property quatNormalizeSkip
  84702. * @type {Number}
  84703. */
  84704. this.quatNormalizeSkip = 0;
  84705. /**
  84706. * Set to true to use fast quaternion normalization. It is often enough accurate to use. If bodies tend to explode, set to false.
  84707. * @property quatNormalizeFast
  84708. * @type {Boolean}
  84709. * @see Quaternion.normalizeFast
  84710. * @see Quaternion.normalize
  84711. */
  84712. this.quatNormalizeFast = false;
  84713. /**
  84714. * The wall-clock time since simulation start
  84715. * @property time
  84716. * @type {Number}
  84717. */
  84718. this.time = 0.0;
  84719. /**
  84720. * Number of timesteps taken since start
  84721. * @property stepnumber
  84722. * @type {Number}
  84723. */
  84724. this.stepnumber = 0;
  84725. /// Default and last timestep sizes
  84726. this.default_dt = 1/60;
  84727. this.nextId = 0;
  84728. /**
  84729. * @property gravity
  84730. * @type {Vec3}
  84731. */
  84732. this.gravity = new Vec3();
  84733. /**
  84734. * @property broadphase
  84735. * @type {Broadphase}
  84736. */
  84737. this.broadphase = new NaiveBroadphase();
  84738. /**
  84739. * @property bodies
  84740. * @type {Array}
  84741. */
  84742. this.bodies = [];
  84743. /**
  84744. * @property solver
  84745. * @type {Solver}
  84746. */
  84747. this.solver = new GSSolver();
  84748. /**
  84749. * @property constraints
  84750. * @type {Array}
  84751. */
  84752. this.constraints = [];
  84753. /**
  84754. * @property narrowphase
  84755. * @type {Narrowphase}
  84756. */
  84757. this.narrowphase = new Narrowphase(this);
  84758. /**
  84759. * @property {ArrayCollisionMatrix} collisionMatrix
  84760. * @type {ArrayCollisionMatrix}
  84761. */
  84762. this.collisionMatrix = new ArrayCollisionMatrix();
  84763. /**
  84764. * CollisionMatrix from the previous step.
  84765. * @property {ArrayCollisionMatrix} collisionMatrixPrevious
  84766. * @type {ArrayCollisionMatrix}
  84767. */
  84768. this.collisionMatrixPrevious = new ArrayCollisionMatrix();
  84769. /**
  84770. * All added materials
  84771. * @property materials
  84772. * @type {Array}
  84773. */
  84774. this.materials = [];
  84775. /**
  84776. * @property contactmaterials
  84777. * @type {Array}
  84778. */
  84779. this.contactmaterials = [];
  84780. /**
  84781. * Used to look up a ContactMaterial given two instances of Material.
  84782. * @property {TupleDictionary} contactMaterialTable
  84783. */
  84784. this.contactMaterialTable = new TupleDictionary();
  84785. this.defaultMaterial = new Material("default");
  84786. /**
  84787. * This contact material is used if no suitable contactmaterial is found for a contact.
  84788. * @property defaultContactMaterial
  84789. * @type {ContactMaterial}
  84790. */
  84791. this.defaultContactMaterial = new ContactMaterial(this.defaultMaterial, this.defaultMaterial, { friction: 0.3, restitution: 0.0 });
  84792. /**
  84793. * @property doProfiling
  84794. * @type {Boolean}
  84795. */
  84796. this.doProfiling = false;
  84797. /**
  84798. * @property profile
  84799. * @type {Object}
  84800. */
  84801. this.profile = {
  84802. solve:0,
  84803. makeContactConstraints:0,
  84804. broadphase:0,
  84805. integrate:0,
  84806. narrowphase:0,
  84807. };
  84808. /**
  84809. * @property subsystems
  84810. * @type {Array}
  84811. */
  84812. this.subsystems = [];
  84813. this.addBodyEvent = {
  84814. type:"addBody",
  84815. body : null,
  84816. };
  84817. this.removeBodyEvent = {
  84818. type:"removeBody",
  84819. body : null,
  84820. };
  84821. }
  84822. World.prototype = new EventTarget();
  84823. // Temp stuff
  84824. var tmpAABB1 = new AABB();
  84825. var tmpArray1 = [];
  84826. var tmpRay = new Ray();
  84827. /**
  84828. * Get the contact material between materials m1 and m2
  84829. * @method getContactMaterial
  84830. * @param {Material} m1
  84831. * @param {Material} m2
  84832. * @return {ContactMaterial} The contact material if it was found.
  84833. */
  84834. World.prototype.getContactMaterial = function(m1,m2){
  84835. return this.contactMaterialTable.get(m1.id,m2.id); //this.contactmaterials[this.mats2cmat[i+j*this.materials.length]];
  84836. };
  84837. /**
  84838. * Get number of objects in the world.
  84839. * @method numObjects
  84840. * @return {Number}
  84841. * @deprecated
  84842. */
  84843. World.prototype.numObjects = function(){
  84844. return this.bodies.length;
  84845. };
  84846. /**
  84847. * Store old collision state info
  84848. * @method collisionMatrixTick
  84849. */
  84850. World.prototype.collisionMatrixTick = function(){
  84851. var temp = this.collisionMatrixPrevious;
  84852. this.collisionMatrixPrevious = this.collisionMatrix;
  84853. this.collisionMatrix = temp;
  84854. this.collisionMatrix.reset();
  84855. };
  84856. /**
  84857. * Add a rigid body to the simulation.
  84858. * @method add
  84859. * @param {Body} body
  84860. * @todo If the simulation has not yet started, why recrete and copy arrays for each body? Accumulate in dynamic arrays in this case.
  84861. * @todo Adding an array of bodies should be possible. This would save some loops too
  84862. * @deprecated Use .addBody instead
  84863. */
  84864. World.prototype.add = World.prototype.addBody = function(body){
  84865. if(this.bodies.indexOf(body) !== -1){
  84866. return;
  84867. }
  84868. body.index = this.bodies.length;
  84869. this.bodies.push(body);
  84870. body.world = this;
  84871. body.initPosition.copy(body.position);
  84872. body.initVelocity.copy(body.velocity);
  84873. body.timeLastSleepy = this.time;
  84874. if(body instanceof Body){
  84875. body.initAngularVelocity.copy(body.angularVelocity);
  84876. body.initQuaternion.copy(body.quaternion);
  84877. }
  84878. this.collisionMatrix.setNumObjects(this.bodies.length);
  84879. this.addBodyEvent.body = body;
  84880. this.dispatchEvent(this.addBodyEvent);
  84881. };
  84882. /**
  84883. * Add a constraint to the simulation.
  84884. * @method addConstraint
  84885. * @param {Constraint} c
  84886. */
  84887. World.prototype.addConstraint = function(c){
  84888. this.constraints.push(c);
  84889. };
  84890. /**
  84891. * Removes a constraint
  84892. * @method removeConstraint
  84893. * @param {Constraint} c
  84894. */
  84895. World.prototype.removeConstraint = function(c){
  84896. var idx = this.constraints.indexOf(c);
  84897. if(idx!==-1){
  84898. this.constraints.splice(idx,1);
  84899. }
  84900. };
  84901. /**
  84902. * Raycast test
  84903. * @method rayTest
  84904. * @param {Vec3} from
  84905. * @param {Vec3} to
  84906. * @param {Function|RaycastResult} result
  84907. * @deprecated Use .raycastAll, .raycastClosest or .raycastAny instead.
  84908. */
  84909. World.prototype.rayTest = function(from, to, result){
  84910. if(result instanceof RaycastResult){
  84911. // Do raycastclosest
  84912. this.raycastClosest(from, to, {
  84913. skipBackfaces: true
  84914. }, result);
  84915. } else {
  84916. // Do raycastAll
  84917. this.raycastAll(from, to, {
  84918. skipBackfaces: true
  84919. }, result);
  84920. }
  84921. };
  84922. /**
  84923. * Ray cast against all bodies. The provided callback will be executed for each hit with a RaycastResult as single argument.
  84924. * @method raycastAll
  84925. * @param {Vec3} from
  84926. * @param {Vec3} to
  84927. * @param {Object} options
  84928. * @param {number} [options.collisionFilterMask=-1]
  84929. * @param {number} [options.collisionFilterGroup=-1]
  84930. * @param {boolean} [options.skipBackfaces=false]
  84931. * @param {boolean} [options.checkCollisionResponse=true]
  84932. * @param {Function} callback
  84933. * @return {boolean} True if any body was hit.
  84934. */
  84935. World.prototype.raycastAll = function(from, to, options, callback){
  84936. options.mode = Ray.ALL;
  84937. options.from = from;
  84938. options.to = to;
  84939. options.callback = callback;
  84940. return tmpRay.intersectWorld(this, options);
  84941. };
  84942. /**
  84943. * Ray cast, and stop at the first result. Note that the order is random - but the method is fast.
  84944. * @method raycastAny
  84945. * @param {Vec3} from
  84946. * @param {Vec3} to
  84947. * @param {Object} options
  84948. * @param {number} [options.collisionFilterMask=-1]
  84949. * @param {number} [options.collisionFilterGroup=-1]
  84950. * @param {boolean} [options.skipBackfaces=false]
  84951. * @param {boolean} [options.checkCollisionResponse=true]
  84952. * @param {RaycastResult} result
  84953. * @return {boolean} True if any body was hit.
  84954. */
  84955. World.prototype.raycastAny = function(from, to, options, result){
  84956. options.mode = Ray.ANY;
  84957. options.from = from;
  84958. options.to = to;
  84959. options.result = result;
  84960. return tmpRay.intersectWorld(this, options);
  84961. };
  84962. /**
  84963. * Ray cast, and return information of the closest hit.
  84964. * @method raycastClosest
  84965. * @param {Vec3} from
  84966. * @param {Vec3} to
  84967. * @param {Object} options
  84968. * @param {number} [options.collisionFilterMask=-1]
  84969. * @param {number} [options.collisionFilterGroup=-1]
  84970. * @param {boolean} [options.skipBackfaces=false]
  84971. * @param {boolean} [options.checkCollisionResponse=true]
  84972. * @param {RaycastResult} result
  84973. * @return {boolean} True if any body was hit.
  84974. */
  84975. World.prototype.raycastClosest = function(from, to, options, result){
  84976. options.mode = Ray.CLOSEST;
  84977. options.from = from;
  84978. options.to = to;
  84979. options.result = result;
  84980. return tmpRay.intersectWorld(this, options);
  84981. };
  84982. /**
  84983. * Remove a rigid body from the simulation.
  84984. * @method remove
  84985. * @param {Body} body
  84986. * @deprecated Use .removeBody instead
  84987. */
  84988. World.prototype.remove = function(body){
  84989. body.world = null;
  84990. var n = this.bodies.length-1,
  84991. bodies = this.bodies,
  84992. idx = bodies.indexOf(body);
  84993. if(idx !== -1){
  84994. bodies.splice(idx, 1); // Todo: should use a garbage free method
  84995. // Recompute index
  84996. for(var i=0; i!==bodies.length; i++){
  84997. bodies[i].index = i;
  84998. }
  84999. this.collisionMatrix.setNumObjects(n);
  85000. this.removeBodyEvent.body = body;
  85001. this.dispatchEvent(this.removeBodyEvent);
  85002. }
  85003. };
  85004. /**
  85005. * Remove a rigid body from the simulation.
  85006. * @method removeBody
  85007. * @param {Body} body
  85008. */
  85009. World.prototype.removeBody = World.prototype.remove;
  85010. /**
  85011. * Adds a material to the World.
  85012. * @method addMaterial
  85013. * @param {Material} m
  85014. * @todo Necessary?
  85015. */
  85016. World.prototype.addMaterial = function(m){
  85017. this.materials.push(m);
  85018. };
  85019. /**
  85020. * Adds a contact material to the World
  85021. * @method addContactMaterial
  85022. * @param {ContactMaterial} cmat
  85023. */
  85024. World.prototype.addContactMaterial = function(cmat) {
  85025. // Add contact material
  85026. this.contactmaterials.push(cmat);
  85027. // Add current contact material to the material table
  85028. this.contactMaterialTable.set(cmat.materials[0].id,cmat.materials[1].id,cmat);
  85029. };
  85030. // performance.now()
  85031. if(typeof performance === 'undefined'){
  85032. performance = {};
  85033. }
  85034. if(!performance.now){
  85035. var nowOffset = Date.now();
  85036. if (performance.timing && performance.timing.navigationStart){
  85037. nowOffset = performance.timing.navigationStart;
  85038. }
  85039. performance.now = function(){
  85040. return Date.now() - nowOffset;
  85041. };
  85042. }
  85043. var step_tmp1 = new Vec3();
  85044. /**
  85045. * Step the physics world forward in time.
  85046. *
  85047. * 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.
  85048. *
  85049. * @method step
  85050. * @param {Number} dt The fixed time step size to use.
  85051. * @param {Number} [timeSinceLastCalled] The time elapsed since the function was last called.
  85052. * @param {Number} [maxSubSteps=10] Maximum number of fixed steps to take per function call.
  85053. *
  85054. * @example
  85055. * // fixed timestepping without interpolation
  85056. * world.step(1/60);
  85057. *
  85058. * @see http://bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World
  85059. */
  85060. World.prototype.step = function(dt, timeSinceLastCalled, maxSubSteps){
  85061. maxSubSteps = maxSubSteps || 10;
  85062. timeSinceLastCalled = timeSinceLastCalled || 0;
  85063. if(timeSinceLastCalled === 0){ // Fixed, simple stepping
  85064. this.internalStep(dt);
  85065. // Increment time
  85066. this.time += dt;
  85067. } else {
  85068. // Compute the number of fixed steps we should have taken since the last step
  85069. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  85070. internalSteps = Math.min(internalSteps,maxSubSteps);
  85071. // Do some fixed steps to catch up
  85072. var t0 = performance.now();
  85073. for(var i=0; i!==internalSteps; i++){
  85074. this.internalStep(dt);
  85075. if(performance.now() - t0 > dt * 1000){
  85076. // We are slower than real-time. Better bail out.
  85077. break;
  85078. }
  85079. }
  85080. // Increment internal clock
  85081. this.time += timeSinceLastCalled;
  85082. // Compute "Left over" time step
  85083. var h = this.time % dt;
  85084. var h_div_dt = h / dt;
  85085. var interpvelo = step_tmp1;
  85086. var bodies = this.bodies;
  85087. for(var j=0; j !== bodies.length; j++){
  85088. var b = bodies[j];
  85089. if(b.type !== Body.STATIC && b.sleepState !== Body.SLEEPING){
  85090. // Interpolate
  85091. b.position.vsub(b.previousPosition, interpvelo);
  85092. interpvelo.scale(h_div_dt, interpvelo);
  85093. b.position.vadd(interpvelo, b.interpolatedPosition);
  85094. // TODO: interpolate quaternion
  85095. // b.interpolatedAngle = b.angle + (b.angle - b.previousAngle) * h_div_dt;
  85096. } else {
  85097. // For static bodies, just copy. Who else will do it?
  85098. b.interpolatedPosition.copy(b.position);
  85099. b.interpolatedQuaternion.copy(b.quaternion);
  85100. }
  85101. }
  85102. }
  85103. };
  85104. /**
  85105. * Step the simulation
  85106. * @method step
  85107. * @param {Number} dt
  85108. */
  85109. var World_step_postStepEvent = {type:"postStep"}, // Reusable event objects to save memory
  85110. World_step_preStepEvent = {type:"preStep"},
  85111. World_step_collideEvent = {type:"collide", body:null, contact:null },
  85112. World_step_oldContacts = [], // Pools for unused objects
  85113. World_step_frictionEquationPool = [],
  85114. World_step_p1 = [], // Reusable arrays for collision pairs
  85115. World_step_p2 = [],
  85116. World_step_gvec = new Vec3(), // Temporary vectors and quats
  85117. World_step_vi = new Vec3(),
  85118. World_step_vj = new Vec3(),
  85119. World_step_wi = new Vec3(),
  85120. World_step_wj = new Vec3(),
  85121. World_step_t1 = new Vec3(),
  85122. World_step_t2 = new Vec3(),
  85123. World_step_rixn = new Vec3(),
  85124. World_step_rjxn = new Vec3(),
  85125. World_step_step_q = new Quaternion(),
  85126. World_step_step_w = new Quaternion(),
  85127. World_step_step_wq = new Quaternion(),
  85128. invI_tau_dt = new Vec3();
  85129. World.prototype.internalStep = function(dt){
  85130. this.dt = dt;
  85131. var world = this,
  85132. that = this,
  85133. contacts = this.contacts,
  85134. p1 = World_step_p1,
  85135. p2 = World_step_p2,
  85136. N = this.numObjects(),
  85137. bodies = this.bodies,
  85138. solver = this.solver,
  85139. gravity = this.gravity,
  85140. doProfiling = this.doProfiling,
  85141. profile = this.profile,
  85142. DYNAMIC = Body.DYNAMIC,
  85143. profilingStart,
  85144. constraints = this.constraints,
  85145. frictionEquationPool = World_step_frictionEquationPool,
  85146. gnorm = gravity.norm(),
  85147. gx = gravity.x,
  85148. gy = gravity.y,
  85149. gz = gravity.z,
  85150. i=0;
  85151. if(doProfiling){
  85152. profilingStart = performance.now();
  85153. }
  85154. // Add gravity to all objects
  85155. for(i=0; i!==N; i++){
  85156. var bi = bodies[i];
  85157. if(bi.type & DYNAMIC){ // Only for dynamic bodies
  85158. var f = bi.force, m = bi.mass;
  85159. f.x += m*gx;
  85160. f.y += m*gy;
  85161. f.z += m*gz;
  85162. }
  85163. }
  85164. // Update subsystems
  85165. for(var i=0, Nsubsystems=this.subsystems.length; i!==Nsubsystems; i++){
  85166. this.subsystems[i].update();
  85167. }
  85168. // Collision detection
  85169. if(doProfiling){ profilingStart = performance.now(); }
  85170. p1.length = 0; // Clean up pair arrays from last step
  85171. p2.length = 0;
  85172. this.broadphase.collisionPairs(this,p1,p2);
  85173. if(doProfiling){ profile.broadphase = performance.now() - profilingStart; }
  85174. // Remove constrained pairs with collideConnected == false
  85175. var Nconstraints = constraints.length;
  85176. for(i=0; i!==Nconstraints; i++){
  85177. var c = constraints[i];
  85178. if(!c.collideConnected){
  85179. for(var j = p1.length-1; j>=0; j-=1){
  85180. if( (c.bodyA === p1[j] && c.bodyB === p2[j]) ||
  85181. (c.bodyB === p1[j] && c.bodyA === p2[j])){
  85182. p1.splice(j, 1);
  85183. p2.splice(j, 1);
  85184. }
  85185. }
  85186. }
  85187. }
  85188. this.collisionMatrixTick();
  85189. // Generate contacts
  85190. if(doProfiling){ profilingStart = performance.now(); }
  85191. var oldcontacts = World_step_oldContacts;
  85192. var NoldContacts = contacts.length;
  85193. for(i=0; i!==NoldContacts; i++){
  85194. oldcontacts.push(contacts[i]);
  85195. }
  85196. contacts.length = 0;
  85197. // Transfer FrictionEquation from current list to the pool for reuse
  85198. var NoldFrictionEquations = this.frictionEquations.length;
  85199. for(i=0; i!==NoldFrictionEquations; i++){
  85200. frictionEquationPool.push(this.frictionEquations[i]);
  85201. }
  85202. this.frictionEquations.length = 0;
  85203. this.narrowphase.getContacts(
  85204. p1,
  85205. p2,
  85206. this,
  85207. contacts,
  85208. oldcontacts, // To be reused
  85209. this.frictionEquations,
  85210. frictionEquationPool
  85211. );
  85212. if(doProfiling){
  85213. profile.narrowphase = performance.now() - profilingStart;
  85214. }
  85215. // Loop over all collisions
  85216. if(doProfiling){
  85217. profilingStart = performance.now();
  85218. }
  85219. // Add all friction eqs
  85220. for (var i = 0; i < this.frictionEquations.length; i++) {
  85221. solver.addEquation(this.frictionEquations[i]);
  85222. }
  85223. var ncontacts = contacts.length;
  85224. for(var k=0; k!==ncontacts; k++){
  85225. // Current contact
  85226. var c = contacts[k];
  85227. // Get current collision indeces
  85228. var bi = c.bi,
  85229. bj = c.bj,
  85230. si = c.si,
  85231. sj = c.sj;
  85232. // Get collision properties
  85233. var cm;
  85234. if(bi.material && bj.material){
  85235. cm = this.getContactMaterial(bi.material,bj.material) || this.defaultContactMaterial;
  85236. } else {
  85237. cm = this.defaultContactMaterial;
  85238. }
  85239. // c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;
  85240. var mu = cm.friction;
  85241. // c.restitution = cm.restitution;
  85242. // If friction or restitution were specified in the material, use them
  85243. if(bi.material && bj.material){
  85244. if(bi.material.friction >= 0 && bj.material.friction >= 0){
  85245. mu = bi.material.friction * bj.material.friction;
  85246. }
  85247. if(bi.material.restitution >= 0 && bj.material.restitution >= 0){
  85248. c.restitution = bi.material.restitution * bj.material.restitution;
  85249. }
  85250. }
  85251. // c.setSpookParams(
  85252. // cm.contactEquationStiffness,
  85253. // cm.contactEquationRelaxation,
  85254. // dt
  85255. // );
  85256. solver.addEquation(c);
  85257. // // Add friction constraint equation
  85258. // if(mu > 0){
  85259. // // Create 2 tangent equations
  85260. // var mug = mu * gnorm;
  85261. // var reducedMass = (bi.invMass + bj.invMass);
  85262. // if(reducedMass > 0){
  85263. // reducedMass = 1/reducedMass;
  85264. // }
  85265. // var pool = frictionEquationPool;
  85266. // var c1 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass);
  85267. // var c2 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass);
  85268. // this.frictionEquations.push(c1, c2);
  85269. // c1.bi = c2.bi = bi;
  85270. // c1.bj = c2.bj = bj;
  85271. // c1.minForce = c2.minForce = -mug*reducedMass;
  85272. // c1.maxForce = c2.maxForce = mug*reducedMass;
  85273. // // Copy over the relative vectors
  85274. // c1.ri.copy(c.ri);
  85275. // c1.rj.copy(c.rj);
  85276. // c2.ri.copy(c.ri);
  85277. // c2.rj.copy(c.rj);
  85278. // // Construct tangents
  85279. // c.ni.tangents(c1.t, c2.t);
  85280. // // Set spook params
  85281. // c1.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt);
  85282. // c2.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt);
  85283. // c1.enabled = c2.enabled = c.enabled;
  85284. // // Add equations to solver
  85285. // solver.addEquation(c1);
  85286. // solver.addEquation(c2);
  85287. // }
  85288. if( bi.allowSleep &&
  85289. bi.type === Body.DYNAMIC &&
  85290. bi.sleepState === Body.SLEEPING &&
  85291. bj.sleepState === Body.AWAKE &&
  85292. bj.type !== Body.STATIC
  85293. ){
  85294. var speedSquaredB = bj.velocity.norm2() + bj.angularVelocity.norm2();
  85295. var speedLimitSquaredB = Math.pow(bj.sleepSpeedLimit,2);
  85296. if(speedSquaredB >= speedLimitSquaredB*2){
  85297. bi._wakeUpAfterNarrowphase = true;
  85298. }
  85299. }
  85300. if( bj.allowSleep &&
  85301. bj.type === Body.DYNAMIC &&
  85302. bj.sleepState === Body.SLEEPING &&
  85303. bi.sleepState === Body.AWAKE &&
  85304. bi.type !== Body.STATIC
  85305. ){
  85306. var speedSquaredA = bi.velocity.norm2() + bi.angularVelocity.norm2();
  85307. var speedLimitSquaredA = Math.pow(bi.sleepSpeedLimit,2);
  85308. if(speedSquaredA >= speedLimitSquaredA*2){
  85309. bj._wakeUpAfterNarrowphase = true;
  85310. }
  85311. }
  85312. // Now we know that i and j are in contact. Set collision matrix state
  85313. this.collisionMatrix.set(bi, bj, true);
  85314. if (!this.collisionMatrixPrevious.get(bi, bj)) {
  85315. // First contact!
  85316. // 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.
  85317. World_step_collideEvent.body = bj;
  85318. World_step_collideEvent.contact = c;
  85319. bi.dispatchEvent(World_step_collideEvent);
  85320. World_step_collideEvent.body = bi;
  85321. bj.dispatchEvent(World_step_collideEvent);
  85322. }
  85323. }
  85324. if(doProfiling){
  85325. profile.makeContactConstraints = performance.now() - profilingStart;
  85326. profilingStart = performance.now();
  85327. }
  85328. // Wake up bodies
  85329. for(i=0; i!==N; i++){
  85330. var bi = bodies[i];
  85331. if(bi._wakeUpAfterNarrowphase){
  85332. bi.wakeUp();
  85333. bi._wakeUpAfterNarrowphase = false;
  85334. }
  85335. }
  85336. // Add user-added constraints
  85337. var Nconstraints = constraints.length;
  85338. for(i=0; i!==Nconstraints; i++){
  85339. var c = constraints[i];
  85340. c.update();
  85341. for(var j=0, Neq=c.equations.length; j!==Neq; j++){
  85342. var eq = c.equations[j];
  85343. solver.addEquation(eq);
  85344. }
  85345. }
  85346. // Solve the constrained system
  85347. solver.solve(dt,this);
  85348. if(doProfiling){
  85349. profile.solve = performance.now() - profilingStart;
  85350. }
  85351. // Remove all contacts from solver
  85352. solver.removeAllEquations();
  85353. // Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details
  85354. var pow = Math.pow;
  85355. for(i=0; i!==N; i++){
  85356. var bi = bodies[i];
  85357. if(bi.type & DYNAMIC){ // Only for dynamic bodies
  85358. var ld = pow(1.0 - bi.linearDamping,dt);
  85359. var v = bi.velocity;
  85360. v.mult(ld,v);
  85361. var av = bi.angularVelocity;
  85362. if(av){
  85363. var ad = pow(1.0 - bi.angularDamping,dt);
  85364. av.mult(ad,av);
  85365. }
  85366. }
  85367. }
  85368. this.dispatchEvent(World_step_preStepEvent);
  85369. // Invoke pre-step callbacks
  85370. for(i=0; i!==N; i++){
  85371. var bi = bodies[i];
  85372. if(bi.preStep){
  85373. bi.preStep.call(bi);
  85374. }
  85375. }
  85376. // Leap frog
  85377. // vnew = v + h*f/m
  85378. // xnew = x + h*vnew
  85379. if(doProfiling){
  85380. profilingStart = performance.now();
  85381. }
  85382. var q = World_step_step_q;
  85383. var w = World_step_step_w;
  85384. var wq = World_step_step_wq;
  85385. var stepnumber = this.stepnumber;
  85386. var DYNAMIC_OR_KINEMATIC = Body.DYNAMIC | Body.KINEMATIC;
  85387. var quatNormalize = stepnumber % (this.quatNormalizeSkip+1) === 0;
  85388. var quatNormalizeFast = this.quatNormalizeFast;
  85389. var half_dt = dt * 0.5;
  85390. var PLANE = Shape.types.PLANE,
  85391. CONVEX = Shape.types.CONVEXPOLYHEDRON;
  85392. for(i=0; i!==N; i++){
  85393. var b = bodies[i],
  85394. force = b.force,
  85395. tau = b.torque;
  85396. if((b.type & DYNAMIC_OR_KINEMATIC) && b.sleepState !== Body.SLEEPING){ // Only for dynamic
  85397. var velo = b.velocity,
  85398. angularVelo = b.angularVelocity,
  85399. pos = b.position,
  85400. quat = b.quaternion,
  85401. invMass = b.invMass,
  85402. invInertia = b.invInertiaWorld;
  85403. velo.x += force.x * invMass * dt;
  85404. velo.y += force.y * invMass * dt;
  85405. velo.z += force.z * invMass * dt;
  85406. if(b.angularVelocity){
  85407. invInertia.vmult(tau,invI_tau_dt);
  85408. invI_tau_dt.mult(dt,invI_tau_dt);
  85409. invI_tau_dt.vadd(angularVelo,angularVelo);
  85410. }
  85411. // Use new velocity - leap frog
  85412. pos.x += velo.x * dt;
  85413. pos.y += velo.y * dt;
  85414. pos.z += velo.z * dt;
  85415. if(b.angularVelocity){
  85416. w.set(angularVelo.x, angularVelo.y, angularVelo.z, 0);
  85417. w.mult(quat,wq);
  85418. quat.x += half_dt * wq.x;
  85419. quat.y += half_dt * wq.y;
  85420. quat.z += half_dt * wq.z;
  85421. quat.w += half_dt * wq.w;
  85422. if(quatNormalize){
  85423. if(quatNormalizeFast){
  85424. quat.normalizeFast();
  85425. } else {
  85426. quat.normalize();
  85427. }
  85428. }
  85429. }
  85430. if(b.aabb){
  85431. b.aabbNeedsUpdate = true;
  85432. }
  85433. // Update world inertia
  85434. if(b.updateInertiaWorld){
  85435. b.updateInertiaWorld();
  85436. }
  85437. }
  85438. }
  85439. this.clearForces();
  85440. this.broadphase.dirty = true;
  85441. if(doProfiling){
  85442. profile.integrate = performance.now() - profilingStart;
  85443. }
  85444. // Update world time
  85445. this.time += dt;
  85446. this.stepnumber += 1;
  85447. this.dispatchEvent(World_step_postStepEvent);
  85448. // Invoke post-step callbacks
  85449. for(i=0; i!==N; i++){
  85450. var bi = bodies[i];
  85451. var postStep = bi.postStep;
  85452. if(postStep){
  85453. postStep.call(bi);
  85454. }
  85455. }
  85456. // Sleeping update
  85457. if(this.allowSleep){
  85458. for(i=0; i!==N; i++){
  85459. bodies[i].sleepTick(this.time);
  85460. }
  85461. }
  85462. };
  85463. /**
  85464. * Sets all body forces in the world to zero.
  85465. * @method clearForces
  85466. */
  85467. World.prototype.clearForces = function(){
  85468. var bodies = this.bodies;
  85469. var N = bodies.length;
  85470. for(var i=0; i !== N; i++){
  85471. var b = bodies[i],
  85472. force = b.force,
  85473. tau = b.torque;
  85474. b.force.set(0,0,0);
  85475. b.torque.set(0,0,0);
  85476. }
  85477. };
  85478. },{"../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])
  85479. (2)
  85480. });
  85481. /***/ }),
  85482. /* 8 */
  85483. /***/ (function(module, exports, __webpack_require__) {
  85484. /**
  85485. * from OimoPhysics DEV 1.1.0a AS3
  85486. * @author Saharan / http://el-ement.com/
  85487. *
  85488. * to Oimo.js 2015 JAVASCRIPT
  85489. * @author LoTh / http://lo-th.github.io/labs/
  85490. */
  85491. var OIMO = {
  85492. REVISION: "1.2",
  85493. // Global identification of next shape.
  85494. // This will be incremented every time a shape is created.
  85495. nextID: 0,
  85496. proxyID: 0,
  85497. // BroadPhase
  85498. BR_NULL: 0,
  85499. BR_BRUTE_FORCE: 1,
  85500. BR_SWEEP_AND_PRUNE: 2,
  85501. BR_BOUNDING_VOLUME_TREE: 3,
  85502. // body type
  85503. BODY_NULL: 0,
  85504. BODY_DYNAMIC: 1,
  85505. BODY_STATIC: 2,
  85506. // shape type
  85507. SHAPE_NULL: 0,
  85508. SHAPE_SPHERE: 1,
  85509. SHAPE_BOX: 2,
  85510. SHAPE_CYLINDER: 3,
  85511. SHAPE_TETRA: 4,
  85512. // joint type
  85513. JOINT_NULL: 0,
  85514. JOINT_DISTANCE: 1,
  85515. JOINT_BALL_AND_SOCKET: 2,
  85516. JOINT_HINGE: 3,
  85517. JOINT_WHEEL: 4,
  85518. JOINT_SLIDER: 5,
  85519. JOINT_PRISMATIC: 6,
  85520. // this world scale defaut is 0.1 to 10 meters max for dynamique body
  85521. // scale all by 100 so object is between 10 to 10000 three unit.
  85522. WORLD_SCALE: 100,
  85523. INV_SCALE: 0.01,
  85524. // AABB aproximation
  85525. AABB_PROX: 0.005,
  85526. // Math function
  85527. sqrt: Math.sqrt,
  85528. abs: Math.abs,
  85529. floor: Math.floor,
  85530. cos: Math.cos,
  85531. sin: Math.sin,
  85532. acos: Math.acos,
  85533. asin: Math.asin,
  85534. atan2: Math.atan2,
  85535. round: Math.round,
  85536. pow: Math.pow,
  85537. max: Math.max,
  85538. min: Math.min,
  85539. random: Math.random,
  85540. lerp: function (a, b, percent) { return a + (b - a) * percent; },
  85541. rand: function (a, b) { return OIMO.lerp(a, b, OIMO.random()); },
  85542. randInt: function (a, b, n) { return OIMO.lerp(a, b, OIMO.random()).toFixed(n || 0) * 1; },
  85543. int: function (x) { return ~~x; },
  85544. fix: function (x, n) { return x.toFixed(n || 3, 10); },
  85545. clamp: function (value, min, max) { return OIMO.max(min, OIMO.min(max, value)); },
  85546. degtorad: 0.0174532925199432957,
  85547. radtodeg: 57.295779513082320876,
  85548. PI: 3.141592653589793,
  85549. TwoPI: 6.283185307179586,
  85550. PI90: 1.570796326794896,
  85551. PI270: 4.712388980384689,
  85552. CustomError: null,
  85553. Error: function (Class, Msg) {
  85554. if (OIMO.CustomError == null) console.error(Class, Msg);
  85555. else OIMO.CustomError.innerHTML += Class + " - " + Msg + '<br>';
  85556. }
  85557. };
  85558. var OIMO_ARRAY_TYPE;
  85559. if (!OIMO_ARRAY_TYPE) { OIMO_ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; }
  85560. try {
  85561. (function (w) {
  85562. var perfNow;
  85563. var perfNowNames = ['now', 'webkitNow', 'msNow', 'mozNow'];
  85564. if (!!w['performance']) for (var i = 0; i < perfNowNames.length; ++i) {
  85565. var n = perfNowNames[i];
  85566. if (!!w['performance'][n]) {
  85567. perfNow = function () { return w['performance'][n]() };
  85568. break;
  85569. }
  85570. }
  85571. if (!perfNow) perfNow = Date.now;
  85572. //w.perfNow = perfNow;
  85573. OIMO.now = perfNow;
  85574. })(window);
  85575. } catch (e) { OIMO.now = function () { return 0; }; }
  85576. /**
  85577. * The class of physical computing world.
  85578. * You must be added to the world physical all computing objects
  85579. * @author saharan
  85580. * @author lo-th
  85581. */
  85582. OIMO.World = function (TimeStep, BroadPhaseType, Iterations, NoStat) {
  85583. // The time between each step
  85584. this.timeStep = TimeStep || 0.01666; // 1/60;
  85585. // The number of iterations for constraint solvers.
  85586. this.numIterations = Iterations || 8;
  85587. // It is a wide-area collision judgment that is used in order to reduce as much as possible a detailed collision judgment.
  85588. switch (BroadPhaseType || 2) {
  85589. case 1: this.broadPhase = new OIMO.BruteForceBroadPhase(); break;
  85590. case 2: default: this.broadPhase = new OIMO.SAPBroadPhase(); break;
  85591. case 3: this.broadPhase = new OIMO.DBVTBroadPhase(); break;
  85592. }
  85593. // This is the detailed information of the performance.
  85594. this.performance = null;
  85595. this.isNoStat = NoStat || false;
  85596. if (!this.isNoStat) this.performance = new OIMO.Performance(this);
  85597. // Whether the constraints randomizer is enabled or not.
  85598. this.enableRandomizer = true;
  85599. // The rigid body list
  85600. this.rigidBodies = null;
  85601. // number of rigid body
  85602. this.numRigidBodies = 0;
  85603. // The contact list
  85604. this.contacts = null;
  85605. this.unusedContacts = null;
  85606. // The number of contact
  85607. this.numContacts = 0;
  85608. // The number of contact points
  85609. this.numContactPoints = 0;
  85610. // The joint list
  85611. this.joints = null;
  85612. // The number of joints.
  85613. this.numJoints = 0;
  85614. // The number of simulation islands.
  85615. this.numIslands = 0;
  85616. // The gravity in the world.
  85617. this.gravity = new OIMO.Vec3(0, -9.80665, 0);
  85618. var numShapeTypes = 5;//4;//3;
  85619. this.detectors = [];
  85620. this.detectors.length = numShapeTypes;
  85621. var i = numShapeTypes;
  85622. while (i--) {
  85623. this.detectors[i] = [];
  85624. this.detectors[i].length = numShapeTypes;
  85625. }
  85626. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_SPHERE] = new OIMO.SphereSphereCollisionDetector();
  85627. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_BOX] = new OIMO.SphereBoxCollisionDetector(false);
  85628. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_SPHERE] = new OIMO.SphereBoxCollisionDetector(true);
  85629. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_BOX] = new OIMO.BoxBoxCollisionDetector();
  85630. // CYLINDER add
  85631. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_CYLINDER] = new OIMO.CylinderCylinderCollisionDetector();
  85632. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_BOX] = new OIMO.BoxCylinderCollisionDetector(true);
  85633. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_CYLINDER] = new OIMO.BoxCylinderCollisionDetector(false);
  85634. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_SPHERE] = new OIMO.SphereCylinderCollisionDetector(true);
  85635. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_CYLINDER] = new OIMO.SphereCylinderCollisionDetector(false);
  85636. // TETRA add
  85637. this.detectors[OIMO.SHAPE_TETRA][OIMO.SHAPE_TETRA] = new OIMO.TetraTetraCollisionDetector();
  85638. this.randX = 65535;
  85639. this.randA = 98765;
  85640. this.randB = 123456789;
  85641. //this.maxIslandRigidBodies = 64;
  85642. this.islandRigidBodies = [];
  85643. //this.islandRigidBodies.length = this.maxIslandRigidBodies;
  85644. this.islandStack = [];
  85645. //this.islandStack.length = this.maxIslandRigidBodies;
  85646. //this.maxIslandConstraints = 128;
  85647. this.islandConstraints = [];
  85648. //this.islandConstraints.length = this.maxIslandConstraints;
  85649. };
  85650. OIMO.World.prototype = {
  85651. constructor: OIMO.World,
  85652. /**
  85653. * Reset the randomizer and remove all rigid bodies, shapes, joints and any object from the world.
  85654. */
  85655. clear: function () {
  85656. this.randX = 65535;
  85657. while (this.joints !== null) {
  85658. this.removeJoint(this.joints);
  85659. }
  85660. while (this.contacts !== null) {
  85661. this.removeContact(this.contacts);
  85662. }
  85663. while (this.rigidBodies !== null) {
  85664. this.removeRigidBody(this.rigidBodies);
  85665. }
  85666. OIMO.nextID = 0;
  85667. OIMO.proxyID = 0;
  85668. },
  85669. /**
  85670. * I'll add a rigid body to the world.
  85671. * Rigid body that has been added will be the operands of each step.
  85672. * @param rigidBody Rigid body that you want to add
  85673. */
  85674. addRigidBody: function (rigidBody) {
  85675. if (rigidBody.parent) {
  85676. OIMO.Error("World", "It is not possible to be added to more than one world one of the rigid body");
  85677. }
  85678. rigidBody.parent = this;
  85679. rigidBody.awake();
  85680. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  85681. this.addShape(shape);
  85682. }
  85683. if (this.rigidBodies !== null) (this.rigidBodies.prev = rigidBody).next = this.rigidBodies;
  85684. this.rigidBodies = rigidBody;
  85685. this.numRigidBodies++;
  85686. },
  85687. /**
  85688. * I will remove the rigid body from the world.
  85689. * Rigid body that has been deleted is excluded from the calculation on a step-by-step basis.
  85690. * @param rigidBody Rigid body to be removed
  85691. */
  85692. removeRigidBody: function (rigidBody) {
  85693. var remove = rigidBody;
  85694. if (remove.parent !== this) return;
  85695. remove.awake();
  85696. var js = remove.jointLink;
  85697. while (js != null) {
  85698. var joint = js.joint;
  85699. js = js.next;
  85700. this.removeJoint(joint);
  85701. }
  85702. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  85703. this.removeShape(shape);
  85704. }
  85705. var prev = remove.prev;
  85706. var next = remove.next;
  85707. if (prev !== null) prev.next = next;
  85708. if (next !== null) next.prev = prev;
  85709. if (this.rigidBodies == remove) this.rigidBodies = next;
  85710. remove.prev = null;
  85711. remove.next = null;
  85712. remove.parent = null;
  85713. this.numRigidBodies--;
  85714. },
  85715. getByName: function (name) {
  85716. var result = null;
  85717. var body = this.rigidBodies;
  85718. while (body !== null) {
  85719. if (body.name !== " " && body.name === name) result = body;
  85720. body = body.next;
  85721. }
  85722. var joint = this.joints;
  85723. while (joint !== null) {
  85724. if (joint.name !== "" && joint.name === name) result = joint;
  85725. joint = joint.next;
  85726. }
  85727. return result;
  85728. },
  85729. /**
  85730. * I'll add a shape to the world..
  85731. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  85732. * Shape will be added to the world automatically, please do not call from outside this method.
  85733. * @param shape Shape you want to add
  85734. */
  85735. addShape: function (shape) {
  85736. if (!shape.parent || !shape.parent.parent) {
  85737. OIMO.Error("World", "It is not possible to be added alone to shape world");
  85738. }
  85739. shape.proxy = this.broadPhase.createProxy(shape);
  85740. shape.updateProxy();
  85741. this.broadPhase.addProxy(shape.proxy);
  85742. },
  85743. /**
  85744. * I will remove the shape from the world.
  85745. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  85746. * Shape will be added to the world automatically, please do not call from outside this method.
  85747. * @param shape Shape you want to delete
  85748. */
  85749. removeShape: function (shape) {
  85750. this.broadPhase.removeProxy(shape.proxy);
  85751. shape.proxy = null;
  85752. },
  85753. /**
  85754. * I'll add a joint to the world.
  85755. * Joint that has been added will be the operands of each step.
  85756. * @param shape Joint to be added
  85757. */
  85758. addJoint: function (joint) {
  85759. if (joint.parent) {
  85760. OIMO.Error("World", "It is not possible to be added to more than one world one of the joint");
  85761. }
  85762. if (this.joints != null) (this.joints.prev = joint).next = this.joints;
  85763. this.joints = joint;
  85764. joint.parent = this;
  85765. this.numJoints++;
  85766. joint.awake();
  85767. joint.attach();
  85768. },
  85769. /**
  85770. * I will remove the joint from the world.
  85771. * Joint that has been added will be the operands of each step.
  85772. * @param shape Joint to be deleted
  85773. */
  85774. removeJoint: function (joint) {
  85775. var remove = joint;
  85776. var prev = remove.prev;
  85777. var next = remove.next;
  85778. if (prev !== null) prev.next = next;
  85779. if (next !== null) next.prev = prev;
  85780. if (this.joints == remove) this.joints = next;
  85781. remove.prev = null;
  85782. remove.next = null;
  85783. this.numJoints--;
  85784. remove.awake();
  85785. remove.detach();
  85786. remove.parent = null;
  85787. },
  85788. worldscale: function (scale) {
  85789. OIMO.WORLD_SCALE = scale || 100;
  85790. OIMO.INV_SCALE = 1 / OIMO.WORLD_SCALE;
  85791. },
  85792. addContact: function (s1, s2) {
  85793. var newContact;
  85794. if (this.unusedContacts !== null) {
  85795. newContact = this.unusedContacts;
  85796. this.unusedContacts = this.unusedContacts.next;
  85797. } else {
  85798. newContact = new OIMO.Contact();
  85799. }
  85800. newContact.attach(s1, s2);
  85801. newContact.detector = this.detectors[s1.type][s2.type];
  85802. if (this.contacts) (this.contacts.prev = newContact).next = this.contacts;
  85803. this.contacts = newContact;
  85804. this.numContacts++;
  85805. },
  85806. removeContact: function (contact) {
  85807. var prev = contact.prev;
  85808. var next = contact.next;
  85809. if (next) next.prev = prev;
  85810. if (prev) prev.next = next;
  85811. if (this.contacts == contact) this.contacts = next;
  85812. contact.prev = null;
  85813. contact.next = null;
  85814. contact.detach();
  85815. contact.next = this.unusedContacts;
  85816. this.unusedContacts = contact;
  85817. this.numContacts--;
  85818. },
  85819. checkContact: function (name1, name2) {
  85820. var n1, n2;
  85821. var contact = this.contacts;
  85822. while (contact !== null) {
  85823. n1 = contact.body1.name || ' ';
  85824. n2 = contact.body2.name || ' ';
  85825. if ((n1 == name1 && n2 == name2) || (n2 == name1 && n1 == name2)) { if (contact.touching) return true; else return false; }
  85826. else contact = contact.next;
  85827. }
  85828. return false;
  85829. },
  85830. callSleep: function (body) {
  85831. if (!body.allowSleep) return false;
  85832. if (body.linearVelocity.lengthSq() > 0.04) return false;
  85833. if (body.angularVelocity.lengthSq() > 0.25) return false;
  85834. return true;
  85835. },
  85836. /**
  85837. * I will proceed only time step seconds time of World.
  85838. */
  85839. step: function () {
  85840. var time0, time1, time2, time3;
  85841. var stat = !this.isNoStat ? true : false;
  85842. if (stat) time0 = OIMO.now();
  85843. var body = this.rigidBodies;
  85844. while (body !== null) {
  85845. body.addedToIsland = false;
  85846. if (body.sleeping) {
  85847. if (
  85848. body.linearVelocity.testZero() ||
  85849. body.angularVelocity.testZero() ||
  85850. body.position.testDiff(body.sleepPosition) ||
  85851. body.orientation.testDiff(body.sleepOrientation)
  85852. ) body.awake(); // awake the body
  85853. }
  85854. body = body.next;
  85855. }
  85856. //------------------------------------------------------
  85857. // UPDATE CONTACT
  85858. //------------------------------------------------------
  85859. // broad phase
  85860. if (stat) time1 = OIMO.now();
  85861. this.broadPhase.detectPairs();
  85862. var pairs = this.broadPhase.pairs;
  85863. var i = this.broadPhase.numPairs;
  85864. //do{
  85865. while (i--) {
  85866. //for(var i=0, l=numPairs; i<l; i++){
  85867. var pair = pairs[i];
  85868. var s1;
  85869. var s2;
  85870. if (pair.shape1.id < pair.shape2.id) {
  85871. s1 = pair.shape1;
  85872. s2 = pair.shape2;
  85873. } else {
  85874. s1 = pair.shape2;
  85875. s2 = pair.shape1;
  85876. }
  85877. var link;
  85878. if (s1.numContacts < s2.numContacts) link = s1.contactLink;
  85879. else link = s2.contactLink;
  85880. var exists = false;
  85881. while (link) {
  85882. var contact = link.contact;
  85883. if (contact.shape1 == s1 && contact.shape2 == s2) {
  85884. contact.persisting = true;
  85885. exists = true;// contact already exists
  85886. break;
  85887. }
  85888. link = link.next;
  85889. }
  85890. if (!exists) {
  85891. this.addContact(s1, s2);
  85892. }
  85893. }// while(i-- >0);
  85894. if (stat) {
  85895. time2 = OIMO.now();
  85896. this.performance.broadPhaseTime = time2 - time1;
  85897. }
  85898. // update & narrow phase
  85899. this.numContactPoints = 0;
  85900. contact = this.contacts;
  85901. while (contact !== null) {
  85902. if (!contact.persisting) {
  85903. if (contact.shape1.aabb.intersectTest(contact.shape2.aabb)) {
  85904. /*var aabb1=contact.shape1.aabb;
  85905. var aabb2=contact.shape2.aabb;
  85906. if(
  85907. aabb1.minX>aabb2.maxX || aabb1.maxX<aabb2.minX ||
  85908. aabb1.minY>aabb2.maxY || aabb1.maxY<aabb2.minY ||
  85909. aabb1.minZ>aabb2.maxZ || aabb1.maxZ<aabb2.minZ
  85910. ){*/
  85911. var next = contact.next;
  85912. this.removeContact(contact);
  85913. contact = next;
  85914. continue;
  85915. }
  85916. }
  85917. var b1 = contact.body1;
  85918. var b2 = contact.body2;
  85919. if (b1.isDynamic && !b1.sleeping || b2.isDynamic && !b2.sleeping) {
  85920. contact.updateManifold();
  85921. }
  85922. this.numContactPoints += contact.manifold.numPoints;
  85923. contact.persisting = false;
  85924. contact.constraint.addedToIsland = false;
  85925. contact = contact.next;
  85926. }
  85927. if (stat) {
  85928. time3 = OIMO.now();
  85929. this.performance.narrowPhaseTime = time3 - time2;
  85930. }
  85931. //------------------------------------------------------
  85932. // SOLVE ISLANDS
  85933. //------------------------------------------------------
  85934. var invTimeStep = 1 / this.timeStep;
  85935. //var body;
  85936. var joint;
  85937. var constraint;
  85938. //var num;
  85939. for (joint = this.joints; joint !== null; joint = joint.next) {
  85940. joint.addedToIsland = false;
  85941. }
  85942. // clear old island array
  85943. this.islandRigidBodies = [];
  85944. this.islandConstraints = [];
  85945. this.islandStack = [];
  85946. // expand island buffers
  85947. /*if(this.maxIslandRigidBodies<this.numRigidBodies){
  85948. this.maxIslandRigidBodies=this.numRigidBodies<<1;
  85949. //this.maxIslandRigidBodies=this.numRigidBodies*2;
  85950. this.islandRigidBodies=[];
  85951. this.islandStack=[];
  85952. this.islandRigidBodies.length = this.maxIslandRigidBodies;
  85953. this.islandStack.length = this.maxIslandRigidBodies;
  85954. }
  85955. var numConstraints=this.numJoints+this.numContacts;
  85956. if(this.maxIslandConstraints<numConstraints){
  85957. this.maxIslandConstraints=numConstraints<<1;
  85958. //this.maxIslandConstraints=numConstraints*2;
  85959. this.islandConstraints=[];
  85960. this.islandConstraints.length = this.maxIslandConstraints;
  85961. }*/
  85962. time1 = OIMO.now();
  85963. this.numIslands = 0;
  85964. // build and solve simulation islands
  85965. for (var base = this.rigidBodies; base !== null; base = base.next) {
  85966. if (base.addedToIsland || base.isStatic || base.sleeping) continue;// ignore
  85967. if (base.isLonely()) {// update single body
  85968. if (base.isDynamic) {
  85969. base.linearVelocity.addTime(this.gravity, this.timeStep);
  85970. /*base.linearVelocity.x+=this.gravity.x*this.timeStep;
  85971. base.linearVelocity.y+=this.gravity.y*this.timeStep;
  85972. base.linearVelocity.z+=this.gravity.z*this.timeStep;*/
  85973. }
  85974. if (this.callSleep(base)) {
  85975. base.sleepTime += this.timeStep;
  85976. if (base.sleepTime > 0.5) base.sleep();
  85977. else base.updatePosition(this.timeStep);
  85978. } else {
  85979. base.sleepTime = 0;
  85980. base.updatePosition(this.timeStep);
  85981. }
  85982. this.numIslands++;
  85983. continue;
  85984. }
  85985. var islandNumRigidBodies = 0;
  85986. var islandNumConstraints = 0;
  85987. var stackCount = 1;
  85988. // add rigid body to stack
  85989. this.islandStack[0] = base;
  85990. base.addedToIsland = true;
  85991. // build an island
  85992. do {
  85993. // get rigid body from stack
  85994. body = this.islandStack[--stackCount];
  85995. this.islandStack[stackCount] = null;
  85996. body.sleeping = false;
  85997. // add rigid body to the island
  85998. this.islandRigidBodies[islandNumRigidBodies++] = body;
  85999. if (body.isStatic) continue;
  86000. // search connections
  86001. for (var cs = body.contactLink; cs !== null; cs = cs.next) {
  86002. var contact = cs.contact;
  86003. constraint = contact.constraint;
  86004. if (constraint.addedToIsland || !contact.touching) continue;// ignore
  86005. // add constraint to the island
  86006. this.islandConstraints[islandNumConstraints++] = constraint;
  86007. constraint.addedToIsland = true;
  86008. var next = cs.body;
  86009. if (next.addedToIsland) continue;
  86010. // add rigid body to stack
  86011. this.islandStack[stackCount++] = next;
  86012. next.addedToIsland = true;
  86013. }
  86014. for (var js = body.jointLink; js !== null; js = js.next) {
  86015. constraint = js.joint;
  86016. if (constraint.addedToIsland) continue;// ignore
  86017. // add constraint to the island
  86018. this.islandConstraints[islandNumConstraints++] = constraint;
  86019. constraint.addedToIsland = true;
  86020. next = js.body;
  86021. if (next.addedToIsland || !next.isDynamic) continue;
  86022. // add rigid body to stack
  86023. this.islandStack[stackCount++] = next;
  86024. next.addedToIsland = true;
  86025. }
  86026. } while (stackCount != 0);
  86027. // update velocities
  86028. var gVel = new OIMO.Vec3().addTime(this.gravity, this.timeStep);
  86029. /*var gx=this.gravity.x*this.timeStep;
  86030. var gy=this.gravity.y*this.timeStep;
  86031. var gz=this.gravity.z*this.timeStep;*/
  86032. var j = islandNumRigidBodies;
  86033. while (j--) {
  86034. //or(var j=0, l=islandNumRigidBodies; j<l; j++){
  86035. body = this.islandRigidBodies[j];
  86036. if (body.isDynamic) {
  86037. body.linearVelocity.addEqual(gVel);
  86038. /*body.linearVelocity.x+=gx;
  86039. body.linearVelocity.y+=gy;
  86040. body.linearVelocity.z+=gz;*/
  86041. }
  86042. }
  86043. // randomizing order
  86044. if (this.enableRandomizer) {
  86045. //for(var j=1, l=islandNumConstraints; j<l; j++){
  86046. j = islandNumConstraints;
  86047. while (j--) {
  86048. if (j !== 0) {
  86049. var swap = (this.randX = (this.randX * this.randA + this.randB & 0x7fffffff)) / 2147483648.0 * j | 0;
  86050. constraint = this.islandConstraints[j];
  86051. this.islandConstraints[j] = this.islandConstraints[swap];
  86052. this.islandConstraints[swap] = constraint;
  86053. }
  86054. }
  86055. }
  86056. // solve contraints
  86057. j = islandNumConstraints;
  86058. while (j--) {
  86059. //for(j=0, l=islandNumConstraints; j<l; j++){
  86060. this.islandConstraints[j].preSolve(this.timeStep, invTimeStep);// pre-solve
  86061. }
  86062. var k = this.numIterations;
  86063. while (k--) {
  86064. //for(var k=0, l=this.numIterations; k<l; k++){
  86065. j = islandNumConstraints;
  86066. while (j--) {
  86067. //for(j=0, m=islandNumConstraints; j<m; j++){
  86068. this.islandConstraints[j].solve();// main-solve
  86069. }
  86070. }
  86071. j = islandNumConstraints;
  86072. while (j--) {
  86073. //for(j=0, l=islandNumConstraints; j<l; j++){
  86074. this.islandConstraints[j].postSolve();// post-solve
  86075. this.islandConstraints[j] = null;// gc
  86076. }
  86077. // sleeping check
  86078. var sleepTime = 10;
  86079. j = islandNumRigidBodies;
  86080. while (j--) {
  86081. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  86082. body = this.islandRigidBodies[j];
  86083. if (this.callSleep(body)) {
  86084. body.sleepTime += this.timeStep;
  86085. if (body.sleepTime < sleepTime) sleepTime = body.sleepTime;
  86086. } else {
  86087. body.sleepTime = 0;
  86088. sleepTime = 0;
  86089. continue;
  86090. }
  86091. }
  86092. if (sleepTime > 0.5) {
  86093. // sleep the island
  86094. j = islandNumRigidBodies;
  86095. while (j--) {
  86096. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  86097. this.islandRigidBodies[j].sleep();
  86098. this.islandRigidBodies[j] = null;// gc
  86099. }
  86100. } else {
  86101. // update positions
  86102. j = islandNumRigidBodies;
  86103. while (j--) {
  86104. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  86105. this.islandRigidBodies[j].updatePosition(this.timeStep);
  86106. this.islandRigidBodies[j] = null;// gc
  86107. }
  86108. }
  86109. this.numIslands++;
  86110. }
  86111. if (stat) {
  86112. time2 = OIMO.now();
  86113. this.performance.solvingTime = time2 - time1;
  86114. //------------------------------------------------------
  86115. // END SIMULATION
  86116. //------------------------------------------------------
  86117. time2 = OIMO.now();
  86118. // fps update
  86119. this.performance.upfps();
  86120. this.performance.totalTime = time2 - time0;
  86121. }
  86122. }
  86123. }
  86124. /**
  86125. * The class of rigid body.
  86126. * Rigid body has the shape of a single or multiple collision processing,
  86127. * I can set the parameters individually.
  86128. * @author saharan
  86129. */
  86130. OIMO.RigidBody = function (x, y, z, rad, ax, ay, az) {
  86131. this.name = " ";
  86132. // The maximum number of shapes that can be added to a one rigid.
  86133. this.MAX_SHAPES = 64;//64;
  86134. this.prev = null;
  86135. this.next = null;
  86136. // I represent the kind of rigid body.
  86137. // Please do not change from the outside this variable.
  86138. // If you want to change the type of rigid body, always
  86139. // Please specify the type you want to set the arguments of setupMass method.
  86140. this.type = OIMO.BODY_NULL;
  86141. this.massInfo = new OIMO.MassInfo();
  86142. // It is the world coordinate of the center of gravity.
  86143. this.position = new OIMO.Vec3(x, y, z);
  86144. this.orientation = this.rotationAxisToQuad(rad || 0, ax || 0, ay || 0, az || 0);
  86145. this.newPosition = new OIMO.Vec3();
  86146. this.controlPos = false;
  86147. this.newOrientation = new OIMO.Quat();
  86148. this.newRotation = new OIMO.Vec3();
  86149. this.currentRotation = new OIMO.Vec3();
  86150. this.controlRot = false;
  86151. this.controlRotInTime = false;
  86152. // Is the translational velocity.
  86153. this.linearVelocity = new OIMO.Vec3();
  86154. // Is the angular velocity.
  86155. this.angularVelocity = new OIMO.Vec3();
  86156. // return matrix for three.js
  86157. this.matrix = new OIMO.Mat44();
  86158. //--------------------------------------------
  86159. // Please do not change from the outside this variables.
  86160. //--------------------------------------------
  86161. // It is a world that rigid body has been added.
  86162. this.parent = null;
  86163. this.contactLink = null;
  86164. this.numContacts = 0;
  86165. // An array of shapes that are included in the rigid body.
  86166. this.shapes = null;
  86167. // The number of shapes that are included in the rigid body.
  86168. this.numShapes = 0;
  86169. // It is the link array of joint that is connected to the rigid body.
  86170. this.jointLink = null;
  86171. // The number of joints that are connected to the rigid body.
  86172. this.numJoints = 0;
  86173. // It is the world coordinate of the center of gravity in the sleep just before.
  86174. this.sleepPosition = new OIMO.Vec3();
  86175. // It is a quaternion that represents the attitude of sleep just before.
  86176. this.sleepOrientation = new OIMO.Quat();
  86177. // I will show this rigid body to determine whether it is a rigid body static.
  86178. this.isStatic = false;
  86179. // I indicates that this rigid body to determine whether it is a rigid body dynamic.
  86180. this.isDynamic = false;
  86181. // It is a rotation matrix representing the orientation.
  86182. this.rotation = new OIMO.Mat33();
  86183. //--------------------------------------------
  86184. // It will be recalculated automatically from the shape, which is included.
  86185. //--------------------------------------------
  86186. // This is the weight.
  86187. this.mass = NaN;
  86188. // It is the reciprocal of the mass.
  86189. this.inverseMass = NaN;
  86190. // It is the inverse of the inertia tensor in the world system.
  86191. this.inverseInertia = new OIMO.Mat33();
  86192. // It is the inertia tensor in the initial state.
  86193. this.localInertia = new OIMO.Mat33();
  86194. // It is the inverse of the inertia tensor in the initial state.
  86195. this.inverseLocalInertia = new OIMO.Mat33();
  86196. // I indicates rigid body whether it has been added to the simulation Island.
  86197. this.addedToIsland = false;
  86198. // It shows how to sleep rigid body.
  86199. this.allowSleep = true;
  86200. // This is the time from when the rigid body at rest.
  86201. this.sleepTime = 0;
  86202. // I shows rigid body to determine whether it is a sleep state.
  86203. this.sleeping = false;
  86204. };
  86205. OIMO.RigidBody.prototype = {
  86206. constructor: OIMO.RigidBody,
  86207. /**
  86208. * I'll add a shape to rigid body.
  86209. * If you add a shape, please call the setupMass method to step up to the start of the next.
  86210. * @param shape shape to Add
  86211. */
  86212. addShape: function (shape) {
  86213. if (shape.parent) OIMO.Error("RigidBody", "It is not possible that you add to the multi-rigid body the shape of one");
  86214. if (this.shapes != null) (this.shapes.prev = shape).next = this.shapes;
  86215. this.shapes = shape;
  86216. shape.parent = this;
  86217. if (this.parent) this.parent.addShape(shape);
  86218. this.numShapes++;
  86219. },
  86220. /**
  86221. * I will delete the shape from the rigid body.
  86222. * If you delete a shape, please call the setupMass method to step up to the start of the next.
  86223. * @param shape shape to Delete
  86224. */
  86225. removeShape: function (shape) {
  86226. var remove = shape;
  86227. if (remove.parent != this) return;
  86228. var prev = remove.prev;
  86229. var next = remove.next;
  86230. if (prev != null) prev.next = next;
  86231. if (next != null) next.prev = prev;
  86232. if (this.shapes == remove) this.shapes = next;
  86233. remove.prev = null;
  86234. remove.next = null;
  86235. remove.parent = null;
  86236. if (this.parent) this.parent.removeShape(remove);
  86237. this.numShapes--;
  86238. },
  86239. remove: function () {
  86240. this.dispose();
  86241. },
  86242. dispose: function () {
  86243. this.parent.removeRigidBody(this);
  86244. },
  86245. checkContact: function (name) {
  86246. this.parent.checkContact(this.name, name);
  86247. },
  86248. /**
  86249. * Calulates mass datas(center of gravity, mass, moment inertia, etc...).
  86250. * If the parameter type is set to BODY_STATIC, the rigid body will be fixed to the space.
  86251. * If the parameter adjustPosition is set to true, the shapes' relative positions and
  86252. * the rigid body's position will be adjusted to the center of gravity.
  86253. * @param type
  86254. * @param adjustPosition
  86255. */
  86256. setupMass: function (type, AdjustPosition) {
  86257. var adjustPosition = (AdjustPosition !== undefined) ? AdjustPosition : true;
  86258. this.type = type || OIMO.BODY_DYNAMIC;
  86259. this.isDynamic = this.type == OIMO.BODY_DYNAMIC;
  86260. this.isStatic = this.type == OIMO.BODY_STATIC;
  86261. this.mass = 0;
  86262. this.localInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  86263. var te = this.localInertia.elements;
  86264. //
  86265. var tmpM = new OIMO.Mat33();
  86266. var tmpV = new OIMO.Vec3();
  86267. for (var shape = this.shapes; shape != null; shape = shape.next) {
  86268. shape.calculateMassInfo(this.massInfo);
  86269. var shapeMass = this.massInfo.mass;
  86270. var relX = shape.relativePosition.x;
  86271. var relY = shape.relativePosition.y;
  86272. var relZ = shape.relativePosition.z;
  86273. /*tmpV.x+=relX*shapeMass;
  86274. tmpV.y+=relY*shapeMass;
  86275. tmpV.z+=relZ*shapeMass;*/
  86276. tmpV.addScale(shape.relativePosition, shapeMass);
  86277. this.mass += shapeMass;
  86278. this.rotateInertia(shape.relativeRotation, this.massInfo.inertia, tmpM);
  86279. this.localInertia.addEqual(tmpM);
  86280. // add offset inertia
  86281. te[0] += shapeMass * (relY * relY + relZ * relZ);
  86282. te[4] += shapeMass * (relX * relX + relZ * relZ);
  86283. te[8] += shapeMass * (relX * relX + relY * relY);
  86284. var xy = shapeMass * relX * relY;
  86285. var yz = shapeMass * relY * relZ;
  86286. var zx = shapeMass * relZ * relX;
  86287. te[1] -= xy;
  86288. te[3] -= xy;
  86289. te[2] -= yz;
  86290. te[6] -= yz;
  86291. te[5] -= zx;
  86292. te[7] -= zx;
  86293. }
  86294. this.inverseMass = 1 / this.mass;
  86295. tmpV.scaleEqual(this.inverseMass);
  86296. if (adjustPosition) {
  86297. this.position.addEqual(tmpV);
  86298. for (shape = this.shapes; shape != null; shape = shape.next) {
  86299. shape.relativePosition.subEqual(tmpV);
  86300. }
  86301. // subtract offset inertia
  86302. relX = tmpV.x;
  86303. relY = tmpV.y;
  86304. relZ = tmpV.z;
  86305. //var te = this.localInertia.elements;
  86306. te[0] -= this.mass * (relY * relY + relZ * relZ);
  86307. te[4] -= this.mass * (relX * relX + relZ * relZ);
  86308. te[8] -= this.mass * (relX * relX + relY * relY);
  86309. xy = this.mass * relX * relY;
  86310. yz = this.mass * relY * relZ;
  86311. zx = this.mass * relZ * relX;
  86312. te[1] += xy;
  86313. te[3] += xy;
  86314. te[2] += yz;
  86315. te[6] += yz;
  86316. te[5] += zx;
  86317. te[7] += zx;
  86318. }
  86319. this.inverseLocalInertia.invert(this.localInertia);
  86320. if (this.type == OIMO.BODY_STATIC) {
  86321. this.inverseMass = 0;
  86322. this.inverseLocalInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  86323. }
  86324. this.syncShapes();
  86325. this.awake();
  86326. },
  86327. /**
  86328. * Awake the rigid body.
  86329. */
  86330. awake: function () {
  86331. if (!this.allowSleep || !this.sleeping) return;
  86332. this.sleeping = false;
  86333. this.sleepTime = 0;
  86334. // awake connected constraints
  86335. var cs = this.contactLink;
  86336. while (cs != null) {
  86337. cs.body.sleepTime = 0;
  86338. cs.body.sleeping = false;
  86339. cs = cs.next;
  86340. }
  86341. var js = this.jointLink;
  86342. while (js != null) {
  86343. js.body.sleepTime = 0;
  86344. js.body.sleeping = false;
  86345. js = js.next;
  86346. }
  86347. for (var shape = this.shapes; shape != null; shape = shape.next) {
  86348. shape.updateProxy();
  86349. }
  86350. },
  86351. /**
  86352. * Sleep the rigid body.
  86353. */
  86354. sleep: function () {
  86355. if (!this.allowSleep || this.sleeping) return;
  86356. this.linearVelocity.set(0, 0, 0);
  86357. this.angularVelocity.set(0, 0, 0);
  86358. this.sleepPosition.copy(this.position);
  86359. this.sleepOrientation.copy(this.orientation);
  86360. /*this.linearVelocity.x=0;
  86361. this.linearVelocity.y=0;
  86362. this.linearVelocity.z=0;
  86363. this.angularVelocity.x=0;
  86364. this.angularVelocity.y=0;
  86365. this.angularVelocity.z=0;
  86366. this.sleepPosition.x=this.position.x;
  86367. this.sleepPosition.y=this.position.y;
  86368. this.sleepPosition.z=this.position.z;*/
  86369. /*this.sleepOrientation.s=this.orientation.s;
  86370. this.sleepOrientation.x=this.orientation.x;
  86371. this.sleepOrientation.y=this.orientation.y;
  86372. this.sleepOrientation.z=this.orientation.z;*/
  86373. this.sleepTime = 0;
  86374. this.sleeping = true;
  86375. for (var shape = this.shapes; shape != null; shape = shape.next) {
  86376. shape.updateProxy();
  86377. }
  86378. },
  86379. /**
  86380. * Get whether the rigid body has not any connection with others.
  86381. * @return
  86382. */
  86383. isLonely: function () {
  86384. return this.numJoints == 0 && this.numContacts == 0;
  86385. },
  86386. /**
  86387. * The time integration of the motion of a rigid body, you can update the information such as the shape.
  86388. * This method is invoked automatically when calling the step of the World,
  86389. * There is no need to call from outside usually.
  86390. * @param timeStep time
  86391. */
  86392. updatePosition: function (timeStep) {
  86393. switch (this.type) {
  86394. case OIMO.BODY_STATIC:
  86395. this.linearVelocity.set(0, 0, 0);
  86396. this.angularVelocity.set(0, 0, 0);
  86397. // ONLY FOR TEST
  86398. if (this.controlPos) {
  86399. this.position.copy(this.newPosition);
  86400. this.controlPos = false;
  86401. }
  86402. if (this.controlRot) {
  86403. this.orientation.copy(this.newOrientation);
  86404. this.controlRot = false;
  86405. }
  86406. /*this.linearVelocity.x=0;
  86407. this.linearVelocity.y=0;
  86408. this.linearVelocity.z=0;
  86409. this.angularVelocity.x=0;
  86410. this.angularVelocity.y=0;
  86411. this.angularVelocity.z=0;*/
  86412. break;
  86413. case OIMO.BODY_DYNAMIC:
  86414. if (this.controlPos) {
  86415. this.angularVelocity.set(0, 0, 0);
  86416. this.linearVelocity.set(0, 0, 0);
  86417. this.linearVelocity.x = (this.newPosition.x - this.position.x) / timeStep;
  86418. this.linearVelocity.y = (this.newPosition.y - this.position.y) / timeStep;
  86419. this.linearVelocity.z = (this.newPosition.z - this.position.z) / timeStep;
  86420. this.controlPos = false;
  86421. }
  86422. if (this.controlRot) {
  86423. this.angularVelocity.set(0, 0, 0);
  86424. this.orientation.copy(this.newOrientation);
  86425. //var t=timeStep//*0.5;
  86426. //var q = new OIMO.Quat();
  86427. //q.sub(this.newOrientation, this.orientation);
  86428. //q.normalize(q);
  86429. /*q.s = (this.newOrientation.s - this.orientation.s)/t;
  86430. q.x = (this.newOrientation.x - this.orientation.x)/t;
  86431. q.y = (this.newOrientation.y - this.orientation.y)/t;
  86432. q.z = (this.newOrientation.z - this.orientation.z)/t;*/
  86433. //this.angularVelocity.applyQuaternion(q);
  86434. //this.angularVelocity.x = this.angularVelocity.x/t;
  86435. //this.angularVelocity.y = this.angularVelocity.y/t;
  86436. //this.angularVelocity.z = this.angularVelocity.z/t;
  86437. this.controlRot = false;
  86438. }
  86439. this.position.addTime(this.linearVelocity, timeStep);
  86440. this.orientation.addTime(this.angularVelocity, timeStep);
  86441. break;
  86442. default: OIMO.Error("RigidBody", "Invalid type.");
  86443. }
  86444. this.syncShapes();
  86445. },
  86446. rotateInertia: function (rot, inertia, out) {
  86447. var tm1 = rot.elements;
  86448. var tm2 = inertia.elements;
  86449. var a0 = tm1[0], a3 = tm1[3], a6 = tm1[6];
  86450. var a1 = tm1[1], a4 = tm1[4], a7 = tm1[7];
  86451. var a2 = tm1[2], a5 = tm1[5], a8 = tm1[8];
  86452. var b0 = tm2[0], b3 = tm2[3], b6 = tm2[6];
  86453. var b1 = tm2[1], b4 = tm2[4], b7 = tm2[7];
  86454. var b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  86455. var e00 = a0 * b0 + a1 * b3 + a2 * b6;
  86456. var e01 = a0 * b1 + a1 * b4 + a2 * b7;
  86457. var e02 = a0 * b2 + a1 * b5 + a2 * b8;
  86458. var e10 = a3 * b0 + a4 * b3 + a5 * b6;
  86459. var e11 = a3 * b1 + a4 * b4 + a5 * b7;
  86460. var e12 = a3 * b2 + a4 * b5 + a5 * b8;
  86461. var e20 = a6 * b0 + a7 * b3 + a8 * b6;
  86462. var e21 = a6 * b1 + a7 * b4 + a8 * b7;
  86463. var e22 = a6 * b2 + a7 * b5 + a8 * b8;
  86464. var oe = out.elements;
  86465. oe[0] = e00 * a0 + e01 * a1 + e02 * a2;
  86466. oe[1] = e00 * a3 + e01 * a4 + e02 * a5;
  86467. oe[2] = e00 * a6 + e01 * a7 + e02 * a8;
  86468. oe[3] = e10 * a0 + e11 * a1 + e12 * a2;
  86469. oe[4] = e10 * a3 + e11 * a4 + e12 * a5;
  86470. oe[5] = e10 * a6 + e11 * a7 + e12 * a8;
  86471. oe[6] = e20 * a0 + e21 * a1 + e22 * a2;
  86472. oe[7] = e20 * a3 + e21 * a4 + e22 * a5;
  86473. oe[8] = e20 * a6 + e21 * a7 + e22 * a8;
  86474. },
  86475. syncShapes: function () {
  86476. var s = this.orientation.s;
  86477. var x = this.orientation.x;
  86478. var y = this.orientation.y;
  86479. var z = this.orientation.z;
  86480. var x2 = 2 * x;
  86481. var y2 = 2 * y;
  86482. var z2 = 2 * z;
  86483. var xx = x * x2;
  86484. var yy = y * y2;
  86485. var zz = z * z2;
  86486. var xy = x * y2;
  86487. var yz = y * z2;
  86488. var xz = x * z2;
  86489. var sx = s * x2;
  86490. var sy = s * y2;
  86491. var sz = s * z2;
  86492. var tr = this.rotation.elements;
  86493. tr[0] = 1 - yy - zz;
  86494. tr[1] = xy - sz;
  86495. tr[2] = xz + sy;
  86496. tr[3] = xy + sz;
  86497. tr[4] = 1 - xx - zz;
  86498. tr[5] = yz - sx;
  86499. tr[6] = xz - sy;
  86500. tr[7] = yz + sx;
  86501. tr[8] = 1 - xx - yy;
  86502. this.rotateInertia(this.rotation, this.inverseLocalInertia, this.inverseInertia);
  86503. for (var shape = this.shapes; shape != null; shape = shape.next) {
  86504. //var relPos=shape.relativePosition;
  86505. //var relRot=shape.relativeRotation;
  86506. //var rot=shape.rotation;
  86507. /*var lx=relPos.x;
  86508. var ly=relPos.y;
  86509. var lz=relPos.z;
  86510. shape.position.x=this.position.x+lx*tr[0]+ly*tr[1]+lz*tr[2];
  86511. shape.position.y=this.position.y+lx*tr[3]+ly*tr[4]+lz*tr[5];
  86512. shape.position.z=this.position.z+lx*tr[6]+ly*tr[7]+lz*tr[8];*/
  86513. shape.position.mul(this.position, shape.relativePosition, this.rotation);
  86514. //shape.rotation.mul(shape.relativeRotation,this.rotation);
  86515. // add by QuaziKb
  86516. shape.rotation.mul(this.rotation, shape.relativeRotation);
  86517. shape.updateProxy();
  86518. }
  86519. },
  86520. applyImpulse: function (position, force) {
  86521. this.linearVelocity.addScale(force, this.inverseMass);
  86522. /*this.linearVelocity.x+=force.x*this.inverseMass;
  86523. this.linearVelocity.y+=force.y*this.inverseMass;
  86524. this.linearVelocity.z+=force.z*this.inverseMass;*/
  86525. var rel = new OIMO.Vec3();
  86526. rel.sub(position, this.position).cross(rel, force).mulMat(this.inverseInertia, rel);
  86527. this.angularVelocity.addEqual(rel);
  86528. /*this.angularVelocity.x+=rel.x;
  86529. this.angularVelocity.y+=rel.y;
  86530. this.angularVelocity.z+=rel.z;*/
  86531. },
  86532. //---------------------------------------------
  86533. //
  86534. // FOR THREE JS
  86535. //
  86536. //---------------------------------------------
  86537. rotationVectToQuad: function (rot) {
  86538. var r = OIMO.EulerToAxis(rot.x * OIMO.degtorad, rot.y * OIMO.degtorad, rot.z * OIMO.degtorad);
  86539. return this.rotationAxisToQuad(r[0], r[1], r[2], r[3]);
  86540. },
  86541. rotationAxisToQuad: function (rad, ax, ay, az) { // in radian
  86542. var len = ax * ax + ay * ay + az * az;
  86543. if (len > 0) {
  86544. len = 1 / OIMO.sqrt(len);
  86545. ax *= len;
  86546. ay *= len;
  86547. az *= len;
  86548. }
  86549. var sin = OIMO.sin(rad * 0.5);
  86550. var cos = OIMO.cos(rad * 0.5);
  86551. return new OIMO.Quat(cos, sin * ax, sin * ay, sin * az);
  86552. },
  86553. //---------------------------------------------
  86554. // SET DYNAMIQUE POSITION AND ROTATION
  86555. //---------------------------------------------
  86556. setPosition: function (pos) {
  86557. this.newPosition.copy(pos).multiplyScalar(OIMO.INV_SCALE);
  86558. //this.newPosition.set(pos.x*OIMO.INV_SCALE,pos.y*OIMO.INV_SCALE,pos.z*OIMO.INV_SCALE);
  86559. this.controlPos = true;
  86560. },
  86561. setQuaternion: function (q) {
  86562. //if(this.type == this.BODY_STATIC)this.orientation.init(q.w,q.x,q.y,q.z);
  86563. this.newOrientation.set(q.x, q.y, q.z, q.w);
  86564. this.controlRot = true;
  86565. },
  86566. setRotation: function (rot) {
  86567. this.newOrientation = this.rotationVectToQuad(rot);
  86568. this.controlRot = true;
  86569. },
  86570. //---------------------------------------------
  86571. // RESET DYNAMIQUE POSITION AND ROTATION
  86572. //---------------------------------------------
  86573. resetPosition: function (x, y, z) {
  86574. this.linearVelocity.set(0, 0, 0);
  86575. this.angularVelocity.set(0, 0, 0);
  86576. this.position.set(x, y, z).multiplyScalar(OIMO.INV_SCALE);
  86577. //this.position.set( x*OIMO.INV_SCALE, y*OIMO.INV_SCALE, z*OIMO.INV_SCALE );
  86578. this.awake();
  86579. },
  86580. resetQuaternion: function (q) {
  86581. this.angularVelocity.set(0, 0, 0);
  86582. this.orientation = new OIMO.Quat(q.w, q.x, q.y, q.z);
  86583. this.awake();
  86584. },
  86585. resetRotation: function (x, y, z) {
  86586. this.angularVelocity.set(0, 0, 0);
  86587. this.orientation = this.rotationVectToQuad(new OIMO.Vec3(x, y, z));
  86588. this.awake();
  86589. },
  86590. //---------------------------------------------
  86591. // GET POSITION AND ROTATION
  86592. //---------------------------------------------
  86593. getPosition: function () {
  86594. return new OIMO.Vec3().scale(this.position, OIMO.WORLD_SCALE);
  86595. },
  86596. getRotation: function () {
  86597. return new OIMO.Euler().setFromRotationMatrix(this.rotation);
  86598. },
  86599. getQuaternion: function () {
  86600. return new OIMO.Quaternion().setFromRotationMatrix(this.rotation);
  86601. },
  86602. getMatrix: function () {
  86603. var m = this.matrix.elements;
  86604. var r, p;
  86605. if (!this.sleeping) {
  86606. // rotation matrix
  86607. r = this.rotation.elements;
  86608. m[0] = r[0]; m[1] = r[3]; m[2] = r[6]; m[3] = 0;
  86609. m[4] = r[1]; m[5] = r[4]; m[6] = r[7]; m[7] = 0;
  86610. m[8] = r[2]; m[9] = r[5]; m[10] = r[8]; m[11] = 0;
  86611. // position matrix
  86612. p = this.position;
  86613. m[12] = p.x * OIMO.WORLD_SCALE;
  86614. m[13] = p.y * OIMO.WORLD_SCALE;
  86615. m[14] = p.z * OIMO.WORLD_SCALE;
  86616. // sleep or not ?
  86617. m[15] = 0;
  86618. } else {
  86619. m[15] = 1;
  86620. }
  86621. return m;
  86622. }
  86623. };
  86624. /**
  86625. * The main class of body.
  86626. * is for simplify creation process and data access of rigidRody
  86627. * Rigid body has the shape of a single or multiple collision processing,
  86628. * all setting in object
  86629. *
  86630. * @author loth
  86631. */
  86632. OIMO.Body = function (Obj) {
  86633. var obj = Obj || {};
  86634. if (!obj.world) return;
  86635. if (obj.type === undefined) obj.type = "box";
  86636. this.name = obj.name || '';
  86637. // obsolete use world.add(obj)
  86638. this.body = obj.world.add(obj);
  86639. /*
  86640. // the world where i am
  86641. this.parent = obj.world;
  86642. // Yep my name
  86643. this.name = obj.name || '';
  86644. // I'm dynamique or not
  86645. var move = obj.move || false;
  86646. // I can sleep or not
  86647. var noSleep = obj.noSleep || false;
  86648. // My start position
  86649. var p = obj.pos || [0,0,0];
  86650. p = p.map(function(x) { return x * OIMO.INV_SCALE; });
  86651. // My size
  86652. var s = obj.size || [1,1,1];
  86653. s = s.map(function(x) { return x * OIMO.INV_SCALE; });
  86654. // My rotation in degre
  86655. var rot = obj.rot || [0,0,0];
  86656. rot = rot.map(function(x) { return x * OIMO.TO_RAD; });
  86657. var r = [];
  86658. for (var i=0; i<rot.length/3; i++){
  86659. var tmp = OIMO.EulerToAxis(rot[i+0], rot[i+1], rot[i+2]);
  86660. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  86661. }
  86662. // My physics setting
  86663. var sc = obj.sc || new OIMO.ShapeConfig();
  86664. if(obj.config){
  86665. // The density of the shape.
  86666. sc.density = obj.config[0] || 1;
  86667. // The coefficient of friction of the shape.
  86668. sc.friction = obj.config[1] || 0.4;
  86669. // The coefficient of restitution of the shape.
  86670. sc.restitution = obj.config[2] || 0.2;
  86671. // The bits of the collision groups to which the shape belongs.
  86672. sc.belongsTo = obj.config[3] || 1;
  86673. // The bits of the collision groups with which the shape collides.
  86674. sc.collidesWith = obj.config[4] || 0xffffffff;
  86675. }
  86676. if(obj.massPos){
  86677. obj.massPos = obj.massPos.map(function(x) { return x * OIMO.INV_SCALE; });
  86678. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  86679. }
  86680. if(obj.massRot){
  86681. obj.massRot = obj.massRot.map(function(x) { return x * OIMO.TO_RAD; });
  86682. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  86683. }
  86684. // My rigidbody
  86685. this.body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  86686. // My shapes
  86687. var shapes = [];
  86688. var type = obj.type || "box";
  86689. if( typeof type === 'string' ) type = [type];// single shape
  86690. var n, n2;
  86691. for(var i=0; i<type.length; i++){
  86692. n = i*3;
  86693. n2 = i*4;
  86694. switch(type[i]){
  86695. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n+0]); break;
  86696. case "cylinder": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break; // fake cylinder
  86697. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break;
  86698. }
  86699. this.body.addShape(shapes[i]);
  86700. if(i>0){
  86701. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  86702. shapes[i].relativePosition = new OIMO.Vec3( p[n+0], p[n+1], p[n+2] );
  86703. if(r[n2+0]) shapes[i].relativeRotation = [ r[n2+0], r[n2+1], r[n2+2], r[n2+3] ];
  86704. }
  86705. }
  86706. // I'm static or i move
  86707. if(move){
  86708. if(obj.massPos || obj.massRot)this.body.setupMass(0x1, false);
  86709. else this.body.setupMass(0x1, true);
  86710. if(noSleep) this.body.allowSleep = false;
  86711. else this.body.allowSleep = true;
  86712. } else {
  86713. this.body.setupMass(0x2);
  86714. }
  86715. this.body.name = this.name;
  86716. this.sleeping = this.body.sleeping;
  86717. // finaly add to physics world
  86718. this.parent.addRigidBody(this.body);*/
  86719. }
  86720. OIMO.Body.prototype = {
  86721. constructor: OIMO.Body,
  86722. // SET
  86723. setPosition: function (pos) {
  86724. this.body.setPosition(pos);
  86725. },
  86726. setQuaternion: function (q) {
  86727. this.body.setQuaternion(q);
  86728. },
  86729. setRotation: function (rot) {
  86730. this.body.setRotation(rot);
  86731. },
  86732. // GET
  86733. getPosition: function () {
  86734. return this.body.getPosition();
  86735. },
  86736. getRotation: function () {
  86737. return this.body.getRotation();
  86738. },
  86739. getQuaternion: function () {
  86740. return this.body.getQuaternion();
  86741. },
  86742. getMatrix: function () {
  86743. return this.body.getMatrix();
  86744. },
  86745. getSleep: function () {
  86746. return this.body.sleeping;
  86747. },
  86748. // RESET
  86749. resetPosition: function (x, y, z) {
  86750. this.body.resetPosition(x, y, z);
  86751. },
  86752. resetRotation: function (x, y, z) {
  86753. this.body.resetRotation(x, y, z);
  86754. },
  86755. // force wakeup
  86756. awake: function () {
  86757. this.body.awake();
  86758. },
  86759. // remove rigidbody
  86760. remove: function () {
  86761. this.body.dispose();
  86762. //this.parent.removeRigidBody(this.body);
  86763. },
  86764. // test if this object hit another
  86765. checkContact: function (name) {
  86766. this.body.checkContact(name);
  86767. //this.parent.checkContact(this.name, name);
  86768. }
  86769. }
  86770. /**
  86771. * The main class of link.
  86772. * is for simplify creation process and data access of Joint
  86773. * all setting in object
  86774. *
  86775. * @author loth
  86776. */
  86777. OIMO.Link = function (Obj) {
  86778. var obj = Obj || {};
  86779. if (!obj.world) return;
  86780. if (obj.type === undefined) obj.type = "jointHinge";
  86781. this.name = obj.name || '';
  86782. // obsolete use world.add(obj)
  86783. this.joint = obj.world.add(obj);
  86784. // the world where i am
  86785. /*this.parent = obj.world;
  86786. this.name = obj.name || '';
  86787. var type = obj.type || "jointHinge";
  86788. var axe1 = obj.axe1 || [1,0,0];
  86789. var axe2 = obj.axe2 || [1,0,0];
  86790. var pos1 = obj.pos1 || [0,0,0];
  86791. var pos2 = obj.pos2 || [0,0,0];
  86792. pos1 = pos1.map(function(x){ return x * OIMO.INV_SCALE; });
  86793. pos2 = pos2.map(function(x){ return x * OIMO.INV_SCALE; });
  86794. var min, max;
  86795. if(type==="jointDistance"){
  86796. min = obj.min || 0;
  86797. max = obj.max || 10;
  86798. min = min*OIMO.INV_SCALE;
  86799. max = max*OIMO.INV_SCALE;
  86800. }else{
  86801. min = obj.min || 57.29578;
  86802. max = obj.max || 0;
  86803. min = min*OIMO.TO_RAD;
  86804. max = max*OIMO.TO_RAD;
  86805. }
  86806. var limit = obj.limit || null;
  86807. var spring = obj.spring || null;
  86808. var motor = obj.motor || null;
  86809. // joint setting
  86810. var jc = new OIMO.JointConfig();
  86811. jc.allowCollision = obj.collision || false;;
  86812. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  86813. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  86814. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  86815. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  86816. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = obj.world.getByName(obj.body1);
  86817. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = obj.world.getByName(obj.body2);
  86818. jc.body1 = obj.body1;
  86819. jc.body2 = obj.body2;
  86820. switch(type){
  86821. case "jointDistance": this.joint = new OIMO.DistanceJoint(jc, min, max);
  86822. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);
  86823. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  86824. break;
  86825. case "jointHinge": this.joint = new OIMO.HingeJoint(jc, min, max);
  86826. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  86827. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  86828. break;
  86829. case "jointPrisme": this.joint = new OIMO.PrismaticJoint(jc, min, max); break;
  86830. case "jointSlide": this.joint = new OIMO.SliderJoint(jc, min, max); break;
  86831. case "jointBall": this.joint = new OIMO.BallAndSocketJoint(jc); break;
  86832. case "jointWheel": this.joint = new OIMO.WheelJoint(jc);
  86833. if(limit !== null) this.joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  86834. if(spring !== null) this.joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  86835. if(motor !== null) this.joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  86836. break;
  86837. }
  86838. this.joint.name = this.name;
  86839. // finaly add to physics world
  86840. this.parent.addJoint(this.joint);*/
  86841. }
  86842. OIMO.Link.prototype = {
  86843. constructor: OIMO.Link,
  86844. getPosition: function () {
  86845. // array of two vect3 [point1, point2]
  86846. return this.joint.getPosition();
  86847. },
  86848. getMatrix: function () {
  86849. return this.joint.getMatrix();
  86850. },
  86851. // remove joint
  86852. remove: function () {
  86853. this.joint.dispose();
  86854. //this.parent.removeJoint(this.joint);
  86855. },
  86856. // force wakeup linked body
  86857. awake: function () {
  86858. this.joint.awake();
  86859. }
  86860. }
  86861. /**
  86862. * The Dictionary class for testing
  86863. * @author lo-th
  86864. */
  86865. OIMO.Dictionary = function () {
  86866. this.data = {};
  86867. this.keys = [];
  86868. };
  86869. OIMO.Dictionary.prototype = {
  86870. constructor: OIMO.Dictionary,
  86871. set: function (value) {
  86872. var key = value.id;
  86873. if (!this.get[key]) this.keys.push(key);
  86874. this.data[key] = value;
  86875. },
  86876. get: function (id) {
  86877. return this.data[id];
  86878. },
  86879. del: function (value) {
  86880. var k = this.keys;
  86881. var n = k.indexOf(value.id);
  86882. if (n > -1) {
  86883. delete this.data[k[n]];
  86884. k.splice(n, 1);
  86885. }
  86886. },
  86887. reset: function () {
  86888. var data = this.data, keys = this.keys, key;
  86889. while (keys.length > 0) {
  86890. key = keys.pop();
  86891. delete data[key];
  86892. }
  86893. }
  86894. };
  86895. OIMO.Performance = function (world) {
  86896. this.parent = world;
  86897. this.infos = new OIMO_ARRAY_TYPE(13);
  86898. this.f = [0, 0, 0];
  86899. this.types = ['None', 'BruteForce', 'Sweep & Prune', 'Bounding Volume Tree'];
  86900. this.broadPhase = this.types[this.parent.broadPhase.types];
  86901. this.version = OIMO.REVISION;
  86902. this.fps = 0;
  86903. this.broadPhaseTime = 0;
  86904. this.narrowPhaseTime = 0;
  86905. this.solvingTime = 0;
  86906. //this.updatingTime = 0;
  86907. this.totalTime = 0;
  86908. };
  86909. OIMO.Performance.prototype = {
  86910. upfps: function () {
  86911. this.f[1] = Date.now();
  86912. 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]++;
  86913. },
  86914. updatingTime: function () {
  86915. return OIMO.fix(this.totalTime - (this.broadPhaseTime + this.narrowPhaseTime + this.solvingTime));
  86916. },
  86917. show: function () {
  86918. var info = [
  86919. "Oimo.js " + this.version + "<br>",
  86920. this.broadPhase + "<br><br>",
  86921. "FPS: " + this.fps + " fps<br><br>",
  86922. "rigidbody " + this.parent.numRigidBodies + "<br>",
  86923. "contact &nbsp;&nbsp;" + this.parent.numContacts + "<br>",
  86924. "ct-point &nbsp;" + this.parent.numContactPoints + "<br>",
  86925. "paircheck " + this.parent.broadPhase.numPairChecks + "<br>",
  86926. "island &nbsp;&nbsp;&nbsp;" + this.parent.numIslands + "<br><br>",
  86927. "Time in milliseconde<br><br>",
  86928. "broad-phase &nbsp;" + OIMO.fix(this.broadPhaseTime) + "<br>",
  86929. "narrow-phase " + OIMO.fix(this.narrowPhaseTime) + "<br>",
  86930. "solving &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.solvingTime) + "<br>",
  86931. "total &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.totalTime) + "<br>",
  86932. "updating &nbsp;&nbsp;&nbsp;&nbsp;" + this.updatingTime() + "<br>"
  86933. ].join("\n");
  86934. return info;
  86935. },
  86936. toArray: function () {
  86937. this.infos[0] = this.parent.broadPhase.types;
  86938. this.infos[1] = this.parent.numRigidBodies;
  86939. this.infos[2] = this.parent.numContacts;
  86940. this.infos[3] = this.parent.broadPhase.numPairChecks;
  86941. this.infos[4] = this.parent.numContactPoints;
  86942. this.infos[5] = this.parent.numIslands;
  86943. this.infos[6] = this.broadPhaseTime;
  86944. this.infos[7] = this.narrowPhaseTime;
  86945. this.infos[8] = this.solvingTime;
  86946. this.infos[9] = this.updatingTime();
  86947. this.infos[10] = this.totalTime;
  86948. this.infos[11] = this.fps;
  86949. return this.infos;
  86950. }
  86951. };
  86952. OIMO.Mat44 = function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  86953. this.elements = new OIMO_ARRAY_TYPE(16);
  86954. var te = this.elements;
  86955. te[0] = (n11 !== undefined) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  86956. te[1] = n21 || 0; te[5] = (n22 !== undefined) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  86957. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = (n33 !== undefined) ? n33 : 1; te[14] = n34 || 0;
  86958. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = (n44 !== undefined) ? n44 : 1;
  86959. };
  86960. OIMO.Mat44.prototype = {
  86961. constructor: OIMO.Mat44,
  86962. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  86963. var te = this.elements;
  86964. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  86965. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  86966. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  86967. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  86968. return this;
  86969. }/*,
  86970. extractRotation: function () {
  86971. var v1 = new THREE.Vector3();
  86972. return function ( m ) {
  86973. var te = this.elements;
  86974. var me = m.elements;
  86975. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  86976. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  86977. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  86978. te[ 0 ] = me[ 0 ] * scaleX;
  86979. te[ 1 ] = me[ 1 ] * scaleX;
  86980. te[ 2 ] = me[ 2 ] * scaleX;
  86981. te[ 4 ] = me[ 4 ] * scaleY;
  86982. te[ 5 ] = me[ 5 ] * scaleY;
  86983. te[ 6 ] = me[ 6 ] * scaleY;
  86984. te[ 8 ] = me[ 8 ] * scaleZ;
  86985. te[ 9 ] = me[ 9 ] * scaleZ;
  86986. te[ 10 ] = me[ 10 ] * scaleZ;
  86987. return this;
  86988. };
  86989. }() */
  86990. }
  86991. OIMO.Mat33 = function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  86992. this.elements = new OIMO_ARRAY_TYPE(9);
  86993. var te = this.elements;
  86994. this.init(
  86995. (e00 !== undefined) ? e00 : 1, e01 || 0, e02 || 0,
  86996. e10 || 0, (e11 !== undefined) ? e11 : 1, e12 || 0,
  86997. e20 || 0, e21 || 0, (e22 !== undefined) ? e22 : 1
  86998. );
  86999. };
  87000. OIMO.Mat33.prototype = {
  87001. constructor: OIMO.Mat33,
  87002. set: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  87003. var te = this.elements;
  87004. te[0] = e00; te[1] = e01; te[2] = e02;
  87005. te[3] = e10; te[4] = e11; te[5] = e12;
  87006. te[6] = e20; te[7] = e21; te[8] = e22;
  87007. return this;
  87008. },
  87009. init: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  87010. var te = this.elements;
  87011. te[0] = e00; te[1] = e01; te[2] = e02;
  87012. te[3] = e10; te[4] = e11; te[5] = e12;
  87013. te[6] = e20; te[7] = e21; te[8] = e22;
  87014. return this;
  87015. },
  87016. multiply: function (s) {
  87017. var te = this.elements;
  87018. te[0] *= s; te[1] *= s; te[2] *= s;
  87019. te[3] *= s; te[4] *= s; te[5] *= s;
  87020. te[6] *= s; te[7] *= s; te[8] *= s;
  87021. return this;
  87022. },
  87023. add: function (m1, m2) {
  87024. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  87025. te[0] = tem1[0] + tem2[0]; te[1] = tem1[1] + tem2[1]; te[2] = tem1[2] + tem2[2];
  87026. te[3] = tem1[3] + tem2[3]; te[4] = tem1[4] + tem2[4]; te[5] = tem1[5] + tem2[5];
  87027. te[6] = tem1[6] + tem2[6]; te[7] = tem1[7] + tem2[7]; te[8] = tem1[8] + tem2[8];
  87028. return this;
  87029. },
  87030. addEqual: function (m) {
  87031. var te = this.elements, tem = m.elements;
  87032. te[0] += tem[0]; te[1] += tem[1]; te[2] += tem[2];
  87033. te[3] += tem[3]; te[4] += tem[4]; te[5] += tem[5];
  87034. te[6] += tem[6]; te[7] += tem[7]; te[8] += tem[8];
  87035. return this;
  87036. },
  87037. sub: function (m1, m2) {
  87038. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  87039. te[0] = tem1[0] - tem2[0]; te[1] = tem1[1] - tem2[1]; te[2] = tem1[2] - tem2[2];
  87040. te[3] = tem1[3] - tem2[3]; te[4] = tem1[4] - tem2[4]; te[5] = tem1[5] - tem2[5];
  87041. te[6] = tem1[6] - tem2[6]; te[7] = tem1[7] - tem2[7]; te[8] = tem1[8] - tem2[8];
  87042. return this;
  87043. },
  87044. subEqual: function (m) {
  87045. var te = this.elements, tem = m.elements;
  87046. te[0] -= tem[0]; te[1] -= tem[1]; te[2] -= tem[2];
  87047. te[3] -= tem[3]; te[4] -= tem[4]; te[5] -= tem[5];
  87048. te[6] -= tem[6]; te[7] -= tem[7]; te[8] -= tem[8];
  87049. return this;
  87050. },
  87051. scale: function (m, s) {
  87052. var te = this.elements, tm = m.elements;
  87053. te[0] = tm[0] * s; te[1] = tm[1] * s; te[2] = tm[2] * s;
  87054. te[3] = tm[3] * s; te[4] = tm[4] * s; te[5] = tm[5] * s;
  87055. te[6] = tm[6] * s; te[7] = tm[7] * s; te[8] = tm[8] * s;
  87056. return this;
  87057. },
  87058. scaleEqual: function (s) {
  87059. var te = this.elements;
  87060. te[0] *= s; te[1] *= s; te[2] *= s;
  87061. te[3] *= s; te[4] *= s; te[5] *= s;
  87062. te[6] *= s; te[7] *= s; te[8] *= s;
  87063. return this;
  87064. },
  87065. mul: function (m1, m2) {
  87066. var te = this.elements, tm1 = m1.elements, tm2 = m2.elements,
  87067. a0 = tm1[0], a3 = tm1[3], a6 = tm1[6],
  87068. a1 = tm1[1], a4 = tm1[4], a7 = tm1[7],
  87069. a2 = tm1[2], a5 = tm1[5], a8 = tm1[8],
  87070. b0 = tm2[0], b3 = tm2[3], b6 = tm2[6],
  87071. b1 = tm2[1], b4 = tm2[4], b7 = tm2[7],
  87072. b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  87073. te[0] = a0 * b0 + a1 * b3 + a2 * b6;
  87074. te[1] = a0 * b1 + a1 * b4 + a2 * b7;
  87075. te[2] = a0 * b2 + a1 * b5 + a2 * b8;
  87076. te[3] = a3 * b0 + a4 * b3 + a5 * b6;
  87077. te[4] = a3 * b1 + a4 * b4 + a5 * b7;
  87078. te[5] = a3 * b2 + a4 * b5 + a5 * b8;
  87079. te[6] = a6 * b0 + a7 * b3 + a8 * b6;
  87080. te[7] = a6 * b1 + a7 * b4 + a8 * b7;
  87081. te[8] = a6 * b2 + a7 * b5 + a8 * b8;
  87082. return this;
  87083. },
  87084. mulScale: function (m, sx, sy, sz, Prepend) {
  87085. var prepend = Prepend || false;
  87086. var te = this.elements, tm = m.elements;
  87087. if (prepend) {
  87088. te[0] = sx * tm[0]; te[1] = sx * tm[1]; te[2] = sx * tm[2];
  87089. te[3] = sy * tm[3]; te[4] = sy * tm[4]; te[5] = sy * tm[5];
  87090. te[6] = sz * tm[6]; te[7] = sz * tm[7]; te[8] = sz * tm[8];
  87091. } else {
  87092. te[0] = tm[0] * sx; te[1] = tm[1] * sy; te[2] = tm[2] * sz;
  87093. te[3] = tm[3] * sx; te[4] = tm[4] * sy; te[5] = tm[5] * sz;
  87094. te[6] = tm[6] * sx; te[7] = tm[7] * sy; te[8] = tm[8] * sz;
  87095. }
  87096. return this;
  87097. },
  87098. mulRotate: function (m, rad, ax, ay, az, Prepend) {
  87099. var prepend = Prepend || false;
  87100. var s = OIMO.sin(rad);
  87101. var c = OIMO.cos(rad);
  87102. var c1 = 1 - c;
  87103. var r00 = ax * ax * c1 + c;
  87104. var r01 = ax * ay * c1 - az * s;
  87105. var r02 = ax * az * c1 + ay * s;
  87106. var r10 = ay * ax * c1 + az * s;
  87107. var r11 = ay * ay * c1 + c;
  87108. var r12 = ay * az * c1 - ax * s;
  87109. var r20 = az * ax * c1 - ay * s;
  87110. var r21 = az * ay * c1 + ax * s;
  87111. var r22 = az * az * c1 + c;
  87112. var tm = m.elements;
  87113. var a0 = tm[0], a3 = tm[3], a6 = tm[6];
  87114. var a1 = tm[1], a4 = tm[4], a7 = tm[7];
  87115. var a2 = tm[2], a5 = tm[5], a8 = tm[8];
  87116. var te = this.elements;
  87117. if (prepend) {
  87118. te[0] = r00 * a0 + r01 * a3 + r02 * a6;
  87119. te[1] = r00 * a1 + r01 * a4 + r02 * a7;
  87120. te[2] = r00 * a2 + r01 * a5 + r02 * a8;
  87121. te[3] = r10 * a0 + r11 * a3 + r12 * a6;
  87122. te[4] = r10 * a1 + r11 * a4 + r12 * a7;
  87123. te[5] = r10 * a2 + r11 * a5 + r12 * a8;
  87124. te[6] = r20 * a0 + r21 * a3 + r22 * a6;
  87125. te[7] = r20 * a1 + r21 * a4 + r22 * a7;
  87126. te[8] = r20 * a2 + r21 * a5 + r22 * a8;
  87127. } else {
  87128. te[0] = a0 * r00 + a1 * r10 + a2 * r20;
  87129. te[1] = a0 * r01 + a1 * r11 + a2 * r21;
  87130. te[2] = a0 * r02 + a1 * r12 + a2 * r22;
  87131. te[3] = a3 * r00 + a4 * r10 + a5 * r20;
  87132. te[4] = a3 * r01 + a4 * r11 + a5 * r21;
  87133. te[5] = a3 * r02 + a4 * r12 + a5 * r22;
  87134. te[6] = a6 * r00 + a7 * r10 + a8 * r20;
  87135. te[7] = a6 * r01 + a7 * r11 + a8 * r21;
  87136. te[8] = a6 * r02 + a7 * r12 + a8 * r22;
  87137. }
  87138. return this;
  87139. },
  87140. transpose: function (m) {
  87141. var te = this.elements, tm = m.elements;
  87142. te[0] = tm[0]; te[1] = tm[3]; te[2] = tm[6];
  87143. te[3] = tm[1]; te[4] = tm[4]; te[5] = tm[7];
  87144. te[6] = tm[2]; te[7] = tm[5]; te[8] = tm[8];
  87145. return this;
  87146. },
  87147. setQuat: function (q) {
  87148. var te = this.elements,
  87149. x2 = 2 * q.x, y2 = 2 * q.y, z2 = 2 * q.z,
  87150. xx = q.x * x2, yy = q.y * y2, zz = q.z * z2,
  87151. xy = q.x * y2, yz = q.y * z2, xz = q.x * z2,
  87152. sx = q.s * x2, sy = q.s * y2, sz = q.s * z2;
  87153. te[0] = 1 - yy - zz;
  87154. te[1] = xy - sz;
  87155. te[2] = xz + sy;
  87156. te[3] = xy + sz;
  87157. te[4] = 1 - xx - zz;
  87158. te[5] = yz - sx;
  87159. te[6] = xz - sy;
  87160. te[7] = yz + sx;
  87161. te[8] = 1 - xx - yy;
  87162. return this;
  87163. },
  87164. invert: function (m) {
  87165. var te = this.elements, tm = m.elements,
  87166. a0 = tm[0], a3 = tm[3], a6 = tm[6],
  87167. a1 = tm[1], a4 = tm[4], a7 = tm[7],
  87168. a2 = tm[2], a5 = tm[5], a8 = tm[8],
  87169. b01 = a4 * a8 - a7 * a5,
  87170. b11 = a7 * a2 - a1 * a8,
  87171. b21 = a1 * a5 - a4 * a2,
  87172. dt = a0 * (b01) + a3 * (b11) + a6 * (b21);
  87173. if (dt != 0) { dt = 1.0 / dt; }
  87174. te[0] = dt * b01;//(a4*a8 - a5*a7);
  87175. te[1] = dt * b11;//(a2*a7 - a1*a8);
  87176. te[2] = dt * b21;//(a1*a5 - a2*a4);
  87177. te[3] = dt * (a5 * a6 - a3 * a8);
  87178. te[4] = dt * (a0 * a8 - a2 * a6);
  87179. te[5] = dt * (a2 * a3 - a0 * a5);
  87180. te[6] = dt * (a3 * a7 - a4 * a6);
  87181. te[7] = dt * (a1 * a6 - a0 * a7);
  87182. te[8] = dt * (a0 * a4 - a1 * a3);
  87183. return this;
  87184. },
  87185. /*copy: function(m){
  87186. var te = this.elements, tem = m.elements;
  87187. te[0] = tem[0]; te[1] = tem[1]; te[2] = tem[2];
  87188. te[3] = tem[3]; te[4] = tem[4]; te[5] = tem[5];
  87189. te[6] = tem[6]; te[7] = tem[7]; te[8] = tem[8];
  87190. return this;
  87191. },*/
  87192. toEuler: function () { // not work !!
  87193. function clamp(x) {
  87194. return OIMO.min(OIMO.max(x, -1), 1);
  87195. }
  87196. var te = this.elements;
  87197. var m11 = te[0], m12 = te[3], m13 = te[6];
  87198. var m21 = te[1], m22 = te[4], m23 = te[7];
  87199. var m31 = te[2], m32 = te[5], m33 = te[8];
  87200. var p = new OIMO.Vec3();
  87201. var d = new OIMO.Quat();
  87202. var s;
  87203. p.y = OIMO.asin(clamp(m13));
  87204. if (OIMO.abs(m13) < 0.99999) {
  87205. p.x = OIMO.atan2(-m23, m33);
  87206. p.z = OIMO.atan2(-m12, m11);
  87207. } else {
  87208. p.x = OIMO.atan2(m32, m22);
  87209. p.z = 0;
  87210. }
  87211. return p;
  87212. },
  87213. /*clone: function(){
  87214. var te = this.elements;
  87215. return new OIMO.Mat33(
  87216. te[0], te[1], te[2],
  87217. te[3], te[4], te[5],
  87218. te[6], te[7], te[8]
  87219. );
  87220. },*/
  87221. toString: function () {
  87222. var te = this.elements;
  87223. var text =
  87224. "Mat33|" + te[0].toFixed(4) + ", " + te[1].toFixed(4) + ", " + te[2].toFixed(4) + "|\n" +
  87225. " |" + te[3].toFixed(4) + ", " + te[4].toFixed(4) + ", " + te[5].toFixed(4) + "|\n" +
  87226. " |" + te[6].toFixed(4) + ", " + te[7].toFixed(4) + ", " + te[8].toFixed(4) + "|";
  87227. return text;
  87228. },
  87229. // OK
  87230. multiplyScalar: function (s) {
  87231. var te = this.elements;
  87232. te[0] *= s; te[3] *= s; te[6] *= s;
  87233. te[1] *= s; te[4] *= s; te[7] *= s;
  87234. te[2] *= s; te[5] *= s; te[8] *= s;
  87235. return this;
  87236. },
  87237. identity: function () {
  87238. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  87239. return this;
  87240. },
  87241. clone: function () {
  87242. return new this.constructor().fromArray(this.elements);
  87243. },
  87244. copy: function (m) {
  87245. var me = m.elements;
  87246. this.set(
  87247. me[0], me[3], me[6],
  87248. me[1], me[4], me[7],
  87249. me[2], me[5], me[8]
  87250. );
  87251. return this;
  87252. },
  87253. fromArray: function (array) {
  87254. this.elements.set(array);
  87255. return this;
  87256. },
  87257. toArray: function () {
  87258. var te = this.elements;
  87259. return [
  87260. te[0], te[1], te[2],
  87261. te[3], te[4], te[5],
  87262. te[6], te[7], te[8]
  87263. ];
  87264. }
  87265. };
  87266. OIMO.Quat = function (s, x, y, z) {
  87267. this.s = (s !== undefined) ? s : 1;
  87268. this.x = x || 0;
  87269. this.y = y || 0;
  87270. this.z = z || 0;
  87271. };
  87272. OIMO.Quat.prototype = {
  87273. constructor: OIMO.Quat,
  87274. set: function (x, y, z, w) {
  87275. this.x = x;
  87276. this.y = y;
  87277. this.z = z;
  87278. this.s = w;
  87279. return this;
  87280. },
  87281. init: function (s, x, y, z) {
  87282. this.s = (s !== undefined) ? s : 1;
  87283. this.x = x || 0;
  87284. this.y = y || 0;
  87285. this.z = z || 0;
  87286. return this;
  87287. },
  87288. add: function (q1, q2) {
  87289. this.s = q1.s + q2.s;
  87290. this.x = q1.x + q2.x;
  87291. this.y = q1.y + q2.y;
  87292. this.z = q1.z + q2.z;
  87293. return this;
  87294. },
  87295. addTime: function (v, t) {
  87296. var x = v.x;
  87297. var y = v.y;
  87298. var z = v.z;
  87299. var qs = this.s;
  87300. var qx = this.x;
  87301. var qy = this.y;
  87302. var qz = this.z;
  87303. t *= 0.5;
  87304. var ns = (-x * qx - y * qy - z * qz) * t;
  87305. var nx = (x * qs + y * qz - z * qy) * t;
  87306. var ny = (-x * qz + y * qs + z * qx) * t;
  87307. var nz = (x * qy - y * qx + z * qs) * t;
  87308. qs += ns;
  87309. qx += nx;
  87310. qy += ny;
  87311. qz += nz;
  87312. var s = 1 / OIMO.sqrt(qs * qs + qx * qx + qy * qy + qz * qz);
  87313. this.s = qs * s;
  87314. this.x = qx * s;
  87315. this.y = qy * s;
  87316. this.z = qz * s;
  87317. return this;
  87318. },
  87319. sub: function (q1, q2) {
  87320. this.s = q1.s - q2.s;
  87321. this.x = q1.x - q2.x;
  87322. this.y = q1.y - q2.y;
  87323. this.z = q1.z - q2.z;
  87324. return this;
  87325. },
  87326. scale: function (q, s) {
  87327. this.s = q.s * s;
  87328. this.x = q.x * s;
  87329. this.y = q.y * s;
  87330. this.z = q.z * s;
  87331. return this;
  87332. },
  87333. mul: function (q1, q2) {
  87334. var ax = q1.x, ay = q1.y, az = q1.z, as = q1.s,
  87335. bx = q2.x, by = q2.y, bz = q2.z, bs = q2.s;
  87336. this.x = ax * bs + as * bx + ay * bz - az * by;
  87337. this.y = ay * bs + as * by + az * bx - ax * bz;
  87338. this.z = az * bs + as * bz + ax * by - ay * bx;
  87339. this.s = as * bs - ax * bx - ay * by - az * bz;
  87340. return this;
  87341. },
  87342. arc: function (v1, v2) {
  87343. var x1 = v1.x;
  87344. var y1 = v1.y;
  87345. var z1 = v1.z;
  87346. var x2 = v2.x;
  87347. var y2 = v2.y;
  87348. var z2 = v2.z;
  87349. var d = x1 * x2 + y1 * y2 + z1 * z2;
  87350. if (d == -1) {
  87351. x2 = y1 * x1 - z1 * z1;
  87352. y2 = -z1 * y1 - x1 * x1;
  87353. z2 = x1 * z1 + y1 * y1;
  87354. d = 1 / OIMO.sqrt(x2 * x2 + y2 * y2 + z2 * z2);
  87355. this.s = 0;
  87356. this.x = x2 * d;
  87357. this.y = y2 * d;
  87358. this.z = z2 * d;
  87359. return this;
  87360. }
  87361. var cx = y1 * z2 - z1 * y2;
  87362. var cy = z1 * x2 - x1 * z2;
  87363. var cz = x1 * y2 - y1 * x2;
  87364. this.s = OIMO.sqrt((1 + d) * 0.5);
  87365. d = 0.5 / this.s;
  87366. this.x = cx * d;
  87367. this.y = cy * d;
  87368. this.z = cz * d;
  87369. return this;
  87370. },
  87371. normalize: function (q) {
  87372. var len = OIMO.sqrt(q.s * q.s + q.x * q.x + q.y * q.y + q.z * q.z);
  87373. if (len > 0) { len = 1 / len; }
  87374. this.s = q.s * len;
  87375. this.x = q.x * len;
  87376. this.y = q.y * len;
  87377. this.z = q.z * len;
  87378. return this;
  87379. },
  87380. invert: function (q) {
  87381. this.s = q.s;
  87382. this.x = -q.x;
  87383. this.y = -q.y;
  87384. this.z = -q.z;
  87385. return this;
  87386. },
  87387. length: function () {
  87388. return OIMO.sqrt(this.s * this.s + this.x * this.x + this.y * this.y + this.z * this.z);
  87389. },
  87390. copy: function (q) {
  87391. this.s = q.s;
  87392. this.x = q.x;
  87393. this.y = q.y;
  87394. this.z = q.z;
  87395. return this;
  87396. },
  87397. testDiff: function (q) {
  87398. if (this.s !== q.s || this.x !== q.x || this.y !== q.y || this.z !== q.z) return true;
  87399. else return false;
  87400. },
  87401. clone: function (q) {
  87402. return new OIMO.Quat(this.s, this.x, this.y, this.z);
  87403. },
  87404. toString: function () {
  87405. return "Quat[" + this.s.toFixed(4) + ", (" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + ")]";
  87406. }
  87407. }
  87408. // for three easy export
  87409. OIMO.Quaternion = function (x, y, z, w) {
  87410. this.x = x || 0;
  87411. this.y = y || 0;
  87412. this.z = z || 0;
  87413. this.w = (w !== undefined) ? w : 1;
  87414. };
  87415. OIMO.Quaternion.prototype = {
  87416. constructor: OIMO.Quaternion,
  87417. setFromRotationMatrix: function (m) {
  87418. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  87419. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  87420. var te = m.elements,
  87421. m11 = te[0], m12 = te[1], m13 = te[2],
  87422. m21 = te[3], m22 = te[4], m23 = te[5],
  87423. m31 = te[6], m32 = te[7], m33 = te[8],
  87424. trace = m11 + m22 + m33,
  87425. s;
  87426. if (trace > 0) {
  87427. s = 0.5 / OIMO.sqrt(trace + 1.0);
  87428. this.w = 0.25 / s;
  87429. this.x = (m32 - m23) * s;
  87430. this.y = (m13 - m31) * s;
  87431. this.z = (m21 - m12) * s;
  87432. } else if (m11 > m22 && m11 > m33) {
  87433. s = 2.0 * OIMO.sqrt(1.0 + m11 - m22 - m33);
  87434. this.w = (m32 - m23) / s;
  87435. this.x = 0.25 * s;
  87436. this.y = (m12 + m21) / s;
  87437. this.z = (m13 + m31) / s;
  87438. } else if (m22 > m33) {
  87439. s = 2.0 * OIMO.sqrt(1.0 + m22 - m11 - m33);
  87440. this.w = (m13 - m31) / s;
  87441. this.x = (m12 + m21) / s;
  87442. this.y = 0.25 * s;
  87443. this.z = (m23 + m32) / s;
  87444. } else {
  87445. s = 2.0 * OIMO.sqrt(1.0 + m33 - m11 - m22);
  87446. this.w = (m21 - m12) / s;
  87447. this.x = (m13 + m31) / s;
  87448. this.y = (m23 + m32) / s;
  87449. this.z = 0.25 * s;
  87450. }
  87451. //this.onChangeCallback();
  87452. return this;
  87453. }
  87454. }
  87455. OIMO.Vec3 = function (x, y, z) {
  87456. this.x = x || 0;
  87457. this.y = y || 0;
  87458. this.z = z || 0;
  87459. };
  87460. OIMO.Vec3.prototype = {
  87461. constructor: OIMO.Vec3,
  87462. init: function (x, y, z) {
  87463. this.x = x || 0;
  87464. this.y = y || 0;
  87465. this.z = z || 0;
  87466. return this;
  87467. },
  87468. set: function (x, y, z) {
  87469. this.x = x;
  87470. this.y = y;
  87471. this.z = z;
  87472. return this;
  87473. },
  87474. add: function (v1, v2) {
  87475. this.x = v1.x + v2.x;
  87476. this.y = v1.y + v2.y;
  87477. this.z = v1.z + v2.z;
  87478. return this;
  87479. },
  87480. addEqual: function (v) {
  87481. this.x += v.x;
  87482. this.y += v.y;
  87483. this.z += v.z;
  87484. return this;
  87485. },
  87486. addTime: function (v, t) {
  87487. this.x += v.x * t;
  87488. this.y += v.y * t;
  87489. this.z += v.z * t;
  87490. return this;
  87491. },
  87492. sub: function (v1, v2) {
  87493. this.x = v1.x - v2.x;
  87494. this.y = v1.y - v2.y;
  87495. this.z = v1.z - v2.z;
  87496. return this;
  87497. },
  87498. subEqual: function (v) {
  87499. this.x -= v.x;
  87500. this.y -= v.y;
  87501. this.z -= v.z;
  87502. return this;
  87503. },
  87504. addScale: function (v, s) {
  87505. this.x += v.x * s;
  87506. this.y += v.y * s;
  87507. this.z += v.z * s;
  87508. return this;
  87509. },
  87510. scale: function (v, s) {
  87511. this.x = v.x * s;
  87512. this.y = v.y * s;
  87513. this.z = v.z * s;
  87514. return this;
  87515. },
  87516. scaleEqual: function (s) {
  87517. this.x *= s;
  87518. this.y *= s;
  87519. this.z *= s;
  87520. return this;
  87521. },
  87522. /*dot: function(v){
  87523. return this.x*v.x+this.y*v.y+this.z*v.z;
  87524. },*/
  87525. cross: function (v1, v2) {
  87526. var ax = v1.x, ay = v1.y, az = v1.z,
  87527. bx = v2.x, by = v2.y, bz = v2.z;
  87528. this.x = ay * bz - az * by;
  87529. this.y = az * bx - ax * bz;
  87530. this.z = ax * by - ay * bx;
  87531. return this;
  87532. },
  87533. mul: function (o, v, m) {
  87534. var te = m.elements;
  87535. this.x = o.x + v.x * te[0] + v.y * te[1] + v.z * te[2];
  87536. this.y = o.y + v.x * te[3] + v.y * te[4] + v.z * te[5];
  87537. this.z = o.z + v.x * te[6] + v.y * te[7] + v.z * te[8];
  87538. return this;
  87539. },
  87540. mulMat: function (m, v) {
  87541. var te = m.elements;
  87542. this.x = te[0] * v.x + te[1] * v.y + te[2] * v.z;
  87543. this.y = te[3] * v.x + te[4] * v.y + te[5] * v.z;
  87544. this.z = te[6] * v.x + te[7] * v.y + te[8] * v.z;
  87545. return this;
  87546. },
  87547. normalize: function (v) {
  87548. var x = v.x, y = v.y, z = v.z;
  87549. var l = x * x + y * y + z * z;
  87550. if (l > 0) {
  87551. l = 1 / OIMO.sqrt(l);
  87552. this.x = x * l;
  87553. this.y = y * l;
  87554. this.z = z * l;
  87555. }
  87556. return this;
  87557. },
  87558. /*norm: function(){
  87559. var x = this.x, y = this.y, z = this.z;
  87560. var l = x*x + y*y + z*z;
  87561. if (l > 0) {
  87562. l = 1 / OIMO.sqrt(l);
  87563. this.x = x*l;
  87564. this.y = y*l;
  87565. this.z = z*l;
  87566. }
  87567. return this;
  87568. },*/
  87569. invert: function (v) {
  87570. this.x = -v.x;
  87571. this.y = -v.y;
  87572. this.z = -v.z;
  87573. return this;
  87574. },
  87575. /*length: function(){
  87576. var x = this.x, y = this.y, z = this.z;
  87577. return OIMO.sqrt(x*x + y*y + z*z);
  87578. },*/
  87579. negate: function () {
  87580. this.x = -this.x;
  87581. this.y = -this.y;
  87582. this.z = -this.z;
  87583. return this;
  87584. },
  87585. dot: function (v) {
  87586. return this.x * v.x + this.y * v.y + this.z * v.z;
  87587. },
  87588. lengthSq: function () {
  87589. return this.x * this.x + this.y * this.y + this.z * this.z;
  87590. },
  87591. length: function () {
  87592. return OIMO.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  87593. },
  87594. /*len: function(){
  87595. var x = this.x, y = this.y, z = this.z;
  87596. return x*x + y*y + z*z;
  87597. },*/
  87598. copy: function (v) {
  87599. this.x = v.x;
  87600. this.y = v.y;
  87601. this.z = v.z;
  87602. return this;
  87603. },
  87604. applyQuaternion: function (q) {
  87605. var x = this.x;
  87606. var y = this.y;
  87607. var z = this.z;
  87608. var qx = q.x;
  87609. var qy = q.y;
  87610. var qz = q.z;
  87611. var qs = q.s;
  87612. // calculate quat * vector
  87613. var ix = qs * x + qy * z - qz * y;
  87614. var iy = qs * y + qz * x - qx * z;
  87615. var iz = qs * z + qx * y - qy * x;
  87616. var iw = -qx * x - qy * y - qz * z;
  87617. // calculate result * inverse quat
  87618. this.x = ix * qs + iw * -qx + iy * -qz - iz * -qy;
  87619. this.y = iy * qs + iw * -qy + iz * -qx - ix * -qz;
  87620. this.z = iz * qs + iw * -qz + ix * -qy - iy * -qx;
  87621. return this;
  87622. },
  87623. testZero: function () {
  87624. if (this.x !== 0 || this.y !== 0 || this.z !== 0) return true;
  87625. else return false;
  87626. },
  87627. testDiff: function (v) {
  87628. return ((v.x !== this.x) || (v.y !== this.y) || (v.z !== this.z));
  87629. //if(this.x!==v.x || this.y!==v.y || this.z!==v.z) return true;
  87630. //else return false;
  87631. },
  87632. equals: function (v) {
  87633. return ((v.x === this.x) && (v.y === this.y) && (v.z === this.z));
  87634. },
  87635. clone: function () {
  87636. return new this.constructor(this.x, this.y, this.z);
  87637. },
  87638. toString: function () {
  87639. return "Vec3[" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + "]";
  87640. },
  87641. multiplyScalar: function (scalar) {
  87642. if (isFinite(scalar)) {
  87643. this.x *= scalar;
  87644. this.y *= scalar;
  87645. this.z *= scalar;
  87646. } else {
  87647. this.x = 0;
  87648. this.y = 0;
  87649. this.z = 0;
  87650. }
  87651. return this;
  87652. },
  87653. divideScalar: function (scalar) {
  87654. return this.multiplyScalar(1 / scalar);
  87655. },
  87656. // TODO rename to normalize
  87657. norm: function () {
  87658. return this.divideScalar(this.length());
  87659. },
  87660. }
  87661. OIMO.Euler = function (x, y, z, order) {
  87662. this._x = x || 0;
  87663. this._y = y || 0;
  87664. this._z = z || 0;
  87665. this._order = order || OIMO.Euler.DefaultOrder;
  87666. };
  87667. OIMO.Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  87668. OIMO.Euler.DefaultOrder = 'XYZ';
  87669. OIMO.clamp = function (x, a, b) {
  87670. return (x < a) ? a : ((x > b) ? b : x);
  87671. }
  87672. OIMO.Euler.prototype = {
  87673. constructor: OIMO.Euler,
  87674. _x: 0, _y: 0, _z: 0, _order: OIMO.Euler.DefaultOrder,
  87675. get x() {
  87676. return this._x;
  87677. },
  87678. set x(value) {
  87679. this._x = value;
  87680. this.onChangeCallback();
  87681. },
  87682. get y() {
  87683. return this._y;
  87684. },
  87685. set y(value) {
  87686. this._y = value;
  87687. this.onChangeCallback();
  87688. },
  87689. get z() {
  87690. return this._z;
  87691. },
  87692. set z(value) {
  87693. this._z = value;
  87694. this.onChangeCallback();
  87695. },
  87696. get order() {
  87697. return this._order;
  87698. },
  87699. set order(value) {
  87700. this._order = value;
  87701. this.onChangeCallback();
  87702. },
  87703. set: function (x, y, z, order) {
  87704. this._x = x;
  87705. this._y = y;
  87706. this._z = z;
  87707. this._order = order || this._order;
  87708. this.onChangeCallback();
  87709. return this;
  87710. },
  87711. copy: function (euler) {
  87712. this._x = euler._x;
  87713. this._y = euler._y;
  87714. this._z = euler._z;
  87715. this._order = euler._order;
  87716. this.onChangeCallback();
  87717. return this;
  87718. },
  87719. setFromRotationMatrix: function (m, order) {
  87720. var clamp = OIMO.clamp;
  87721. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  87722. var te = m.elements;
  87723. /*var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  87724. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  87725. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];*/
  87726. var m11 = te[0], m12 = te[1], m13 = te[2],
  87727. m21 = te[3], m22 = te[4], m23 = te[5],
  87728. m31 = te[6], m32 = te[7], m33 = te[8];
  87729. order = order || this._order;
  87730. if (order === 'XYZ') {
  87731. this._y = OIMO.asin(clamp(m13, -1, 1));
  87732. if (OIMO.abs(m13) < 0.99999) {
  87733. this._x = OIMO.atan2(-m23, m33);
  87734. this._z = OIMO.atan2(-m12, m11);
  87735. } else {
  87736. this._x = OIMO.atan2(m32, m22);
  87737. this._z = 0;
  87738. }
  87739. } else if (order === 'YXZ') {
  87740. this._x = OIMO.asin(-clamp(m23, -1, 1));
  87741. if (OIMO.abs(m23) < 0.99999) {
  87742. this._y = OIMO.atan2(m13, m33);
  87743. this._z = OIMO.atan2(m21, m22);
  87744. } else {
  87745. this._y = OIMO.atan2(-m31, m11);
  87746. this._z = 0;
  87747. }
  87748. } else if (order === 'ZXY') {
  87749. this._x = OIMO.asin(clamp(m32, -1, 1));
  87750. if (OIMO.abs(m32) < 0.99999) {
  87751. this._y = OIMO.atan2(-m31, m33);
  87752. this._z = OIMO.atan2(-m12, m22);
  87753. } else {
  87754. this._y = 0;
  87755. this._z = OIMO.atan2(m21, m11);
  87756. }
  87757. } else if (order === 'ZYX') {
  87758. this._y = OIMO.asin(-clamp(m31, -1, 1));
  87759. if (OIMO.abs(m31) < 0.99999) {
  87760. this._x = OIMO.atan2(m32, m33);
  87761. this._z = OIMO.atan2(m21, m11);
  87762. } else {
  87763. this._x = 0;
  87764. this._z = OIMO.atan2(-m12, m22);
  87765. }
  87766. } else if (order === 'YZX') {
  87767. this._z = OIMO.asin(clamp(m21, -1, 1));
  87768. if (OIMO.abs(m21) < 0.99999) {
  87769. this._x = OIMO.atan2(-m23, m22);
  87770. this._y = OIMO.atan2(-m31, m11);
  87771. } else {
  87772. this._x = 0;
  87773. this._y = OIMO.atan2(m13, m33);
  87774. }
  87775. } else if (order === 'XZY') {
  87776. this._z = OIMO.asin(-clamp(m12, -1, 1));
  87777. if (OIMO.abs(m12) < 0.99999) {
  87778. this._x = OIMO.atan2(m32, m22);
  87779. this._y = OIMO.atan2(m13, m11);
  87780. } else {
  87781. this._x = OIMO.atan2(-m23, m33);
  87782. this._y = 0;
  87783. }
  87784. } else {
  87785. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order)
  87786. }
  87787. this._order = order;
  87788. this.onChangeCallback();
  87789. return this;
  87790. },
  87791. setFromQuaternion: function (q, order, update) {
  87792. var clamp = OIMO.clamp;
  87793. // q is assumed to be normalized
  87794. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  87795. var sqx = q.x * q.x;
  87796. var sqy = q.y * q.y;
  87797. var sqz = q.z * q.z;
  87798. var sqw = q.s * q.s;
  87799. order = order || this._order;
  87800. if (order === 'XYZ') {
  87801. this._x = OIMO.atan2(2 * (q.x * q.s - q.y * q.z), (sqw - sqx - sqy + sqz));
  87802. this._y = OIMO.asin(clamp(2 * (q.x * q.z + q.y * q.s), -1, 1));
  87803. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw + sqx - sqy - sqz));
  87804. } else if (order === 'YXZ') {
  87805. this._x = OIMO.asin(clamp(2 * (q.x * q.s - q.y * q.z), -1, 1));
  87806. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw - sqx - sqy + sqz));
  87807. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw - sqx + sqy - sqz));
  87808. } else if (order === 'ZXY') {
  87809. this._x = OIMO.asin(clamp(2 * (q.x * q.s + q.y * q.z), -1, 1));
  87810. this._y = OIMO.atan2(2 * (q.y * q.s - q.z * q.x), (sqw - sqx - sqy + sqz));
  87811. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw - sqx + sqy - sqz));
  87812. } else if (order === 'ZYX') {
  87813. this._x = OIMO.atan2(2 * (q.x * q.s + q.z * q.y), (sqw - sqx - sqy + sqz));
  87814. this._y = OIMO.asin(clamp(2 * (q.y * q.s - q.x * q.z), -1, 1));
  87815. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw + sqx - sqy - sqz));
  87816. } else if (order === 'YZX') {
  87817. this._x = OIMO.atan2(2 * (q.x * q.s - q.z * q.y), (sqw - sqx + sqy - sqz));
  87818. this._y = OIMO.atan2(2 * (q.y * q.s - q.x * q.z), (sqw + sqx - sqy - sqz));
  87819. this._z = OIMO.asin(clamp(2 * (q.x * q.y + q.z * q.s), -1, 1));
  87820. } else if (order === 'XZY') {
  87821. this._x = OIMO.atan2(2 * (q.x * q.s + q.y * q.z), (sqw - sqx + sqy - sqz));
  87822. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw + sqx - sqy - sqz));
  87823. this._z = OIMO.asin(clamp(2 * (q.z * q.s - q.x * q.y), -1, 1));
  87824. } else {
  87825. console.warn('OIMO.Euler: .setFromQuaternion() given unsupported order: ' + order)
  87826. }
  87827. this._order = order;
  87828. if (update !== false) this.onChangeCallback();
  87829. return this;
  87830. },
  87831. reorder: function () {
  87832. // WARNING: this discards revolution information -bhouston
  87833. var q = new OIMO.Quat();
  87834. return function (newOrder) {
  87835. q.setFromEuler(this);
  87836. this.setFromQuaternion(q, newOrder);
  87837. };
  87838. }(),
  87839. equals: function (euler) {
  87840. return (euler._x === this._x) && (euler._y === this._y) && (euler._z === this._z) && (euler._order === this._order);
  87841. },
  87842. fromArray: function (array) {
  87843. this._x = array[0];
  87844. this._y = array[1];
  87845. this._z = array[2];
  87846. if (array[3] !== undefined) this._order = array[3];
  87847. this.onChangeCallback();
  87848. return this;
  87849. },
  87850. toArray: function () {
  87851. return [this._x, this._y, this._z, this._order];
  87852. },
  87853. onChange: function (callback) {
  87854. this.onChangeCallback = callback;
  87855. return this;
  87856. },
  87857. onChangeCallback: function () { },
  87858. clone: function () {
  87859. return new OIMO.Euler(this._x, this._y, this._z, this._order);
  87860. }
  87861. };
  87862. OIMO.EulerToAxis = function (ox, oy, oz) {// angles in radians
  87863. var c1 = OIMO.cos(oy * 0.5);//heading
  87864. var s1 = OIMO.sin(oy * 0.5);
  87865. var c2 = OIMO.cos(oz * 0.5);//altitude
  87866. var s2 = OIMO.sin(oz * 0.5);
  87867. var c3 = OIMO.cos(ox * 0.5);//bank
  87868. var s3 = OIMO.sin(ox * 0.5);
  87869. var c1c2 = c1 * c2;
  87870. var s1s2 = s1 * s2;
  87871. var w = c1c2 * c3 - s1s2 * s3;
  87872. var x = c1c2 * s3 + s1s2 * c3;
  87873. var y = s1 * c2 * c3 + c1 * s2 * s3;
  87874. var z = c1 * s2 * c3 - s1 * c2 * s3;
  87875. var angle = 2 * OIMO.acos(w);
  87876. var norm = x * x + y * y + z * z;
  87877. if (norm < 0.001) {
  87878. x = 1;
  87879. y = z = 0;
  87880. } else {
  87881. norm = OIMO.sqrt(norm);
  87882. x /= norm;
  87883. y /= norm;
  87884. z /= norm;
  87885. }
  87886. return [angle, x, y, z];
  87887. }
  87888. OIMO.EulerToMatrix = function (ox, oy, oz) {// angles in radians
  87889. var ch = OIMO.cos(oy);//heading
  87890. var sh = OIMO.sin(oy);
  87891. var ca = OIMO.cos(oz);//altitude
  87892. var sa = OIMO.sin(oz);
  87893. var cb = OIMO.cos(ox);//bank
  87894. var sb = OIMO.sin(ox);
  87895. var mtx = new OIMO.Mat33();
  87896. var te = mtx.elements;
  87897. te[0] = ch * ca;
  87898. te[1] = sh * sb - ch * sa * cb;
  87899. te[2] = ch * sa * sb + sh * cb;
  87900. te[3] = sa;
  87901. te[4] = ca * cb;
  87902. te[5] = -ca * sb;
  87903. te[6] = -sh * ca;
  87904. te[7] = sh * sa * cb + ch * sb;
  87905. te[8] = -sh * sa * sb + ch * cb;
  87906. return mtx;
  87907. }
  87908. OIMO.MatrixToEuler = function (mtx) {// angles in radians
  87909. var te = mtx.elements;
  87910. var x, y, z;
  87911. if (te[3] > 0.998) { // singularity at north pole
  87912. y = OIMO.atan2(te[2], te[8]);
  87913. z = OIMO.PI / 2;
  87914. x = 0;
  87915. } else if (te[3] < -0.998) { // singularity at south pole
  87916. y = OIMO.atan2(te[2], te[8]);
  87917. z = -OIMO.PI / 2;
  87918. x = 0;
  87919. } else {
  87920. y = OIMO.atan2(-te[6], te[0]);
  87921. x = OIMO.atan2(-te[5], te[4]);
  87922. z = OIMO.asin(te[3]);
  87923. }
  87924. return [x, y, z];
  87925. }
  87926. OIMO.unwrapDegrees = function (r) {
  87927. r = r % 360;
  87928. if (r > 180) r -= 360;
  87929. if (r < -180) r += 360;
  87930. return r;
  87931. }
  87932. OIMO.unwrapRadian = function (r) {
  87933. r = r % OIMO.TwoPI;
  87934. if (r > OIMO.PI) r -= OIMO.TwoPI;
  87935. if (r < -OIMO.PI) r += OIMO.TwoPI;
  87936. return r;
  87937. }
  87938. OIMO.Distance3d = function (p1, p2) {
  87939. var xd = p2[0] - p1[0];
  87940. var yd = p2[1] - p1[1];
  87941. var zd = p2[2] - p1[2];
  87942. return OIMO.sqrt(xd * xd + yd * yd + zd * zd);
  87943. }
  87944. /**
  87945. * The base class of all type of the constraints.
  87946. * @author saharan
  87947. */
  87948. OIMO.Constraint = function () {
  87949. // The parent world of the constraint.
  87950. this.parent = null;
  87951. // The first body of the constraint.
  87952. this.body1 = null;
  87953. // The second body of the constraint.
  87954. this.body2 = null;
  87955. // Internal
  87956. this.addedToIsland = false;
  87957. }
  87958. OIMO.Constraint.prototype = {
  87959. constructor: OIMO.Constraint,
  87960. /**
  87961. * Prepare for solving the constraint.
  87962. * @param timeStep
  87963. * @param invTimeStep
  87964. */
  87965. preSolve: function (timeStep, invTimeStep) {
  87966. OIMO.Error("Constraint", "Inheritance error.");
  87967. },
  87968. /**
  87969. * Solve the constraint.
  87970. * This is usually called iteratively.
  87971. */
  87972. solve: function () {
  87973. OIMO.Error("Constraint", "Inheritance error.");
  87974. },
  87975. /**
  87976. * Do the post-processing.
  87977. */
  87978. postSolve: function () {
  87979. OIMO.Error("Constraint", "Inheritance error.");
  87980. }
  87981. }
  87982. /**
  87983. * Joints are used to constrain the motion between two rigid bodies.
  87984. * @author saharan
  87985. * @author lo-th
  87986. */
  87987. OIMO.Joint = function (config) {
  87988. OIMO.Constraint.call(this);
  87989. // joint name
  87990. this.name = "";
  87991. // The type of the joint.
  87992. this.type = OIMO.JOINT_NULL;
  87993. // The previous joint in the world.
  87994. this.prev = null;
  87995. // The next joint in the world.
  87996. this.next = null;
  87997. this.body1 = config.body1;
  87998. this.body2 = config.body2;
  87999. // The anchor point on the first rigid body in local coordinate system.
  88000. this.localAnchorPoint1 = new OIMO.Vec3().copy(config.localAnchorPoint1);
  88001. // The anchor point on the second rigid body in local coordinate system.
  88002. this.localAnchorPoint2 = new OIMO.Vec3().copy(config.localAnchorPoint2);
  88003. // The anchor point on the first rigid body in world coordinate system relative to the body's origin.
  88004. this.relativeAnchorPoint1 = new OIMO.Vec3();
  88005. // The anchor point on the second rigid body in world coordinate system relative to the body's origin.
  88006. this.relativeAnchorPoint2 = new OIMO.Vec3();
  88007. // The anchor point on the first rigid body in world coordinate system.
  88008. this.anchorPoint1 = new OIMO.Vec3();
  88009. // The anchor point on the second rigid body in world coordinate system.
  88010. this.anchorPoint2 = new OIMO.Vec3();
  88011. // Whether allow collision between connected rigid bodies or not.
  88012. this.allowCollision = config.allowCollision;
  88013. this.b1Link = new OIMO.JointLink(this);
  88014. this.b2Link = new OIMO.JointLink(this);
  88015. this.matrix = new OIMO.Mat44();
  88016. };
  88017. OIMO.Joint.prototype = Object.create(OIMO.Constraint.prototype);
  88018. OIMO.Joint.prototype.constructor = OIMO.Joint;
  88019. // Update all the anchor points.
  88020. OIMO.Joint.prototype.updateAnchorPoints = function () {
  88021. this.relativeAnchorPoint1.mulMat(this.body1.rotation, this.localAnchorPoint1);
  88022. this.relativeAnchorPoint2.mulMat(this.body2.rotation, this.localAnchorPoint2);
  88023. this.anchorPoint1.add(this.relativeAnchorPoint1, this.body1.position);
  88024. this.anchorPoint2.add(this.relativeAnchorPoint2, this.body2.position);
  88025. };
  88026. // Attach the joint from the bodies.
  88027. OIMO.Joint.prototype.attach = function () {
  88028. this.b1Link.body = this.body2;
  88029. this.b2Link.body = this.body1;
  88030. if (this.body1.jointLink != null) (this.b1Link.next = this.body1.jointLink).prev = this.b1Link;
  88031. else this.b1Link.next = null;
  88032. this.body1.jointLink = this.b1Link;
  88033. this.body1.numJoints++;
  88034. if (this.body2.jointLink != null) (this.b2Link.next = this.body2.jointLink).prev = this.b2Link;
  88035. else this.b2Link.next = null;
  88036. this.body2.jointLink = this.b2Link;
  88037. this.body2.numJoints++;
  88038. };
  88039. // Detach the joint from the bodies.
  88040. OIMO.Joint.prototype.detach = function () {
  88041. var prev = this.b1Link.prev;
  88042. var next = this.b1Link.next;
  88043. if (prev != null) prev.next = next;
  88044. if (next != null) next.prev = prev;
  88045. if (this.body1.jointLink == this.b1Link) this.body1.jointLink = next;
  88046. this.b1Link.prev = null;
  88047. this.b1Link.next = null;
  88048. this.b1Link.body = null;
  88049. this.body1.numJoints--;
  88050. prev = this.b2Link.prev;
  88051. next = this.b2Link.next;
  88052. if (prev != null) prev.next = next;
  88053. if (next != null) next.prev = prev;
  88054. if (this.body2.jointLink == this.b2Link) this.body2.jointLink = next;
  88055. this.b2Link.prev = null;
  88056. this.b2Link.next = null;
  88057. this.b2Link.body = null;
  88058. this.body2.numJoints--;
  88059. this.b1Link.body = null;
  88060. this.b2Link.body = null;
  88061. };
  88062. // Awake the bodies.
  88063. OIMO.Joint.prototype.awake = function () {
  88064. this.body1.awake();
  88065. this.body2.awake();
  88066. };
  88067. // calculation function
  88068. OIMO.Joint.prototype.preSolve = function (timeStep, invTimeStep) {
  88069. };
  88070. OIMO.Joint.prototype.solve = function () {
  88071. };
  88072. OIMO.Joint.prototype.postSolve = function () {
  88073. };
  88074. // Delete process
  88075. OIMO.Joint.prototype.remove = function () {
  88076. this.dispose();
  88077. };
  88078. OIMO.Joint.prototype.dispose = function () {
  88079. this.parent.removeJoint(this);
  88080. };
  88081. // Three js add
  88082. OIMO.Joint.prototype.getPosition = function () {
  88083. var p1 = new OIMO.Vec3().scale(this.anchorPoint1, OIMO.WORLD_SCALE);
  88084. var p2 = new OIMO.Vec3().scale(this.anchorPoint2, OIMO.WORLD_SCALE);
  88085. return [p1, p2];
  88086. };
  88087. OIMO.Joint.prototype.getMatrix = function () {
  88088. var m = this.matrix.elements;
  88089. var p1 = this.anchorPoint1;
  88090. var p2 = this.anchorPoint2;
  88091. m[0] = p1.x * OIMO.WORLD_SCALE;
  88092. m[1] = p1.y * OIMO.WORLD_SCALE;
  88093. m[2] = p1.z * OIMO.WORLD_SCALE;
  88094. m[3] = 0;
  88095. m[4] = p2.x * OIMO.WORLD_SCALE;
  88096. m[5] = p2.y * OIMO.WORLD_SCALE;
  88097. m[6] = p2.z * OIMO.WORLD_SCALE;
  88098. m[7] = 0;
  88099. return m;
  88100. };
  88101. /**
  88102. * A joint configuration holds all configuration data for constructing a joint.
  88103. * Joint configurations can be reused safely.
  88104. * @author saharan
  88105. */
  88106. OIMO.JointConfig = function () {
  88107. // The first rigid body of the joint.
  88108. this.body1 = null;
  88109. // The second rigid body of the joint.
  88110. this.body2 = null;
  88111. // The anchor point on the first rigid body in local coordinate system.
  88112. this.localAnchorPoint1 = new OIMO.Vec3();
  88113. // The anchor point on the second rigid body in local coordinate system.
  88114. this.localAnchorPoint2 = new OIMO.Vec3();
  88115. // The axis in the first body's coordinate system.
  88116. // his property is available in some joints.
  88117. this.localAxis1 = new OIMO.Vec3();
  88118. // The axis in the second body's coordinate system.
  88119. // This property is available in some joints.
  88120. this.localAxis2 = new OIMO.Vec3();
  88121. // Whether allow collision between connected rigid bodies or not.
  88122. this.allowCollision = false;
  88123. };
  88124. /**
  88125. * A link list of joints.
  88126. * @author saharan
  88127. */
  88128. OIMO.JointLink = function (joint) {
  88129. // The previous joint link.
  88130. this.prev = null;
  88131. // The next joint link.
  88132. this.next = null;
  88133. // The other rigid body connected to the joint.
  88134. this.body = null;
  88135. // The joint of the link.
  88136. this.joint = joint;
  88137. };
  88138. /**
  88139. * An information of limit and motor.
  88140. * @author saharan
  88141. */
  88142. OIMO.LimitMotor = function (axis, fixed) {
  88143. fixed = fixed || false;
  88144. // The axis of the constraint.
  88145. this.axis = axis;
  88146. // The current angle for rotational constraints.
  88147. this.angle = 0;
  88148. // The lower limit. Set lower > upper to disable
  88149. this.lowerLimit = fixed ? 0 : 1;
  88150. //if(fixed)this.lowerLimit = 0;
  88151. //else this.lowerLimit = 1;
  88152. // The upper limit. Set lower > upper to disable.
  88153. this.upperLimit = 0;
  88154. // The target motor speed.
  88155. this.motorSpeed = 0;
  88156. // The maximum motor force or torque. Set 0 to disable.
  88157. this.maxMotorForce = 0;
  88158. // The frequency of the spring. Set 0 to disable.
  88159. this.frequency = 0;
  88160. // The damping ratio of the spring. Set 0 for no damping, 1 for critical damping.
  88161. this.dampingRatio = 0;
  88162. };
  88163. OIMO.LimitMotor.prototype = {
  88164. constructor: OIMO.LimitMotor,
  88165. /**
  88166. * Set limit data into this constraint.
  88167. * @param lowerLimit
  88168. * @param upperLimit
  88169. */
  88170. setLimit: function (lowerLimit, upperLimit) {
  88171. this.lowerLimit = lowerLimit;
  88172. this.upperLimit = upperLimit;
  88173. },
  88174. /**
  88175. * Set motor data into this constraint.
  88176. * @param motorSpeed
  88177. * @param maxMotorForce
  88178. */
  88179. setMotor: function (motorSpeed, maxMotorForce) {
  88180. this.motorSpeed = motorSpeed;
  88181. this.maxMotorForce = maxMotorForce;
  88182. },
  88183. /**
  88184. * Set spring data into this constraint.
  88185. * @param frequency
  88186. * @param dampingRatio
  88187. */
  88188. setSpring: function (frequency, dampingRatio) {
  88189. this.frequency = frequency;
  88190. this.dampingRatio = dampingRatio;
  88191. }
  88192. };
  88193. /**
  88194. * A ball-and-socket joint limits relative translation on two anchor points on rigid bodies.
  88195. * @author saharan
  88196. * @author lo-th
  88197. */
  88198. OIMO.BallAndSocketJoint = function (config) {
  88199. OIMO.Joint.call(this, config);
  88200. this.type = OIMO.JOINT_BALL_AND_SOCKET;
  88201. this.lc = new OIMO.LinearConstraint(this);
  88202. };
  88203. OIMO.BallAndSocketJoint.prototype = Object.create(OIMO.Joint.prototype);
  88204. OIMO.BallAndSocketJoint.prototype.constructor = OIMO.BallAndSocketJoint;
  88205. OIMO.BallAndSocketJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  88206. this.updateAnchorPoints();
  88207. this.lc.preSolve(timeStep, invTimeStep);
  88208. };
  88209. OIMO.BallAndSocketJoint.prototype.solve = function () {
  88210. this.lc.solve();
  88211. };
  88212. OIMO.BallAndSocketJoint.prototype.postSolve = function () {
  88213. };
  88214. /**
  88215. * A distance joint limits the distance between two anchor points on rigid bodies.
  88216. * @author saharan
  88217. * @author lo-th
  88218. */
  88219. OIMO.DistanceJoint = function (config, minDistance, maxDistance) {
  88220. OIMO.Joint.call(this, config);
  88221. this.type = OIMO.JOINT_DISTANCE;
  88222. this.normal = new OIMO.Vec3();
  88223. this.nr = new OIMO.Vec3();
  88224. // The limit and motor information of the joint.
  88225. this.limitMotor = new OIMO.LimitMotor(this.normal, true);
  88226. this.limitMotor.lowerLimit = minDistance;
  88227. this.limitMotor.upperLimit = maxDistance;
  88228. this.t = new OIMO.TranslationalConstraint(this, this.limitMotor);
  88229. };
  88230. OIMO.DistanceJoint.prototype = Object.create(OIMO.Joint.prototype);
  88231. OIMO.DistanceJoint.prototype.constructor = OIMO.DistanceJoint;
  88232. OIMO.DistanceJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  88233. this.updateAnchorPoints();
  88234. //var nr = this.nr;
  88235. this.nr.sub(this.anchorPoint2, this.anchorPoint1);
  88236. //var len = OIMO.sqrt( nr.x*nr.x + nr.y*nr.y + nr.z*nr.z );
  88237. //if(len>0) len = 1/len;
  88238. //this.normal.scale( nr, len );
  88239. this.normal.normalize(this.nr);
  88240. this.t.preSolve(timeStep, invTimeStep);
  88241. };
  88242. OIMO.DistanceJoint.prototype.solve = function () {
  88243. this.t.solve();
  88244. };
  88245. OIMO.DistanceJoint.prototype.postSolve = function () {
  88246. };
  88247. /**
  88248. * A hinge joint allows only for relative rotation of rigid bodies along the axis.
  88249. * @author saharan
  88250. * @author lo-th
  88251. */
  88252. OIMO.HingeJoint = function (config, lowerAngleLimit, upperAngleLimit) {
  88253. OIMO.Joint.call(this, config);
  88254. this.type = OIMO.JOINT_HINGE;
  88255. // The axis in the first body's coordinate system.
  88256. this.localAxis1 = config.localAxis1.clone().norm();
  88257. // The axis in the second body's coordinate system.
  88258. this.localAxis2 = config.localAxis2.clone().norm();
  88259. // make angle axis 1
  88260. this.localAngle1 = new OIMO.Vec3(
  88261. this.localAxis1.y * this.localAxis1.x - this.localAxis1.z * this.localAxis1.z,
  88262. -this.localAxis1.z * this.localAxis1.y - this.localAxis1.x * this.localAxis1.x,
  88263. this.localAxis1.x * this.localAxis1.z + this.localAxis1.y * this.localAxis1.y
  88264. ).norm();
  88265. // make angle axis 2
  88266. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  88267. this.localAngle2 = new OIMO.Vec3().mulMat(arc, this.localAngle1);
  88268. this.nor = new OIMO.Vec3();
  88269. this.tan = new OIMO.Vec3();
  88270. this.bin = new OIMO.Vec3();
  88271. this.ax1 = new OIMO.Vec3();
  88272. this.ax2 = new OIMO.Vec3();
  88273. this.an1 = new OIMO.Vec3();
  88274. this.an2 = new OIMO.Vec3();
  88275. // The rotational limit and motor information of the joint.
  88276. this.limitMotor = new OIMO.LimitMotor(this.nor, false);
  88277. this.limitMotor.lowerLimit = lowerAngleLimit;
  88278. this.limitMotor.upperLimit = upperAngleLimit;
  88279. this.lc = new OIMO.LinearConstraint(this);
  88280. this.r3 = new OIMO.Rotational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  88281. };
  88282. OIMO.HingeJoint.prototype = Object.create(OIMO.Joint.prototype);
  88283. OIMO.HingeJoint.prototype.constructor = OIMO.HingeJoint;
  88284. OIMO.HingeJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  88285. var tmp1X, tmp1Y, tmp1Z, limite;//, nx, ny, nz, tx, ty, tz, bx, by, bz;
  88286. this.updateAnchorPoints();
  88287. this.ax1.mulMat(this.body1.rotation, this.localAxis1);
  88288. this.ax2.mulMat(this.body2.rotation, this.localAxis2);
  88289. this.an1.mulMat(this.body1.rotation, this.localAngle1);
  88290. this.an2.mulMat(this.body2.rotation, this.localAngle2);
  88291. this.nor.set(
  88292. this.ax1.x * this.body2.inverseMass + this.ax2.x * this.body1.inverseMass,
  88293. this.ax1.y * this.body2.inverseMass + this.ax2.y * this.body1.inverseMass,
  88294. this.ax1.z * this.body2.inverseMass + this.ax2.z * this.body1.inverseMass
  88295. ).norm();
  88296. this.tan.set(
  88297. this.nor.y * this.nor.x - this.nor.z * this.nor.z,
  88298. -this.nor.z * this.nor.y - this.nor.x * this.nor.x,
  88299. this.nor.x * this.nor.z + this.nor.y * this.nor.y
  88300. ).norm();
  88301. this.bin.set(
  88302. this.nor.y * this.tan.z - this.nor.z * this.tan.y,
  88303. this.nor.z * this.tan.x - this.nor.x * this.tan.z,
  88304. this.nor.x * this.tan.y - this.nor.y * this.tan.x
  88305. );
  88306. // calculate hinge angle
  88307. limite = this.acosClamp(this.an1.x * this.an2.x + this.an1.y * this.an2.y + this.an1.z * this.an2.z)
  88308. if (
  88309. this.nor.x * (this.an1.y * this.an2.z - this.an1.z * this.an2.y) +
  88310. this.nor.y * (this.an1.z * this.an2.x - this.an1.x * this.an2.z) +
  88311. this.nor.z * (this.an1.x * this.an2.y - this.an1.y * this.an2.x) < 0
  88312. ) {
  88313. this.limitMotor.angle = -limite;
  88314. } else {
  88315. this.limitMotor.angle = limite;
  88316. }
  88317. tmp1X = this.ax1.y * this.ax2.z - this.ax1.z * this.ax2.y;
  88318. tmp1Y = this.ax1.z * this.ax2.x - this.ax1.x * this.ax2.z;
  88319. tmp1Z = this.ax1.x * this.ax2.y - this.ax1.y * this.ax2.x;
  88320. this.r3.limitMotor2.angle = this.tan.x * tmp1X + this.tan.y * tmp1Y + this.tan.z * tmp1Z;
  88321. this.r3.limitMotor3.angle = this.bin.x * tmp1X + this.bin.y * tmp1Y + this.bin.z * tmp1Z;
  88322. this.r3.preSolve(timeStep, invTimeStep);
  88323. this.lc.preSolve(timeStep, invTimeStep);
  88324. };
  88325. OIMO.HingeJoint.prototype.solve = function () {
  88326. this.r3.solve();
  88327. this.lc.solve();
  88328. };
  88329. OIMO.HingeJoint.prototype.postSolve = function () {
  88330. };
  88331. OIMO.HingeJoint.prototype.acosClamp = function (cos) {
  88332. if (cos > 1) return 0;
  88333. else if (cos < -1) return OIMO.PI;
  88334. else return OIMO.acos(cos);
  88335. };
  88336. /**
  88337. * A prismatic joint allows only for relative translation of rigid bodies along the axis.
  88338. * @author saharan
  88339. * @author lo-th
  88340. */
  88341. OIMO.PrismaticJoint = function (config, lowerTranslation, upperTranslation) {
  88342. OIMO.Joint.call(this, config);
  88343. this.type = OIMO.JOINT_PRISMATIC;
  88344. // The axis in the first body's coordinate system.
  88345. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  88346. // The axis in the second body's coordinate system.
  88347. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  88348. this.localAxis1X = this.localAxis1.x;
  88349. this.localAxis1Y = this.localAxis1.y;
  88350. this.localAxis1Z = this.localAxis1.z;
  88351. this.localAxis2X = this.localAxis2.x;
  88352. this.localAxis2Y = this.localAxis2.y;
  88353. this.localAxis2Z = this.localAxis2.z;
  88354. this.nor = new OIMO.Vec3();
  88355. this.tan = new OIMO.Vec3();
  88356. this.bin = new OIMO.Vec3();
  88357. this.ac = new OIMO.AngularConstraint(this, new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  88358. // The translational limit and motor information of the joint.
  88359. this.limitMotor = new OIMO.LimitMotor(this.nor, true);
  88360. this.limitMotor.lowerLimit = lowerTranslation;
  88361. this.limitMotor.upperLimit = upperTranslation;
  88362. this.t3 = new OIMO.Translational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  88363. };
  88364. OIMO.PrismaticJoint.prototype = Object.create(OIMO.Joint.prototype);
  88365. OIMO.PrismaticJoint.prototype.constructor = OIMO.PrismaticJoint;
  88366. OIMO.PrismaticJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  88367. var tmpM;
  88368. var tmp1X;
  88369. var tmp1Y;
  88370. var tmp1Z;
  88371. this.updateAnchorPoints();
  88372. tmpM = this.body1.rotation.elements;
  88373. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  88374. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  88375. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  88376. tmpM = this.body2.rotation.elements;
  88377. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  88378. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  88379. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  88380. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  88381. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  88382. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  88383. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  88384. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  88385. nx *= tmp1X;
  88386. ny *= tmp1X;
  88387. nz *= tmp1X;
  88388. var tx = ny * nx - nz * nz;
  88389. var ty = -nz * ny - nx * nx;
  88390. var tz = nx * nz + ny * ny;
  88391. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  88392. tx *= tmp1X;
  88393. ty *= tmp1X;
  88394. tz *= tmp1X;
  88395. var bx = ny * tz - nz * ty;
  88396. var by = nz * tx - nx * tz;
  88397. var bz = nx * ty - ny * tx;
  88398. this.nor.init(nx, ny, nz);
  88399. this.tan.init(tx, ty, tz);
  88400. this.bin.init(bx, by, bz);
  88401. this.ac.preSolve(timeStep, invTimeStep);
  88402. this.t3.preSolve(timeStep, invTimeStep);
  88403. };
  88404. OIMO.PrismaticJoint.prototype.solve = function () {
  88405. this.ac.solve();
  88406. this.t3.solve();
  88407. };
  88408. OIMO.PrismaticJoint.prototype.postSolve = function () {
  88409. };
  88410. /**
  88411. * A slider joint allows for relative translation and relative rotation between two rigid bodies along the axis.
  88412. * @author saharan
  88413. * @author lo-th
  88414. */
  88415. OIMO.SliderJoint = function (config, lowerTranslation, upperTranslation) {
  88416. OIMO.Joint.call(this, config);
  88417. this.type = OIMO.JOINT_SLIDER;
  88418. // The first axis in local coordinate system.
  88419. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  88420. // The second axis in local coordinate system.
  88421. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  88422. var len;
  88423. this.localAxis1X = this.localAxis1.x;
  88424. this.localAxis1Y = this.localAxis1.y;
  88425. this.localAxis1Z = this.localAxis1.z;
  88426. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  88427. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  88428. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  88429. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  88430. this.localAngAxis1X *= len;
  88431. this.localAngAxis1Y *= len;
  88432. this.localAngAxis1Z *= len;
  88433. this.localAxis2X = this.localAxis2.x;
  88434. this.localAxis2Y = this.localAxis2.y;
  88435. this.localAxis2Z = this.localAxis2.z;
  88436. // make angle axis 2
  88437. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  88438. var tarc = arc.elements;
  88439. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  88440. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  88441. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  88442. this.nor = new OIMO.Vec3();
  88443. this.tan = new OIMO.Vec3();
  88444. this.bin = new OIMO.Vec3();
  88445. // The limit and motor for the rotation
  88446. this.rotationalLimitMotor = new OIMO.LimitMotor(this.nor, false);
  88447. this.r3 = new OIMO.Rotational3Constraint(this, this.rotationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  88448. // The limit and motor for the translation.
  88449. this.translationalLimitMotor = new OIMO.LimitMotor(this.nor, true);
  88450. this.translationalLimitMotor.lowerLimit = lowerTranslation;
  88451. this.translationalLimitMotor.upperLimit = upperTranslation;
  88452. this.t3 = new OIMO.Translational3Constraint(this, this.translationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  88453. };
  88454. OIMO.SliderJoint.prototype = Object.create(OIMO.Joint.prototype);
  88455. OIMO.SliderJoint.prototype.constructor = OIMO.SliderJoint;
  88456. OIMO.SliderJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  88457. var tmpM;
  88458. var tmp1X;
  88459. var tmp1Y;
  88460. var tmp1Z;
  88461. this.updateAnchorPoints();
  88462. tmpM = this.body1.rotation.elements;
  88463. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  88464. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  88465. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  88466. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  88467. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  88468. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  88469. tmpM = this.body2.rotation.elements;
  88470. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  88471. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  88472. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  88473. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  88474. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  88475. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  88476. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  88477. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  88478. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  88479. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  88480. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  88481. nx *= tmp1X;
  88482. ny *= tmp1X;
  88483. nz *= tmp1X;
  88484. var tx = ny * nx - nz * nz;
  88485. var ty = -nz * ny - nx * nx;
  88486. var tz = nx * nz + ny * ny;
  88487. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  88488. tx *= tmp1X;
  88489. ty *= tmp1X;
  88490. tz *= tmp1X;
  88491. var bx = ny * tz - nz * ty;
  88492. var by = nz * tx - nx * tz;
  88493. var bz = nx * ty - ny * tx;
  88494. this.nor.init(nx, ny, nz);
  88495. this.tan.init(tx, ty, tz);
  88496. this.bin.init(bx, by, bz);
  88497. // ----------------------------------------------
  88498. // calculate hinge angle
  88499. // ----------------------------------------------
  88500. if (
  88501. nx * (angAxis1Y * angAxis2Z - angAxis1Z * angAxis2Y) +
  88502. ny * (angAxis1Z * angAxis2X - angAxis1X * angAxis2Z) +
  88503. nz * (angAxis1X * angAxis2Y - angAxis1Y * angAxis2X) < 0
  88504. ) {
  88505. this.rotationalLimitMotor.angle = -this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  88506. } else {
  88507. this.rotationalLimitMotor.angle = this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  88508. }
  88509. // angular error
  88510. tmp1X = axis1Y * axis2Z - axis1Z * axis2Y;
  88511. tmp1Y = axis1Z * axis2X - axis1X * axis2Z;
  88512. tmp1Z = axis1X * axis2Y - axis1Y * axis2X;
  88513. this.r3.limitMotor2.angle = tx * tmp1X + ty * tmp1Y + tz * tmp1Z;
  88514. this.r3.limitMotor3.angle = bx * tmp1X + by * tmp1Y + bz * tmp1Z;
  88515. this.r3.preSolve(timeStep, invTimeStep);
  88516. this.t3.preSolve(timeStep, invTimeStep);
  88517. };
  88518. OIMO.SliderJoint.prototype.solve = function () {
  88519. this.r3.solve();
  88520. this.t3.solve();
  88521. };
  88522. OIMO.SliderJoint.prototype.postSolve = function () {
  88523. };
  88524. OIMO.SliderJoint.prototype.acosClamp = function (cos) {
  88525. if (cos > 1) return 0;
  88526. else if (cos < -1) return OIMO.PI;
  88527. else return OIMO.acos(cos);
  88528. };
  88529. /**
  88530. * A wheel joint allows for relative rotation between two rigid bodies along two axes.
  88531. * The wheel joint also allows for relative translation for the suspension.
  88532. * @author saharan
  88533. * @author lo-th
  88534. */
  88535. OIMO.WheelJoint = function (config) {
  88536. OIMO.Joint.call(this, config);
  88537. this.type = OIMO.JOINT_WHEEL;
  88538. // The first axis in local coordinate system.
  88539. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  88540. // The second axis in local coordinate system.
  88541. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  88542. var len;
  88543. this.localAxis1X = this.localAxis1.x;
  88544. this.localAxis1Y = this.localAxis1.y;
  88545. this.localAxis1Z = this.localAxis1.z;
  88546. this.localAxis2X = this.localAxis2.x;
  88547. this.localAxis2Y = this.localAxis2.y;
  88548. this.localAxis2Z = this.localAxis2.z;
  88549. var dot = this.localAxis1X * this.localAxis2X + this.localAxis1Y * this.localAxis2Y + this.localAxis1Z * this.localAxis2Z;
  88550. if (dot > -1 && dot < 1) {
  88551. this.localAngAxis1X = this.localAxis2X - dot * this.localAxis1X;
  88552. this.localAngAxis1Y = this.localAxis2Y - dot * this.localAxis1Y;
  88553. this.localAngAxis1Z = this.localAxis2Z - dot * this.localAxis1Z;
  88554. this.localAngAxis2X = this.localAxis1X - dot * this.localAxis2X;
  88555. this.localAngAxis2Y = this.localAxis1Y - dot * this.localAxis2Y;
  88556. this.localAngAxis2Z = this.localAxis1Z - dot * this.localAxis2Z;
  88557. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  88558. this.localAngAxis1X *= len;
  88559. this.localAngAxis1Y *= len;
  88560. this.localAngAxis1Z *= len;
  88561. len = 1 / OIMO.sqrt(this.localAngAxis2X * this.localAngAxis2X + this.localAngAxis2Y * this.localAngAxis2Y + this.localAngAxis2Z * this.localAngAxis2Z);
  88562. this.localAngAxis2X *= len;
  88563. this.localAngAxis2Y *= len;
  88564. this.localAngAxis2Z *= len;
  88565. } else {
  88566. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  88567. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  88568. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  88569. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  88570. this.localAngAxis1X *= len;
  88571. this.localAngAxis1Y *= len;
  88572. this.localAngAxis1Z *= len;
  88573. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  88574. var tarc = arc.elements;
  88575. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  88576. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  88577. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  88578. }
  88579. this.nor = new OIMO.Vec3();
  88580. this.tan = new OIMO.Vec3();
  88581. this.bin = new OIMO.Vec3();
  88582. // The translational limit and motor information of the joint.
  88583. this.translationalLimitMotor = new OIMO.LimitMotor(this.tan, true);
  88584. this.translationalLimitMotor.frequency = 8;
  88585. this.translationalLimitMotor.dampingRatio = 1;
  88586. // The first rotational limit and motor information of the joint.
  88587. this.rotationalLimitMotor1 = new OIMO.LimitMotor(this.tan, false);
  88588. // The second rotational limit and motor information of the joint.
  88589. this.rotationalLimitMotor2 = new OIMO.LimitMotor(this.bin, false);
  88590. this.t3 = new OIMO.Translational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.translationalLimitMotor, new OIMO.LimitMotor(this.bin, true));
  88591. this.t3.weight = 1;
  88592. this.r3 = new OIMO.Rotational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.rotationalLimitMotor1, this.rotationalLimitMotor2);
  88593. };
  88594. OIMO.WheelJoint.prototype = Object.create(OIMO.Joint.prototype);
  88595. OIMO.WheelJoint.prototype.constructor = OIMO.WheelJoint;
  88596. OIMO.WheelJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  88597. var tmpM;
  88598. var tmp1X;
  88599. var tmp1Y;
  88600. var tmp1Z;
  88601. this.updateAnchorPoints();
  88602. tmpM = this.body1.rotation.elements;
  88603. var x1 = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  88604. var y1 = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  88605. var z1 = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  88606. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  88607. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  88608. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  88609. tmpM = this.body2.rotation.elements;
  88610. var x2 = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  88611. var y2 = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  88612. var z2 = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  88613. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  88614. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  88615. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  88616. this.r3.limitMotor1.angle = x1 * x2 + y1 * y2 + z1 * z2;
  88617. if (x1 * (angAxis1Y * z2 - angAxis1Z * y2) + y1 * (angAxis1Z * x2 - angAxis1X * z2) + z1 * (angAxis1X * y2 - angAxis1Y * x2) < 0) {
  88618. this.rotationalLimitMotor1.angle = -this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  88619. } else {
  88620. this.rotationalLimitMotor1.angle = this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  88621. }
  88622. if (x2 * (angAxis2Y * z1 - angAxis2Z * y1) + y2 * (angAxis2Z * x1 - angAxis2X * z1) + z2 * (angAxis2X * y1 - angAxis2Y * x1) < 0) {
  88623. this.rotationalLimitMotor2.angle = this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  88624. } else {
  88625. this.rotationalLimitMotor2.angle = -this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  88626. }
  88627. var nx = y2 * z1 - z2 * y1;
  88628. var ny = z2 * x1 - x2 * z1;
  88629. var nz = x2 * y1 - y2 * x1;
  88630. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  88631. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  88632. nx *= tmp1X;
  88633. ny *= tmp1X;
  88634. nz *= tmp1X;
  88635. var tx = ny * z2 - nz * y2;
  88636. var ty = nz * x2 - nx * z2;
  88637. var tz = nx * y2 - ny * x2;
  88638. tmp1X = OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  88639. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  88640. tx *= tmp1X;
  88641. ty *= tmp1X;
  88642. tz *= tmp1X;
  88643. var bx = y1 * nz - z1 * ny;
  88644. var by = z1 * nx - x1 * nz;
  88645. var bz = x1 * ny - y1 * nx;
  88646. tmp1X = OIMO.sqrt(bx * bx + by * by + bz * bz);
  88647. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  88648. bx *= tmp1X;
  88649. by *= tmp1X;
  88650. bz *= tmp1X;
  88651. this.nor.init(nx, ny, nz);
  88652. this.tan.init(tx, ty, tz);
  88653. this.bin.init(bx, by, bz);
  88654. this.r3.preSolve(timeStep, invTimeStep);
  88655. this.t3.preSolve(timeStep, invTimeStep);
  88656. };
  88657. OIMO.WheelJoint.prototype.solve = function () {
  88658. this.r3.solve();
  88659. this.t3.solve();
  88660. };
  88661. OIMO.WheelJoint.prototype.postSolve = function () {
  88662. };
  88663. OIMO.WheelJoint.prototype.acosClamp = function (cos) {
  88664. if (cos > 1) return 0;
  88665. else if (cos < -1) return OIMO.PI;
  88666. else return OIMO.acos(cos);
  88667. };
  88668. /**
  88669. * An angular constraint for all axes for various joints.
  88670. * @author saharan
  88671. */
  88672. OIMO.AngularConstraint = function (joint, targetOrientation) {
  88673. this.joint = joint;
  88674. this.targetOrientation = new OIMO.Quat().invert(targetOrientation);
  88675. this.relativeOrientation = new OIMO.Quat();
  88676. this.ii1 = null;
  88677. this.ii2 = null;
  88678. this.dd = null;
  88679. this.vel = new OIMO.Vec3();
  88680. this.imp = new OIMO.Vec3();
  88681. this.rn0 = new OIMO.Vec3();
  88682. this.rn1 = new OIMO.Vec3();
  88683. this.rn2 = new OIMO.Vec3();
  88684. this.b1 = joint.body1;
  88685. this.b2 = joint.body2;
  88686. this.a1 = this.b1.angularVelocity;
  88687. this.a2 = this.b2.angularVelocity;
  88688. this.i1 = this.b1.inverseInertia;
  88689. this.i2 = this.b2.inverseInertia;
  88690. };
  88691. OIMO.AngularConstraint.prototype = {
  88692. constructor: OIMO.AngularConstraint,
  88693. preSolve: function (timeStep, invTimeStep) {
  88694. var inv, len, v, vv;
  88695. this.ii1 = this.i1.clone();
  88696. this.ii2 = this.i2.clone();
  88697. v = new OIMO.Mat33().add(this.ii1, this.ii2).elements;
  88698. 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]));
  88699. this.dd = new OIMO.Mat33(
  88700. v[4] * v[8] - v[5] * v[7], v[2] * v[7] - v[1] * v[8], v[1] * v[5] - v[2] * v[4],
  88701. v[5] * v[6] - v[3] * v[8], v[0] * v[8] - v[2] * v[6], v[2] * v[3] - v[0] * v[5],
  88702. v[3] * v[7] - v[4] * v[6], v[1] * v[6] - v[0] * v[7], v[0] * v[4] - v[1] * v[3]
  88703. ).multiply(inv);
  88704. this.relativeOrientation.invert(this.b1.orientation);
  88705. this.relativeOrientation.mul(this.targetOrientation, this.relativeOrientation);
  88706. this.relativeOrientation.mul(this.b2.orientation, this.relativeOrientation);
  88707. inv = this.relativeOrientation.s * 2;
  88708. this.vel.scale(this.relativeOrientation, inv);
  88709. len = this.vel.length();
  88710. if (len > 0.02) {
  88711. len = (0.02 - len) / len * invTimeStep * 0.05;
  88712. this.vel.scaleEqual(len);
  88713. } else {
  88714. this.vel.init();
  88715. }
  88716. this.rn1.mulMat(this.ii1, this.imp);
  88717. this.rn2.mulMat(this.ii2, this.imp);
  88718. this.a1.addEqual(this.rn1);
  88719. this.a2.subEqual(this.rn2);
  88720. },
  88721. solve: function () {
  88722. var r = this.a2.clone().subEqual(this.a1).subEqual(this.vel);
  88723. this.rn0.mulMat(this.dd, r);
  88724. this.rn1.mulMat(this.ii1, this.rn0);
  88725. this.rn2.mulMat(this.ii2, this.rn0);
  88726. this.imp.addEqual(this.rn0);
  88727. this.a1.addEqual(this.rn1);
  88728. this.a2.subEqual(this.rn2);
  88729. }
  88730. };
  88731. /**
  88732. * A linear constraint for all axes for various joints.
  88733. * @author saharan
  88734. */
  88735. OIMO.LinearConstraint = function (joint) {
  88736. this.m1 = NaN;
  88737. this.m2 = NaN;
  88738. this.ii1 = null;
  88739. this.ii2 = null;
  88740. this.dd = null;
  88741. this.r1x = NaN;
  88742. this.r1y = NaN;
  88743. this.r1z = NaN;
  88744. this.r2x = NaN;
  88745. this.r2y = NaN;
  88746. this.r2z = NaN;
  88747. this.ax1x = NaN;
  88748. this.ax1y = NaN;
  88749. this.ax1z = NaN;
  88750. this.ay1x = NaN;
  88751. this.ay1y = NaN;
  88752. this.ay1z = NaN;
  88753. this.az1x = NaN;
  88754. this.az1y = NaN;
  88755. this.az1z = NaN;
  88756. this.ax2x = NaN;
  88757. this.ax2y = NaN;
  88758. this.ax2z = NaN;
  88759. this.ay2x = NaN;
  88760. this.ay2y = NaN;
  88761. this.ay2z = NaN;
  88762. this.az2x = NaN;
  88763. this.az2y = NaN;
  88764. this.az2z = NaN;
  88765. this.vel = NaN;
  88766. this.velx = NaN;
  88767. this.vely = NaN;
  88768. this.velz = NaN;
  88769. this.joint = joint;
  88770. this.r1 = joint.relativeAnchorPoint1;
  88771. this.r2 = joint.relativeAnchorPoint2;
  88772. this.p1 = joint.anchorPoint1;
  88773. this.p2 = joint.anchorPoint2;
  88774. this.b1 = joint.body1;
  88775. this.b2 = joint.body2;
  88776. this.l1 = this.b1.linearVelocity;
  88777. this.l2 = this.b2.linearVelocity;
  88778. this.a1 = this.b1.angularVelocity;
  88779. this.a2 = this.b2.angularVelocity;
  88780. this.i1 = this.b1.inverseInertia;
  88781. this.i2 = this.b2.inverseInertia;
  88782. this.impx = 0;
  88783. this.impy = 0;
  88784. this.impz = 0;
  88785. }
  88786. OIMO.LinearConstraint.prototype = {
  88787. constructor: OIMO.LinearConstraint,
  88788. preSolve: function (timeStep, invTimeStep) {
  88789. this.r1x = this.r1.x;
  88790. this.r1y = this.r1.y;
  88791. this.r1z = this.r1.z;
  88792. this.r2x = this.r2.x;
  88793. this.r2y = this.r2.y;
  88794. this.r2z = this.r2.z;
  88795. this.m1 = this.b1.inverseMass;
  88796. this.m2 = this.b2.inverseMass;
  88797. this.ii1 = this.i1.clone();
  88798. this.ii2 = this.i2.clone();
  88799. var ii1 = this.ii1.elements;
  88800. var ii2 = this.ii2.elements;
  88801. this.ax1x = this.r1z * ii1[1] + -this.r1y * ii1[2];
  88802. this.ax1y = this.r1z * ii1[4] + -this.r1y * ii1[5];
  88803. this.ax1z = this.r1z * ii1[7] + -this.r1y * ii1[8];
  88804. this.ay1x = -this.r1z * ii1[0] + this.r1x * ii1[2];
  88805. this.ay1y = -this.r1z * ii1[3] + this.r1x * ii1[5];
  88806. this.ay1z = -this.r1z * ii1[6] + this.r1x * ii1[8];
  88807. this.az1x = this.r1y * ii1[0] + -this.r1x * ii1[1];
  88808. this.az1y = this.r1y * ii1[3] + -this.r1x * ii1[4];
  88809. this.az1z = this.r1y * ii1[6] + -this.r1x * ii1[7];
  88810. this.ax2x = this.r2z * ii2[1] + -this.r2y * ii2[2];
  88811. this.ax2y = this.r2z * ii2[4] + -this.r2y * ii2[5];
  88812. this.ax2z = this.r2z * ii2[7] + -this.r2y * ii2[8];
  88813. this.ay2x = -this.r2z * ii2[0] + this.r2x * ii2[2];
  88814. this.ay2y = -this.r2z * ii2[3] + this.r2x * ii2[5];
  88815. this.ay2z = -this.r2z * ii2[6] + this.r2x * ii2[8];
  88816. this.az2x = this.r2y * ii2[0] + -this.r2x * ii2[1];
  88817. this.az2y = this.r2y * ii2[3] + -this.r2x * ii2[4];
  88818. this.az2z = this.r2y * ii2[6] + -this.r2x * ii2[7];
  88819. // calculate point-to-point mass matrix
  88820. // from impulse equation
  88821. //
  88822. // M = ([/m] - [r^][/I][r^]) ^ -1
  88823. //
  88824. // where
  88825. //
  88826. // [/m] = |1/m, 0, 0|
  88827. // |0, 1/m, 0|
  88828. // |0, 0, 1/m|
  88829. //
  88830. // [r^] = |0, -rz, ry|
  88831. // |rz, 0, -rx|
  88832. // |-ry, rx, 0|
  88833. //
  88834. // [/I] = Inverted moment inertia
  88835. var rxx = this.m1 + this.m2;
  88836. var kk = new OIMO.Mat33(rxx, 0, 0, 0, rxx, 0, 0, 0, rxx);
  88837. var k = kk.elements;
  88838. k[0] += ii1[4] * this.r1z * this.r1z - (ii1[7] + ii1[5]) * this.r1y * this.r1z + ii1[8] * this.r1y * this.r1y;
  88839. k[1] += (ii1[6] * this.r1y + ii1[5] * this.r1x) * this.r1z - ii1[3] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  88840. k[2] += (ii1[3] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[6] * this.r1y * this.r1y + ii1[7] * this.r1x * this.r1y;
  88841. k[3] += (ii1[2] * this.r1y + ii1[7] * this.r1x) * this.r1z - ii1[1] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  88842. k[4] += ii1[0] * this.r1z * this.r1z - (ii1[6] + ii1[2]) * this.r1x * this.r1z + ii1[8] * this.r1x * this.r1x;
  88843. k[5] += (ii1[1] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[7] * this.r1x * this.r1x + ii1[6] * this.r1x * this.r1y;
  88844. k[6] += (ii1[1] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[2] * this.r1y * this.r1y + ii1[5] * this.r1x * this.r1y;
  88845. k[7] += (ii1[3] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[5] * this.r1x * this.r1x + ii1[2] * this.r1x * this.r1y;
  88846. k[8] += ii1[0] * this.r1y * this.r1y - (ii1[3] + ii1[1]) * this.r1x * this.r1y + ii1[4] * this.r1x * this.r1x;
  88847. k[0] += ii2[4] * this.r2z * this.r2z - (ii2[7] + ii2[5]) * this.r2y * this.r2z + ii2[8] * this.r2y * this.r2y;
  88848. k[1] += (ii2[6] * this.r2y + ii2[5] * this.r2x) * this.r2z - ii2[3] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  88849. k[2] += (ii2[3] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[6] * this.r2y * this.r2y + ii2[7] * this.r2x * this.r2y;
  88850. k[3] += (ii2[2] * this.r2y + ii2[7] * this.r2x) * this.r2z - ii2[1] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  88851. k[4] += ii2[0] * this.r2z * this.r2z - (ii2[6] + ii2[2]) * this.r2x * this.r2z + ii2[8] * this.r2x * this.r2x;
  88852. k[5] += (ii2[1] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[7] * this.r2x * this.r2x + ii2[6] * this.r2x * this.r2y;
  88853. k[6] += (ii2[1] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[2] * this.r2y * this.r2y + ii2[5] * this.r2x * this.r2y;
  88854. k[7] += (ii2[3] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[5] * this.r2x * this.r2x + ii2[2] * this.r2x * this.r2y;
  88855. k[8] += ii2[0] * this.r2y * this.r2y - (ii2[3] + ii2[1]) * this.r2x * this.r2y + ii2[4] * this.r2x * this.r2x;
  88856. 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]));
  88857. this.dd = new OIMO.Mat33(
  88858. k[4] * k[8] - k[5] * k[7], k[2] * k[7] - k[1] * k[8], k[1] * k[5] - k[2] * k[4],
  88859. k[5] * k[6] - k[3] * k[8], k[0] * k[8] - k[2] * k[6], k[2] * k[3] - k[0] * k[5],
  88860. k[3] * k[7] - k[4] * k[6], k[1] * k[6] - k[0] * k[7], k[0] * k[4] - k[1] * k[3]
  88861. ).multiply(inv);
  88862. this.velx = this.p2.x - this.p1.x;
  88863. this.vely = this.p2.y - this.p1.y;
  88864. this.velz = this.p2.z - this.p1.z;
  88865. var len = OIMO.sqrt(this.velx * this.velx + this.vely * this.vely + this.velz * this.velz);
  88866. if (len > 0.005) {
  88867. len = (0.005 - len) / len * invTimeStep * 0.05;
  88868. this.velx *= len;
  88869. this.vely *= len;
  88870. this.velz *= len;
  88871. } else {
  88872. this.velx = 0;
  88873. this.vely = 0;
  88874. this.velz = 0;
  88875. }
  88876. this.impx *= 0.95;
  88877. this.impy *= 0.95;
  88878. this.impz *= 0.95;
  88879. this.l1.x += this.impx * this.m1;
  88880. this.l1.y += this.impy * this.m1;
  88881. this.l1.z += this.impz * this.m1;
  88882. this.a1.x += this.impx * this.ax1x + this.impy * this.ay1x + this.impz * this.az1x;
  88883. this.a1.y += this.impx * this.ax1y + this.impy * this.ay1y + this.impz * this.az1y;
  88884. this.a1.z += this.impx * this.ax1z + this.impy * this.ay1z + this.impz * this.az1z;
  88885. this.l2.x -= this.impx * this.m2;
  88886. this.l2.y -= this.impy * this.m2;
  88887. this.l2.z -= this.impz * this.m2;
  88888. this.a2.x -= this.impx * this.ax2x + this.impy * this.ay2x + this.impz * this.az2x;
  88889. this.a2.y -= this.impx * this.ax2y + this.impy * this.ay2y + this.impz * this.az2y;
  88890. this.a2.z -= this.impx * this.ax2z + this.impy * this.ay2z + this.impz * this.az2z;
  88891. },
  88892. solve: function () {
  88893. var d = this.dd.elements;
  88894. 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;
  88895. 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;
  88896. 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;
  88897. var nimpx = rvx * d[0] + rvy * d[1] + rvz * d[2];
  88898. var nimpy = rvx * d[3] + rvy * d[4] + rvz * d[5];
  88899. var nimpz = rvx * d[6] + rvy * d[7] + rvz * d[8];
  88900. this.impx += nimpx;
  88901. this.impy += nimpy;
  88902. this.impz += nimpz;
  88903. this.l1.x += nimpx * this.m1;
  88904. this.l1.y += nimpy * this.m1;
  88905. this.l1.z += nimpz * this.m1;
  88906. this.a1.x += nimpx * this.ax1x + nimpy * this.ay1x + nimpz * this.az1x;
  88907. this.a1.y += nimpx * this.ax1y + nimpy * this.ay1y + nimpz * this.az1y;
  88908. this.a1.z += nimpx * this.ax1z + nimpy * this.ay1z + nimpz * this.az1z;
  88909. this.l2.x -= nimpx * this.m2;
  88910. this.l2.y -= nimpy * this.m2;
  88911. this.l2.z -= nimpz * this.m2;
  88912. this.a2.x -= nimpx * this.ax2x + nimpy * this.ay2x + nimpz * this.az2x;
  88913. this.a2.y -= nimpx * this.ax2y + nimpy * this.ay2y + nimpz * this.az2y;
  88914. this.a2.z -= nimpx * this.ax2z + nimpy * this.ay2z + nimpz * this.az2z;
  88915. }
  88916. }
  88917. /**
  88918. * A three-axis rotational constraint for various joints.
  88919. * @author saharan
  88920. */
  88921. OIMO.Rotational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  88922. this.cfm1 = NaN;
  88923. this.cfm2 = NaN;
  88924. this.cfm3 = NaN;
  88925. this.i1e00 = NaN;
  88926. this.i1e01 = NaN;
  88927. this.i1e02 = NaN;
  88928. this.i1e10 = NaN;
  88929. this.i1e11 = NaN;
  88930. this.i1e12 = NaN;
  88931. this.i1e20 = NaN;
  88932. this.i1e21 = NaN;
  88933. this.i1e22 = NaN;
  88934. this.i2e00 = NaN;
  88935. this.i2e01 = NaN;
  88936. this.i2e02 = NaN;
  88937. this.i2e10 = NaN;
  88938. this.i2e11 = NaN;
  88939. this.i2e12 = NaN;
  88940. this.i2e20 = NaN;
  88941. this.i2e21 = NaN;
  88942. this.i2e22 = NaN;
  88943. this.ax1 = NaN;
  88944. this.ay1 = NaN;
  88945. this.az1 = NaN;
  88946. this.ax2 = NaN;
  88947. this.ay2 = NaN;
  88948. this.az2 = NaN;
  88949. this.ax3 = NaN;
  88950. this.ay3 = NaN;
  88951. this.az3 = NaN;
  88952. this.a1x1 = NaN; // jacoians
  88953. this.a1y1 = NaN;
  88954. this.a1z1 = NaN;
  88955. this.a2x1 = NaN;
  88956. this.a2y1 = NaN;
  88957. this.a2z1 = NaN;
  88958. this.a1x2 = NaN;
  88959. this.a1y2 = NaN;
  88960. this.a1z2 = NaN;
  88961. this.a2x2 = NaN;
  88962. this.a2y2 = NaN;
  88963. this.a2z2 = NaN;
  88964. this.a1x3 = NaN;
  88965. this.a1y3 = NaN;
  88966. this.a1z3 = NaN;
  88967. this.a2x3 = NaN;
  88968. this.a2y3 = NaN;
  88969. this.a2z3 = NaN;
  88970. this.lowerLimit1 = NaN;
  88971. this.upperLimit1 = NaN;
  88972. this.limitVelocity1 = NaN;
  88973. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  88974. this.enableMotor1 = false;
  88975. this.motorSpeed1 = NaN;
  88976. this.maxMotorForce1 = NaN;
  88977. this.maxMotorImpulse1 = NaN;
  88978. this.lowerLimit2 = NaN;
  88979. this.upperLimit2 = NaN;
  88980. this.limitVelocity2 = NaN;
  88981. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  88982. this.enableMotor2 = false;
  88983. this.motorSpeed2 = NaN;
  88984. this.maxMotorForce2 = NaN;
  88985. this.maxMotorImpulse2 = NaN;
  88986. this.lowerLimit3 = NaN;
  88987. this.upperLimit3 = NaN;
  88988. this.limitVelocity3 = NaN;
  88989. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  88990. this.enableMotor3 = false;
  88991. this.motorSpeed3 = NaN;
  88992. this.maxMotorForce3 = NaN;
  88993. this.maxMotorImpulse3 = NaN;
  88994. this.k00 = NaN; // K = J*M*JT
  88995. this.k01 = NaN;
  88996. this.k02 = NaN;
  88997. this.k10 = NaN;
  88998. this.k11 = NaN;
  88999. this.k12 = NaN;
  89000. this.k20 = NaN;
  89001. this.k21 = NaN;
  89002. this.k22 = NaN;
  89003. this.kv00 = NaN; // diagonals without CFMs
  89004. this.kv11 = NaN;
  89005. this.kv22 = NaN;
  89006. this.dv00 = NaN; // ...inverted
  89007. this.dv11 = NaN;
  89008. this.dv22 = NaN;
  89009. this.d00 = NaN; // K^-1
  89010. this.d01 = NaN;
  89011. this.d02 = NaN;
  89012. this.d10 = NaN;
  89013. this.d11 = NaN;
  89014. this.d12 = NaN;
  89015. this.d20 = NaN;
  89016. this.d21 = NaN;
  89017. this.d22 = NaN;
  89018. this.limitMotor1 = limitMotor1;
  89019. this.limitMotor2 = limitMotor2;
  89020. this.limitMotor3 = limitMotor3;
  89021. this.b1 = joint.body1;
  89022. this.b2 = joint.body2;
  89023. this.a1 = this.b1.angularVelocity;
  89024. this.a2 = this.b2.angularVelocity;
  89025. this.i1 = this.b1.inverseInertia;
  89026. this.i2 = this.b2.inverseInertia;
  89027. this.limitImpulse1 = 0;
  89028. this.motorImpulse1 = 0;
  89029. this.limitImpulse2 = 0;
  89030. this.motorImpulse2 = 0;
  89031. this.limitImpulse3 = 0;
  89032. this.motorImpulse3 = 0;
  89033. }
  89034. OIMO.Rotational3Constraint.prototype = {
  89035. constructor: OIMO.Rotational3Constraint,
  89036. preSolve: function (timeStep, invTimeStep) {
  89037. this.ax1 = this.limitMotor1.axis.x;
  89038. this.ay1 = this.limitMotor1.axis.y;
  89039. this.az1 = this.limitMotor1.axis.z;
  89040. this.ax2 = this.limitMotor2.axis.x;
  89041. this.ay2 = this.limitMotor2.axis.y;
  89042. this.az2 = this.limitMotor2.axis.z;
  89043. this.ax3 = this.limitMotor3.axis.x;
  89044. this.ay3 = this.limitMotor3.axis.y;
  89045. this.az3 = this.limitMotor3.axis.z;
  89046. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  89047. this.upperLimit1 = this.limitMotor1.upperLimit;
  89048. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  89049. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  89050. this.enableMotor1 = this.maxMotorForce1 > 0;
  89051. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  89052. this.upperLimit2 = this.limitMotor2.upperLimit;
  89053. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  89054. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  89055. this.enableMotor2 = this.maxMotorForce2 > 0;
  89056. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  89057. this.upperLimit3 = this.limitMotor3.upperLimit;
  89058. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  89059. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  89060. this.enableMotor3 = this.maxMotorForce3 > 0;
  89061. var ti1 = this.i1.elements;
  89062. var ti2 = this.i2.elements;
  89063. this.i1e00 = ti1[0];
  89064. this.i1e01 = ti1[1];
  89065. this.i1e02 = ti1[2];
  89066. this.i1e10 = ti1[3];
  89067. this.i1e11 = ti1[4];
  89068. this.i1e12 = ti1[5];
  89069. this.i1e20 = ti1[6];
  89070. this.i1e21 = ti1[7];
  89071. this.i1e22 = ti1[8];
  89072. this.i2e00 = ti2[0];
  89073. this.i2e01 = ti2[1];
  89074. this.i2e02 = ti2[2];
  89075. this.i2e10 = ti2[3];
  89076. this.i2e11 = ti2[4];
  89077. this.i2e12 = ti2[5];
  89078. this.i2e20 = ti2[6];
  89079. this.i2e21 = ti2[7];
  89080. this.i2e22 = ti2[8];
  89081. var frequency1 = this.limitMotor1.frequency;
  89082. var frequency2 = this.limitMotor2.frequency;
  89083. var frequency3 = this.limitMotor3.frequency;
  89084. var enableSpring1 = frequency1 > 0;
  89085. var enableSpring2 = frequency2 > 0;
  89086. var enableSpring3 = frequency3 > 0;
  89087. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  89088. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  89089. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  89090. var angle1 = this.limitMotor1.angle;
  89091. if (enableLimit1) {
  89092. if (this.lowerLimit1 == this.upperLimit1) {
  89093. if (this.limitState1 != 0) {
  89094. this.limitState1 = 0;
  89095. this.limitImpulse1 = 0;
  89096. }
  89097. this.limitVelocity1 = this.lowerLimit1 - angle1;
  89098. } else if (angle1 < this.lowerLimit1) {
  89099. if (this.limitState1 != -1) {
  89100. this.limitState1 = -1;
  89101. this.limitImpulse1 = 0;
  89102. }
  89103. this.limitVelocity1 = this.lowerLimit1 - angle1;
  89104. } else if (angle1 > this.upperLimit1) {
  89105. if (this.limitState1 != 1) {
  89106. this.limitState1 = 1;
  89107. this.limitImpulse1 = 0;
  89108. }
  89109. this.limitVelocity1 = this.upperLimit1 - angle1;
  89110. } else {
  89111. this.limitState1 = 2;
  89112. this.limitImpulse1 = 0;
  89113. this.limitVelocity1 = 0;
  89114. }
  89115. if (!enableSpring1) {
  89116. if (this.limitVelocity1 > 0.02) this.limitVelocity1 -= 0.02;
  89117. else if (this.limitVelocity1 < -0.02) this.limitVelocity1 += 0.02;
  89118. else this.limitVelocity1 = 0;
  89119. }
  89120. } else {
  89121. this.limitState1 = 2;
  89122. this.limitImpulse1 = 0;
  89123. }
  89124. var angle2 = this.limitMotor2.angle;
  89125. if (enableLimit2) {
  89126. if (this.lowerLimit2 == this.upperLimit2) {
  89127. if (this.limitState2 != 0) {
  89128. this.limitState2 = 0;
  89129. this.limitImpulse2 = 0;
  89130. }
  89131. this.limitVelocity2 = this.lowerLimit2 - angle2;
  89132. } else if (angle2 < this.lowerLimit2) {
  89133. if (this.limitState2 != -1) {
  89134. this.limitState2 = -1;
  89135. this.limitImpulse2 = 0;
  89136. }
  89137. this.limitVelocity2 = this.lowerLimit2 - angle2;
  89138. } else if (angle2 > this.upperLimit2) {
  89139. if (this.limitState2 != 1) {
  89140. this.limitState2 = 1;
  89141. this.limitImpulse2 = 0;
  89142. }
  89143. this.limitVelocity2 = this.upperLimit2 - angle2;
  89144. } else {
  89145. this.limitState2 = 2;
  89146. this.limitImpulse2 = 0;
  89147. this.limitVelocity2 = 0;
  89148. }
  89149. if (!enableSpring2) {
  89150. if (this.limitVelocity2 > 0.02) this.limitVelocity2 -= 0.02;
  89151. else if (this.limitVelocity2 < -0.02) this.limitVelocity2 += 0.02;
  89152. else this.limitVelocity2 = 0;
  89153. }
  89154. } else {
  89155. this.limitState2 = 2;
  89156. this.limitImpulse2 = 0;
  89157. }
  89158. var angle3 = this.limitMotor3.angle;
  89159. if (enableLimit3) {
  89160. if (this.lowerLimit3 == this.upperLimit3) {
  89161. if (this.limitState3 != 0) {
  89162. this.limitState3 = 0;
  89163. this.limitImpulse3 = 0;
  89164. }
  89165. this.limitVelocity3 = this.lowerLimit3 - angle3;
  89166. } else if (angle3 < this.lowerLimit3) {
  89167. if (this.limitState3 != -1) {
  89168. this.limitState3 = -1;
  89169. this.limitImpulse3 = 0;
  89170. }
  89171. this.limitVelocity3 = this.lowerLimit3 - angle3;
  89172. } else if (angle3 > this.upperLimit3) {
  89173. if (this.limitState3 != 1) {
  89174. this.limitState3 = 1;
  89175. this.limitImpulse3 = 0;
  89176. }
  89177. this.limitVelocity3 = this.upperLimit3 - angle3;
  89178. } else {
  89179. this.limitState3 = 2;
  89180. this.limitImpulse3 = 0;
  89181. this.limitVelocity3 = 0;
  89182. }
  89183. if (!enableSpring3) {
  89184. if (this.limitVelocity3 > 0.02) this.limitVelocity3 -= 0.02;
  89185. else if (this.limitVelocity3 < -0.02) this.limitVelocity3 += 0.02;
  89186. else this.limitVelocity3 = 0;
  89187. }
  89188. } else {
  89189. this.limitState3 = 2;
  89190. this.limitImpulse3 = 0;
  89191. }
  89192. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  89193. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  89194. } else {
  89195. this.motorImpulse1 = 0;
  89196. this.maxMotorImpulse1 = 0;
  89197. }
  89198. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  89199. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  89200. } else {
  89201. this.motorImpulse2 = 0;
  89202. this.maxMotorImpulse2 = 0;
  89203. }
  89204. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  89205. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  89206. } else {
  89207. this.motorImpulse3 = 0;
  89208. this.maxMotorImpulse3 = 0;
  89209. }
  89210. // build jacobians
  89211. this.a1x1 = this.ax1 * this.i1e00 + this.ay1 * this.i1e01 + this.az1 * this.i1e02;
  89212. this.a1y1 = this.ax1 * this.i1e10 + this.ay1 * this.i1e11 + this.az1 * this.i1e12;
  89213. this.a1z1 = this.ax1 * this.i1e20 + this.ay1 * this.i1e21 + this.az1 * this.i1e22;
  89214. this.a2x1 = this.ax1 * this.i2e00 + this.ay1 * this.i2e01 + this.az1 * this.i2e02;
  89215. this.a2y1 = this.ax1 * this.i2e10 + this.ay1 * this.i2e11 + this.az1 * this.i2e12;
  89216. this.a2z1 = this.ax1 * this.i2e20 + this.ay1 * this.i2e21 + this.az1 * this.i2e22;
  89217. this.a1x2 = this.ax2 * this.i1e00 + this.ay2 * this.i1e01 + this.az2 * this.i1e02;
  89218. this.a1y2 = this.ax2 * this.i1e10 + this.ay2 * this.i1e11 + this.az2 * this.i1e12;
  89219. this.a1z2 = this.ax2 * this.i1e20 + this.ay2 * this.i1e21 + this.az2 * this.i1e22;
  89220. this.a2x2 = this.ax2 * this.i2e00 + this.ay2 * this.i2e01 + this.az2 * this.i2e02;
  89221. this.a2y2 = this.ax2 * this.i2e10 + this.ay2 * this.i2e11 + this.az2 * this.i2e12;
  89222. this.a2z2 = this.ax2 * this.i2e20 + this.ay2 * this.i2e21 + this.az2 * this.i2e22;
  89223. this.a1x3 = this.ax3 * this.i1e00 + this.ay3 * this.i1e01 + this.az3 * this.i1e02;
  89224. this.a1y3 = this.ax3 * this.i1e10 + this.ay3 * this.i1e11 + this.az3 * this.i1e12;
  89225. this.a1z3 = this.ax3 * this.i1e20 + this.ay3 * this.i1e21 + this.az3 * this.i1e22;
  89226. this.a2x3 = this.ax3 * this.i2e00 + this.ay3 * this.i2e01 + this.az3 * this.i2e02;
  89227. this.a2y3 = this.ax3 * this.i2e10 + this.ay3 * this.i2e11 + this.az3 * this.i2e12;
  89228. this.a2z3 = this.ax3 * this.i2e20 + this.ay3 * this.i2e21 + this.az3 * this.i2e22;
  89229. // build an impulse matrix
  89230. this.k00 = this.ax1 * (this.a1x1 + this.a2x1) + this.ay1 * (this.a1y1 + this.a2y1) + this.az1 * (this.a1z1 + this.a2z1);
  89231. this.k01 = this.ax1 * (this.a1x2 + this.a2x2) + this.ay1 * (this.a1y2 + this.a2y2) + this.az1 * (this.a1z2 + this.a2z2);
  89232. this.k02 = this.ax1 * (this.a1x3 + this.a2x3) + this.ay1 * (this.a1y3 + this.a2y3) + this.az1 * (this.a1z3 + this.a2z3);
  89233. this.k10 = this.ax2 * (this.a1x1 + this.a2x1) + this.ay2 * (this.a1y1 + this.a2y1) + this.az2 * (this.a1z1 + this.a2z1);
  89234. this.k11 = this.ax2 * (this.a1x2 + this.a2x2) + this.ay2 * (this.a1y2 + this.a2y2) + this.az2 * (this.a1z2 + this.a2z2);
  89235. this.k12 = this.ax2 * (this.a1x3 + this.a2x3) + this.ay2 * (this.a1y3 + this.a2y3) + this.az2 * (this.a1z3 + this.a2z3);
  89236. this.k20 = this.ax3 * (this.a1x1 + this.a2x1) + this.ay3 * (this.a1y1 + this.a2y1) + this.az3 * (this.a1z1 + this.a2z1);
  89237. this.k21 = this.ax3 * (this.a1x2 + this.a2x2) + this.ay3 * (this.a1y2 + this.a2y2) + this.az3 * (this.a1z2 + this.a2z2);
  89238. this.k22 = this.ax3 * (this.a1x3 + this.a2x3) + this.ay3 * (this.a1y3 + this.a2y3) + this.az3 * (this.a1z3 + this.a2z3);
  89239. this.kv00 = this.k00;
  89240. this.kv11 = this.k11;
  89241. this.kv22 = this.k22;
  89242. this.dv00 = 1 / this.kv00;
  89243. this.dv11 = 1 / this.kv11;
  89244. this.dv22 = 1 / this.kv22;
  89245. if (enableSpring1 && this.limitState1 != 2) {
  89246. var omega = 6.2831853 * frequency1;
  89247. var k = omega * omega * timeStep;
  89248. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  89249. this.cfm1 = this.kv00 * dmp;
  89250. this.limitVelocity1 *= k * dmp;
  89251. } else {
  89252. this.cfm1 = 0;
  89253. this.limitVelocity1 *= invTimeStep * 0.05;
  89254. }
  89255. if (enableSpring2 && this.limitState2 != 2) {
  89256. omega = 6.2831853 * frequency2;
  89257. k = omega * omega * timeStep;
  89258. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  89259. this.cfm2 = this.kv11 * dmp;
  89260. this.limitVelocity2 *= k * dmp;
  89261. } else {
  89262. this.cfm2 = 0;
  89263. this.limitVelocity2 *= invTimeStep * 0.05;
  89264. }
  89265. if (enableSpring3 && this.limitState3 != 2) {
  89266. omega = 6.2831853 * frequency3;
  89267. k = omega * omega * timeStep;
  89268. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  89269. this.cfm3 = this.kv22 * dmp;
  89270. this.limitVelocity3 *= k * dmp;
  89271. } else {
  89272. this.cfm3 = 0;
  89273. this.limitVelocity3 *= invTimeStep * 0.05;
  89274. }
  89275. this.k00 += this.cfm1;
  89276. this.k11 += this.cfm2;
  89277. this.k22 += this.cfm3;
  89278. var inv = 1 / (
  89279. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  89280. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  89281. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  89282. );
  89283. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  89284. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  89285. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  89286. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  89287. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  89288. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  89289. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  89290. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  89291. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  89292. this.limitImpulse1 *= 0.95;
  89293. this.motorImpulse1 *= 0.95;
  89294. this.limitImpulse2 *= 0.95;
  89295. this.motorImpulse2 *= 0.95;
  89296. this.limitImpulse3 *= 0.95;
  89297. this.motorImpulse3 *= 0.95;
  89298. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  89299. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  89300. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  89301. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  89302. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  89303. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  89304. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  89305. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  89306. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  89307. },
  89308. solve_: function () {
  89309. var rvx = this.a2.x - this.a1.x;
  89310. var rvy = this.a2.y - this.a1.y;
  89311. var rvz = this.a2.z - this.a1.z;
  89312. this.limitVelocity3 = 30;
  89313. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1 - this.limitVelocity1;
  89314. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2 - this.limitVelocity2;
  89315. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3 - this.limitVelocity3;
  89316. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  89317. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  89318. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  89319. this.limitImpulse1 += dLimitImpulse1;
  89320. this.limitImpulse2 += dLimitImpulse2;
  89321. this.limitImpulse3 += dLimitImpulse3;
  89322. this.a1.x += dLimitImpulse1 * this.a1x1 + dLimitImpulse2 * this.a1x2 + dLimitImpulse3 * this.a1x3;
  89323. this.a1.y += dLimitImpulse1 * this.a1y1 + dLimitImpulse2 * this.a1y2 + dLimitImpulse3 * this.a1y3;
  89324. this.a1.z += dLimitImpulse1 * this.a1z1 + dLimitImpulse2 * this.a1z2 + dLimitImpulse3 * this.a1z3;
  89325. this.a2.x -= dLimitImpulse1 * this.a2x1 + dLimitImpulse2 * this.a2x2 + dLimitImpulse3 * this.a2x3;
  89326. this.a2.y -= dLimitImpulse1 * this.a2y1 + dLimitImpulse2 * this.a2y2 + dLimitImpulse3 * this.a2y3;
  89327. this.a2.z -= dLimitImpulse1 * this.a2z1 + dLimitImpulse2 * this.a2z2 + dLimitImpulse3 * this.a2z3;
  89328. },
  89329. solve: function () {
  89330. var rvx = this.a2.x - this.a1.x;
  89331. var rvy = this.a2.y - this.a1.y;
  89332. var rvz = this.a2.z - this.a1.z;
  89333. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  89334. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  89335. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  89336. var oldMotorImpulse1 = this.motorImpulse1;
  89337. var oldMotorImpulse2 = this.motorImpulse2;
  89338. var oldMotorImpulse3 = this.motorImpulse3;
  89339. var dMotorImpulse1 = 0;
  89340. var dMotorImpulse2 = 0;
  89341. var dMotorImpulse3 = 0;
  89342. if (this.enableMotor1) {
  89343. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  89344. this.motorImpulse1 += dMotorImpulse1;
  89345. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  89346. this.motorImpulse1 = this.maxMotorImpulse1;
  89347. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  89348. this.motorImpulse1 = -this.maxMotorImpulse1;
  89349. }
  89350. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  89351. }
  89352. if (this.enableMotor2) {
  89353. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  89354. this.motorImpulse2 += dMotorImpulse2;
  89355. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  89356. this.motorImpulse2 = this.maxMotorImpulse2;
  89357. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  89358. this.motorImpulse2 = -this.maxMotorImpulse2;
  89359. }
  89360. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  89361. }
  89362. if (this.enableMotor3) {
  89363. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  89364. this.motorImpulse3 += dMotorImpulse3;
  89365. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  89366. this.motorImpulse3 = this.maxMotorImpulse3;
  89367. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  89368. this.motorImpulse3 = -this.maxMotorImpulse3;
  89369. }
  89370. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  89371. }
  89372. // apply motor impulse to relative velocity
  89373. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  89374. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  89375. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  89376. // subtract target velocity and applied impulse
  89377. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  89378. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  89379. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  89380. var oldLimitImpulse1 = this.limitImpulse1;
  89381. var oldLimitImpulse2 = this.limitImpulse2;
  89382. var oldLimitImpulse3 = this.limitImpulse3;
  89383. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  89384. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  89385. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  89386. this.limitImpulse1 += dLimitImpulse1;
  89387. this.limitImpulse2 += dLimitImpulse2;
  89388. this.limitImpulse3 += dLimitImpulse3;
  89389. // clamp
  89390. var clampState = 0;
  89391. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  89392. dLimitImpulse1 = -oldLimitImpulse1;
  89393. rvn2 += dLimitImpulse1 * this.k10;
  89394. rvn3 += dLimitImpulse1 * this.k20;
  89395. clampState |= 1;
  89396. }
  89397. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  89398. dLimitImpulse2 = -oldLimitImpulse2;
  89399. rvn1 += dLimitImpulse2 * this.k01;
  89400. rvn3 += dLimitImpulse2 * this.k21;
  89401. clampState |= 2;
  89402. }
  89403. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  89404. dLimitImpulse3 = -oldLimitImpulse3;
  89405. rvn1 += dLimitImpulse3 * this.k02;
  89406. rvn2 += dLimitImpulse3 * this.k12;
  89407. clampState |= 4;
  89408. }
  89409. // update un-clamped impulse
  89410. // TODO: isolate division
  89411. var det;
  89412. switch (clampState) {
  89413. case 1: // update 2 3
  89414. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  89415. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  89416. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  89417. break;
  89418. case 2: // update 1 3
  89419. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  89420. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  89421. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  89422. break;
  89423. case 3: // update 3
  89424. dLimitImpulse3 = rvn3 / this.k22;
  89425. break;
  89426. case 4: // update 1 2
  89427. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  89428. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  89429. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  89430. break;
  89431. case 5: // update 2
  89432. dLimitImpulse2 = rvn2 / this.k11;
  89433. break;
  89434. case 6: // update 1
  89435. dLimitImpulse1 = rvn1 / this.k00;
  89436. break;
  89437. }
  89438. this.limitImpulse1 = dLimitImpulse1 + oldLimitImpulse1;
  89439. this.limitImpulse2 = dLimitImpulse2 + oldLimitImpulse2;
  89440. this.limitImpulse3 = dLimitImpulse3 + oldLimitImpulse3;
  89441. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  89442. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  89443. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  89444. // apply impulse
  89445. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  89446. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  89447. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  89448. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  89449. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  89450. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  89451. rvx = this.a2.x - this.a1.x;
  89452. rvy = this.a2.y - this.a1.y;
  89453. rvz = this.a2.z - this.a1.z;
  89454. rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  89455. }
  89456. }
  89457. /**
  89458. * A rotational constraint for various joints.
  89459. * @author saharan
  89460. */
  89461. OIMO.RotationalConstraint = function (joint, limitMotor) {
  89462. this.cfm = NaN;
  89463. this.i1e00 = NaN;
  89464. this.i1e01 = NaN;
  89465. this.i1e02 = NaN;
  89466. this.i1e10 = NaN;
  89467. this.i1e11 = NaN;
  89468. this.i1e12 = NaN;
  89469. this.i1e20 = NaN;
  89470. this.i1e21 = NaN;
  89471. this.i1e22 = NaN;
  89472. this.i2e00 = NaN;
  89473. this.i2e01 = NaN;
  89474. this.i2e02 = NaN;
  89475. this.i2e10 = NaN;
  89476. this.i2e11 = NaN;
  89477. this.i2e12 = NaN;
  89478. this.i2e20 = NaN;
  89479. this.i2e21 = NaN;
  89480. this.i2e22 = NaN;
  89481. this.motorDenom = NaN;
  89482. this.invMotorDenom = NaN;
  89483. this.invDenom = NaN;
  89484. this.ax = NaN;
  89485. this.ay = NaN;
  89486. this.az = NaN;
  89487. this.a1x = NaN;
  89488. this.a1y = NaN;
  89489. this.a1z = NaN;
  89490. this.a2x = NaN;
  89491. this.a2y = NaN;
  89492. this.a2z = NaN;
  89493. this.enableLimit = false;
  89494. this.lowerLimit = NaN;
  89495. this.upperLimit = NaN;
  89496. this.limitVelocity = NaN;
  89497. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  89498. this.enableMotor = false;
  89499. this.motorSpeed = NaN;
  89500. this.maxMotorForce = NaN;
  89501. this.maxMotorImpulse = NaN;
  89502. this.limitMotor = limitMotor;
  89503. this.b1 = joint.body1;
  89504. this.b2 = joint.body2;
  89505. this.a1 = this.b1.angularVelocity;
  89506. this.a2 = this.b2.angularVelocity;
  89507. this.i1 = this.b1.inverseInertia;
  89508. this.i2 = this.b2.inverseInertia;
  89509. this.limitImpulse = 0;
  89510. this.motorImpulse = 0;
  89511. }
  89512. OIMO.RotationalConstraint.prototype = {
  89513. constructor: OIMO.RotationalConstraint,
  89514. preSolve: function (timeStep, invTimeStep) {
  89515. this.ax = this.limitMotor.axis.x;
  89516. this.ay = this.limitMotor.axis.y;
  89517. this.az = this.limitMotor.axis.z;
  89518. this.lowerLimit = this.limitMotor.lowerLimit;
  89519. this.upperLimit = this.limitMotor.upperLimit;
  89520. this.motorSpeed = this.limitMotor.motorSpeed;
  89521. this.maxMotorForce = this.limitMotor.maxMotorForce;
  89522. this.enableMotor = this.maxMotorForce > 0;
  89523. var ti1 = this.i1.elements;
  89524. var ti2 = this.i2.elements;
  89525. this.i1e00 = ti1[0];
  89526. this.i1e01 = ti1[1];
  89527. this.i1e02 = ti1[2];
  89528. this.i1e10 = ti1[3];
  89529. this.i1e11 = ti1[4];
  89530. this.i1e12 = ti1[5];
  89531. this.i1e20 = ti1[6];
  89532. this.i1e21 = ti1[7];
  89533. this.i1e22 = ti1[8];
  89534. this.i2e00 = ti2[0];
  89535. this.i2e01 = ti2[1];
  89536. this.i2e02 = ti2[2];
  89537. this.i2e10 = ti2[3];
  89538. this.i2e11 = ti2[4];
  89539. this.i2e12 = ti2[5];
  89540. this.i2e20 = ti2[6];
  89541. this.i2e21 = ti2[7];
  89542. this.i2e22 = ti2[8];
  89543. var frequency = this.limitMotor.frequency;
  89544. var enableSpring = frequency > 0;
  89545. var enableLimit = this.lowerLimit <= this.upperLimit;
  89546. var angle = this.limitMotor.angle;
  89547. if (enableLimit) {
  89548. if (this.lowerLimit == this.upperLimit) {
  89549. if (this.limitState != 0) {
  89550. this.limitState = 0;
  89551. this.limitImpulse = 0;
  89552. }
  89553. this.limitVelocity = this.lowerLimit - angle;
  89554. } else if (angle < this.lowerLimit) {
  89555. if (this.limitState != -1) {
  89556. this.limitState = -1;
  89557. this.limitImpulse = 0;
  89558. }
  89559. this.limitVelocity = this.lowerLimit - angle;
  89560. } else if (angle > this.upperLimit) {
  89561. if (this.limitState != 1) {
  89562. this.limitState = 1;
  89563. this.limitImpulse = 0;
  89564. }
  89565. this.limitVelocity = this.upperLimit - angle;
  89566. } else {
  89567. this.limitState = 2;
  89568. this.limitImpulse = 0;
  89569. this.limitVelocity = 0;
  89570. }
  89571. if (!enableSpring) {
  89572. if (this.limitVelocity > 0.02) this.limitVelocity -= 0.02;
  89573. else if (this.limitVelocity < -0.02) this.limitVelocity += 0.02;
  89574. else this.limitVelocity = 0;
  89575. }
  89576. } else {
  89577. this.limitState = 2;
  89578. this.limitImpulse = 0;
  89579. }
  89580. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  89581. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  89582. } else {
  89583. this.motorImpulse = 0;
  89584. this.maxMotorImpulse = 0;
  89585. }
  89586. this.a1x = this.ax * this.i1e00 + this.ay * this.i1e01 + this.az * this.i1e02;
  89587. this.a1y = this.ax * this.i1e10 + this.ay * this.i1e11 + this.az * this.i1e12;
  89588. this.a1z = this.ax * this.i1e20 + this.ay * this.i1e21 + this.az * this.i1e22;
  89589. this.a2x = this.ax * this.i2e00 + this.ay * this.i2e01 + this.az * this.i2e02;
  89590. this.a2y = this.ax * this.i2e10 + this.ay * this.i2e11 + this.az * this.i2e12;
  89591. this.a2z = this.ax * this.i2e20 + this.ay * this.i2e21 + this.az * this.i2e22;
  89592. this.motorDenom = this.ax * (this.a1x + this.a2x) + this.ay * (this.a1y + this.a2y) + this.az * (this.a1z + this.a2z);
  89593. this.invMotorDenom = 1 / this.motorDenom;
  89594. if (enableSpring && this.limitState != 2) {
  89595. var omega = 6.2831853 * frequency;
  89596. var k = omega * omega * timeStep;
  89597. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  89598. this.cfm = this.motorDenom * dmp;
  89599. this.limitVelocity *= k * dmp;
  89600. } else {
  89601. this.cfm = 0;
  89602. this.limitVelocity *= invTimeStep * 0.05;
  89603. }
  89604. this.invDenom = 1 / (this.motorDenom + this.cfm);
  89605. this.limitImpulse *= 0.95;
  89606. this.motorImpulse *= 0.95;
  89607. var totalImpulse = this.limitImpulse + this.motorImpulse;
  89608. this.a1.x += totalImpulse * this.a1x;
  89609. this.a1.y += totalImpulse * this.a1y;
  89610. this.a1.z += totalImpulse * this.a1z;
  89611. this.a2.x -= totalImpulse * this.a2x;
  89612. this.a2.y -= totalImpulse * this.a2y;
  89613. this.a2.z -= totalImpulse * this.a2z;
  89614. },
  89615. solve: function () {
  89616. 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);
  89617. // motor part
  89618. var newMotorImpulse;
  89619. if (this.enableMotor) {
  89620. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  89621. var oldMotorImpulse = this.motorImpulse;
  89622. this.motorImpulse += newMotorImpulse;
  89623. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  89624. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  89625. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  89626. rvn -= newMotorImpulse * this.motorDenom;
  89627. } else newMotorImpulse = 0;
  89628. // limit part
  89629. var newLimitImpulse;
  89630. if (this.limitState != 2) {
  89631. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  89632. var oldLimitImpulse = this.limitImpulse;
  89633. this.limitImpulse += newLimitImpulse;
  89634. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  89635. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  89636. } else newLimitImpulse = 0;
  89637. var totalImpulse = newLimitImpulse + newMotorImpulse;
  89638. this.a1.x += totalImpulse * this.a1x;
  89639. this.a1.y += totalImpulse * this.a1y;
  89640. this.a1.z += totalImpulse * this.a1z;
  89641. this.a2.x -= totalImpulse * this.a2x;
  89642. this.a2.y -= totalImpulse * this.a2y;
  89643. this.a2.z -= totalImpulse * this.a2z;
  89644. }
  89645. }
  89646. /**
  89647. * A three-axis translational constraint for various joints.
  89648. * @author saharan
  89649. */
  89650. OIMO.Translational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  89651. this.m1 = NaN;
  89652. this.m2 = NaN;
  89653. this.i1e00 = NaN;
  89654. this.i1e01 = NaN;
  89655. this.i1e02 = NaN;
  89656. this.i1e10 = NaN;
  89657. this.i1e11 = NaN;
  89658. this.i1e12 = NaN;
  89659. this.i1e20 = NaN;
  89660. this.i1e21 = NaN;
  89661. this.i1e22 = NaN;
  89662. this.i2e00 = NaN;
  89663. this.i2e01 = NaN;
  89664. this.i2e02 = NaN;
  89665. this.i2e10 = NaN;
  89666. this.i2e11 = NaN;
  89667. this.i2e12 = NaN;
  89668. this.i2e20 = NaN;
  89669. this.i2e21 = NaN;
  89670. this.i2e22 = NaN;
  89671. this.ax1 = NaN;
  89672. this.ay1 = NaN;
  89673. this.az1 = NaN;
  89674. this.ax2 = NaN;
  89675. this.ay2 = NaN;
  89676. this.az2 = NaN;
  89677. this.ax3 = NaN;
  89678. this.ay3 = NaN;
  89679. this.az3 = NaN;
  89680. this.r1x = NaN;
  89681. this.r1y = NaN;
  89682. this.r1z = NaN;
  89683. this.r2x = NaN;
  89684. this.r2y = NaN;
  89685. this.r2z = NaN;
  89686. this.t1x1 = NaN;// jacobians
  89687. this.t1y1 = NaN;
  89688. this.t1z1 = NaN;
  89689. this.t2x1 = NaN;
  89690. this.t2y1 = NaN;
  89691. this.t2z1 = NaN;
  89692. this.l1x1 = NaN;
  89693. this.l1y1 = NaN;
  89694. this.l1z1 = NaN;
  89695. this.l2x1 = NaN;
  89696. this.l2y1 = NaN;
  89697. this.l2z1 = NaN;
  89698. this.a1x1 = NaN;
  89699. this.a1y1 = NaN;
  89700. this.a1z1 = NaN;
  89701. this.a2x1 = NaN;
  89702. this.a2y1 = NaN;
  89703. this.a2z1 = NaN;
  89704. this.t1x2 = NaN;
  89705. this.t1y2 = NaN;
  89706. this.t1z2 = NaN;
  89707. this.t2x2 = NaN;
  89708. this.t2y2 = NaN;
  89709. this.t2z2 = NaN;
  89710. this.l1x2 = NaN;
  89711. this.l1y2 = NaN;
  89712. this.l1z2 = NaN;
  89713. this.l2x2 = NaN;
  89714. this.l2y2 = NaN;
  89715. this.l2z2 = NaN;
  89716. this.a1x2 = NaN;
  89717. this.a1y2 = NaN;
  89718. this.a1z2 = NaN;
  89719. this.a2x2 = NaN;
  89720. this.a2y2 = NaN;
  89721. this.a2z2 = NaN;
  89722. this.t1x3 = NaN;
  89723. this.t1y3 = NaN;
  89724. this.t1z3 = NaN;
  89725. this.t2x3 = NaN;
  89726. this.t2y3 = NaN;
  89727. this.t2z3 = NaN;
  89728. this.l1x3 = NaN;
  89729. this.l1y3 = NaN;
  89730. this.l1z3 = NaN;
  89731. this.l2x3 = NaN;
  89732. this.l2y3 = NaN;
  89733. this.l2z3 = NaN;
  89734. this.a1x3 = NaN;
  89735. this.a1y3 = NaN;
  89736. this.a1z3 = NaN;
  89737. this.a2x3 = NaN;
  89738. this.a2y3 = NaN;
  89739. this.a2z3 = NaN;
  89740. this.lowerLimit1 = NaN;
  89741. this.upperLimit1 = NaN;
  89742. this.limitVelocity1 = NaN;
  89743. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  89744. this.enableMotor1 = false;
  89745. this.motorSpeed1 = NaN;
  89746. this.maxMotorForce1 = NaN;
  89747. this.maxMotorImpulse1 = NaN;
  89748. this.lowerLimit2 = NaN;
  89749. this.upperLimit2 = NaN;
  89750. this.limitVelocity2 = NaN;
  89751. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  89752. this.enableMotor2 = false;
  89753. this.motorSpeed2 = NaN;
  89754. this.maxMotorForce2 = NaN;
  89755. this.maxMotorImpulse2 = NaN;
  89756. this.lowerLimit3 = NaN;
  89757. this.upperLimit3 = NaN;
  89758. this.limitVelocity3 = NaN;
  89759. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  89760. this.enableMotor3 = false;
  89761. this.motorSpeed3 = NaN;
  89762. this.maxMotorForce3 = NaN;
  89763. this.maxMotorImpulse3 = NaN;
  89764. this.k00 = NaN; // K = J*M*JT
  89765. this.k01 = NaN;
  89766. this.k02 = NaN;
  89767. this.k10 = NaN;
  89768. this.k11 = NaN;
  89769. this.k12 = NaN;
  89770. this.k20 = NaN;
  89771. this.k21 = NaN;
  89772. this.k22 = NaN;
  89773. this.kv00 = NaN; // diagonals without CFMs
  89774. this.kv11 = NaN;
  89775. this.kv22 = NaN;
  89776. this.dv00 = NaN; // ...inverted
  89777. this.dv11 = NaN;
  89778. this.dv22 = NaN;
  89779. this.d00 = NaN; // K^-1
  89780. this.d01 = NaN;
  89781. this.d02 = NaN;
  89782. this.d10 = NaN;
  89783. this.d11 = NaN;
  89784. this.d12 = NaN;
  89785. this.d20 = NaN;
  89786. this.d21 = NaN;
  89787. this.d22 = NaN;
  89788. this.limitMotor1 = limitMotor1;
  89789. this.limitMotor2 = limitMotor2;
  89790. this.limitMotor3 = limitMotor3;
  89791. this.b1 = joint.body1;
  89792. this.b2 = joint.body2;
  89793. this.p1 = joint.anchorPoint1;
  89794. this.p2 = joint.anchorPoint2;
  89795. this.r1 = joint.relativeAnchorPoint1;
  89796. this.r2 = joint.relativeAnchorPoint2;
  89797. this.l1 = this.b1.linearVelocity;
  89798. this.l2 = this.b2.linearVelocity;
  89799. this.a1 = this.b1.angularVelocity;
  89800. this.a2 = this.b2.angularVelocity;
  89801. this.i1 = this.b1.inverseInertia;
  89802. this.i2 = this.b2.inverseInertia;
  89803. this.limitImpulse1 = 0;
  89804. this.motorImpulse1 = 0;
  89805. this.limitImpulse2 = 0;
  89806. this.motorImpulse2 = 0;
  89807. this.limitImpulse3 = 0;
  89808. this.motorImpulse3 = 0;
  89809. this.cfm1 = 0;// Constraint Force Mixing
  89810. this.cfm2 = 0;
  89811. this.cfm3 = 0;
  89812. this.weight = -1;
  89813. }
  89814. OIMO.Translational3Constraint.prototype = {
  89815. constructor: OIMO.Translational3Constraint,
  89816. preSolve: function (timeStep, invTimeStep) {
  89817. this.ax1 = this.limitMotor1.axis.x;
  89818. this.ay1 = this.limitMotor1.axis.y;
  89819. this.az1 = this.limitMotor1.axis.z;
  89820. this.ax2 = this.limitMotor2.axis.x;
  89821. this.ay2 = this.limitMotor2.axis.y;
  89822. this.az2 = this.limitMotor2.axis.z;
  89823. this.ax3 = this.limitMotor3.axis.x;
  89824. this.ay3 = this.limitMotor3.axis.y;
  89825. this.az3 = this.limitMotor3.axis.z;
  89826. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  89827. this.upperLimit1 = this.limitMotor1.upperLimit;
  89828. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  89829. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  89830. this.enableMotor1 = this.maxMotorForce1 > 0;
  89831. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  89832. this.upperLimit2 = this.limitMotor2.upperLimit;
  89833. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  89834. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  89835. this.enableMotor2 = this.maxMotorForce2 > 0;
  89836. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  89837. this.upperLimit3 = this.limitMotor3.upperLimit;
  89838. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  89839. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  89840. this.enableMotor3 = this.maxMotorForce3 > 0;
  89841. this.m1 = this.b1.inverseMass;
  89842. this.m2 = this.b2.inverseMass;
  89843. var ti1 = this.i1.elements;
  89844. var ti2 = this.i2.elements;
  89845. this.i1e00 = ti1[0];
  89846. this.i1e01 = ti1[1];
  89847. this.i1e02 = ti1[2];
  89848. this.i1e10 = ti1[3];
  89849. this.i1e11 = ti1[4];
  89850. this.i1e12 = ti1[5];
  89851. this.i1e20 = ti1[6];
  89852. this.i1e21 = ti1[7];
  89853. this.i1e22 = ti1[8];
  89854. this.i2e00 = ti2[0];
  89855. this.i2e01 = ti2[1];
  89856. this.i2e02 = ti2[2];
  89857. this.i2e10 = ti2[3];
  89858. this.i2e11 = ti2[4];
  89859. this.i2e12 = ti2[5];
  89860. this.i2e20 = ti2[6];
  89861. this.i2e21 = ti2[7];
  89862. this.i2e22 = ti2[8];
  89863. var dx = this.p2.x - this.p1.x;
  89864. var dy = this.p2.y - this.p1.y;
  89865. var dz = this.p2.z - this.p1.z;
  89866. var d1 = dx * this.ax1 + dy * this.ay1 + dz * this.az1;
  89867. var d2 = dx * this.ax2 + dy * this.ay2 + dz * this.az2;
  89868. var d3 = dx * this.ax3 + dy * this.ay3 + dz * this.az3;
  89869. var frequency1 = this.limitMotor1.frequency;
  89870. var frequency2 = this.limitMotor2.frequency;
  89871. var frequency3 = this.limitMotor3.frequency;
  89872. var enableSpring1 = frequency1 > 0;
  89873. var enableSpring2 = frequency2 > 0;
  89874. var enableSpring3 = frequency3 > 0;
  89875. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  89876. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  89877. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  89878. // for stability
  89879. if (enableSpring1 && d1 > 20 || d1 < -20) {
  89880. enableSpring1 = false;
  89881. }
  89882. if (enableSpring2 && d2 > 20 || d2 < -20) {
  89883. enableSpring2 = false;
  89884. }
  89885. if (enableSpring3 && d3 > 20 || d3 < -20) {
  89886. enableSpring3 = false;
  89887. }
  89888. if (enableLimit1) {
  89889. if (this.lowerLimit1 == this.upperLimit1) {
  89890. if (this.limitState1 != 0) {
  89891. this.limitState1 = 0;
  89892. this.limitImpulse1 = 0;
  89893. }
  89894. this.limitVelocity1 = this.lowerLimit1 - d1;
  89895. if (!enableSpring1) d1 = this.lowerLimit1;
  89896. } else if (d1 < this.lowerLimit1) {
  89897. if (this.limitState1 != -1) {
  89898. this.limitState1 = -1;
  89899. this.limitImpulse1 = 0;
  89900. }
  89901. this.limitVelocity1 = this.lowerLimit1 - d1;
  89902. if (!enableSpring1) d1 = this.lowerLimit1;
  89903. } else if (d1 > this.upperLimit1) {
  89904. if (this.limitState1 != 1) {
  89905. this.limitState1 = 1;
  89906. this.limitImpulse1 = 0;
  89907. }
  89908. this.limitVelocity1 = this.upperLimit1 - d1;
  89909. if (!enableSpring1) d1 = this.upperLimit1;
  89910. } else {
  89911. this.limitState1 = 2;
  89912. this.limitImpulse1 = 0;
  89913. this.limitVelocity1 = 0;
  89914. }
  89915. if (!enableSpring1) {
  89916. if (this.limitVelocity1 > 0.005) this.limitVelocity1 -= 0.005;
  89917. else if (this.limitVelocity1 < -0.005) this.limitVelocity1 += 0.005;
  89918. else this.limitVelocity1 = 0;
  89919. }
  89920. } else {
  89921. this.limitState1 = 2;
  89922. this.limitImpulse1 = 0;
  89923. }
  89924. if (enableLimit2) {
  89925. if (this.lowerLimit2 == this.upperLimit2) {
  89926. if (this.limitState2 != 0) {
  89927. this.limitState2 = 0;
  89928. this.limitImpulse2 = 0;
  89929. }
  89930. this.limitVelocity2 = this.lowerLimit2 - d2;
  89931. if (!enableSpring2) d2 = this.lowerLimit2;
  89932. } else if (d2 < this.lowerLimit2) {
  89933. if (this.limitState2 != -1) {
  89934. this.limitState2 = -1;
  89935. this.limitImpulse2 = 0;
  89936. }
  89937. this.limitVelocity2 = this.lowerLimit2 - d2;
  89938. if (!enableSpring2) d2 = this.lowerLimit2;
  89939. } else if (d2 > this.upperLimit2) {
  89940. if (this.limitState2 != 1) {
  89941. this.limitState2 = 1;
  89942. this.limitImpulse2 = 0;
  89943. }
  89944. this.limitVelocity2 = this.upperLimit2 - d2;
  89945. if (!enableSpring2) d2 = this.upperLimit2;
  89946. } else {
  89947. this.limitState2 = 2;
  89948. this.limitImpulse2 = 0;
  89949. this.limitVelocity2 = 0;
  89950. }
  89951. if (!enableSpring2) {
  89952. if (this.limitVelocity2 > 0.005) this.limitVelocity2 -= 0.005;
  89953. else if (this.limitVelocity2 < -0.005) this.limitVelocity2 += 0.005;
  89954. else this.limitVelocity2 = 0;
  89955. }
  89956. } else {
  89957. this.limitState2 = 2;
  89958. this.limitImpulse2 = 0;
  89959. }
  89960. if (enableLimit3) {
  89961. if (this.lowerLimit3 == this.upperLimit3) {
  89962. if (this.limitState3 != 0) {
  89963. this.limitState3 = 0;
  89964. this.limitImpulse3 = 0;
  89965. }
  89966. this.limitVelocity3 = this.lowerLimit3 - d3;
  89967. if (!enableSpring3) d3 = this.lowerLimit3;
  89968. } else if (d3 < this.lowerLimit3) {
  89969. if (this.limitState3 != -1) {
  89970. this.limitState3 = -1;
  89971. this.limitImpulse3 = 0;
  89972. }
  89973. this.limitVelocity3 = this.lowerLimit3 - d3;
  89974. if (!enableSpring3) d3 = this.lowerLimit3;
  89975. } else if (d3 > this.upperLimit3) {
  89976. if (this.limitState3 != 1) {
  89977. this.limitState3 = 1;
  89978. this.limitImpulse3 = 0;
  89979. }
  89980. this.limitVelocity3 = this.upperLimit3 - d3;
  89981. if (!enableSpring3) d3 = this.upperLimit3;
  89982. } else {
  89983. this.limitState3 = 2;
  89984. this.limitImpulse3 = 0;
  89985. this.limitVelocity3 = 0;
  89986. }
  89987. if (!enableSpring3) {
  89988. if (this.limitVelocity3 > 0.005) this.limitVelocity3 -= 0.005;
  89989. else if (this.limitVelocity3 < -0.005) this.limitVelocity3 += 0.005;
  89990. else this.limitVelocity3 = 0;
  89991. }
  89992. } else {
  89993. this.limitState3 = 2;
  89994. this.limitImpulse3 = 0;
  89995. }
  89996. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  89997. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  89998. } else {
  89999. this.motorImpulse1 = 0;
  90000. this.maxMotorImpulse1 = 0;
  90001. }
  90002. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  90003. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  90004. } else {
  90005. this.motorImpulse2 = 0;
  90006. this.maxMotorImpulse2 = 0;
  90007. }
  90008. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  90009. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  90010. } else {
  90011. this.motorImpulse3 = 0;
  90012. this.maxMotorImpulse3 = 0;
  90013. }
  90014. var rdx = d1 * this.ax1 + d2 * this.ax2 + d3 * this.ax2;
  90015. var rdy = d1 * this.ay1 + d2 * this.ay2 + d3 * this.ay2;
  90016. var rdz = d1 * this.az1 + d2 * this.az2 + d3 * this.az2;
  90017. var w1 = this.m2 / (this.m1 + this.m2);
  90018. if (this.weight >= 0) w1 = this.weight; // use given weight
  90019. var w2 = 1 - w1;
  90020. this.r1x = this.r1.x + rdx * w1;
  90021. this.r1y = this.r1.y + rdy * w1;
  90022. this.r1z = this.r1.z + rdz * w1;
  90023. this.r2x = this.r2.x - rdx * w2;
  90024. this.r2y = this.r2.y - rdy * w2;
  90025. this.r2z = this.r2.z - rdz * w2;
  90026. // build jacobians
  90027. this.t1x1 = this.r1y * this.az1 - this.r1z * this.ay1;
  90028. this.t1y1 = this.r1z * this.ax1 - this.r1x * this.az1;
  90029. this.t1z1 = this.r1x * this.ay1 - this.r1y * this.ax1;
  90030. this.t2x1 = this.r2y * this.az1 - this.r2z * this.ay1;
  90031. this.t2y1 = this.r2z * this.ax1 - this.r2x * this.az1;
  90032. this.t2z1 = this.r2x * this.ay1 - this.r2y * this.ax1;
  90033. this.l1x1 = this.ax1 * this.m1;
  90034. this.l1y1 = this.ay1 * this.m1;
  90035. this.l1z1 = this.az1 * this.m1;
  90036. this.l2x1 = this.ax1 * this.m2;
  90037. this.l2y1 = this.ay1 * this.m2;
  90038. this.l2z1 = this.az1 * this.m2;
  90039. this.a1x1 = this.t1x1 * this.i1e00 + this.t1y1 * this.i1e01 + this.t1z1 * this.i1e02;
  90040. this.a1y1 = this.t1x1 * this.i1e10 + this.t1y1 * this.i1e11 + this.t1z1 * this.i1e12;
  90041. this.a1z1 = this.t1x1 * this.i1e20 + this.t1y1 * this.i1e21 + this.t1z1 * this.i1e22;
  90042. this.a2x1 = this.t2x1 * this.i2e00 + this.t2y1 * this.i2e01 + this.t2z1 * this.i2e02;
  90043. this.a2y1 = this.t2x1 * this.i2e10 + this.t2y1 * this.i2e11 + this.t2z1 * this.i2e12;
  90044. this.a2z1 = this.t2x1 * this.i2e20 + this.t2y1 * this.i2e21 + this.t2z1 * this.i2e22;
  90045. this.t1x2 = this.r1y * this.az2 - this.r1z * this.ay2;
  90046. this.t1y2 = this.r1z * this.ax2 - this.r1x * this.az2;
  90047. this.t1z2 = this.r1x * this.ay2 - this.r1y * this.ax2;
  90048. this.t2x2 = this.r2y * this.az2 - this.r2z * this.ay2;
  90049. this.t2y2 = this.r2z * this.ax2 - this.r2x * this.az2;
  90050. this.t2z2 = this.r2x * this.ay2 - this.r2y * this.ax2;
  90051. this.l1x2 = this.ax2 * this.m1;
  90052. this.l1y2 = this.ay2 * this.m1;
  90053. this.l1z2 = this.az2 * this.m1;
  90054. this.l2x2 = this.ax2 * this.m2;
  90055. this.l2y2 = this.ay2 * this.m2;
  90056. this.l2z2 = this.az2 * this.m2;
  90057. this.a1x2 = this.t1x2 * this.i1e00 + this.t1y2 * this.i1e01 + this.t1z2 * this.i1e02;
  90058. this.a1y2 = this.t1x2 * this.i1e10 + this.t1y2 * this.i1e11 + this.t1z2 * this.i1e12;
  90059. this.a1z2 = this.t1x2 * this.i1e20 + this.t1y2 * this.i1e21 + this.t1z2 * this.i1e22;
  90060. this.a2x2 = this.t2x2 * this.i2e00 + this.t2y2 * this.i2e01 + this.t2z2 * this.i2e02;
  90061. this.a2y2 = this.t2x2 * this.i2e10 + this.t2y2 * this.i2e11 + this.t2z2 * this.i2e12;
  90062. this.a2z2 = this.t2x2 * this.i2e20 + this.t2y2 * this.i2e21 + this.t2z2 * this.i2e22;
  90063. this.t1x3 = this.r1y * this.az3 - this.r1z * this.ay3;
  90064. this.t1y3 = this.r1z * this.ax3 - this.r1x * this.az3;
  90065. this.t1z3 = this.r1x * this.ay3 - this.r1y * this.ax3;
  90066. this.t2x3 = this.r2y * this.az3 - this.r2z * this.ay3;
  90067. this.t2y3 = this.r2z * this.ax3 - this.r2x * this.az3;
  90068. this.t2z3 = this.r2x * this.ay3 - this.r2y * this.ax3;
  90069. this.l1x3 = this.ax3 * this.m1;
  90070. this.l1y3 = this.ay3 * this.m1;
  90071. this.l1z3 = this.az3 * this.m1;
  90072. this.l2x3 = this.ax3 * this.m2;
  90073. this.l2y3 = this.ay3 * this.m2;
  90074. this.l2z3 = this.az3 * this.m2;
  90075. this.a1x3 = this.t1x3 * this.i1e00 + this.t1y3 * this.i1e01 + this.t1z3 * this.i1e02;
  90076. this.a1y3 = this.t1x3 * this.i1e10 + this.t1y3 * this.i1e11 + this.t1z3 * this.i1e12;
  90077. this.a1z3 = this.t1x3 * this.i1e20 + this.t1y3 * this.i1e21 + this.t1z3 * this.i1e22;
  90078. this.a2x3 = this.t2x3 * this.i2e00 + this.t2y3 * this.i2e01 + this.t2z3 * this.i2e02;
  90079. this.a2y3 = this.t2x3 * this.i2e10 + this.t2y3 * this.i2e11 + this.t2z3 * this.i2e12;
  90080. this.a2z3 = this.t2x3 * this.i2e20 + this.t2y3 * this.i2e21 + this.t2z3 * this.i2e22;
  90081. // build an impulse matrix
  90082. var m12 = this.m1 + this.m2;
  90083. this.k00 = (this.ax1 * this.ax1 + this.ay1 * this.ay1 + this.az1 * this.az1) * m12;
  90084. this.k01 = (this.ax1 * this.ax2 + this.ay1 * this.ay2 + this.az1 * this.az2) * m12;
  90085. this.k02 = (this.ax1 * this.ax3 + this.ay1 * this.ay3 + this.az1 * this.az3) * m12;
  90086. this.k10 = (this.ax2 * this.ax1 + this.ay2 * this.ay1 + this.az2 * this.az1) * m12;
  90087. this.k11 = (this.ax2 * this.ax2 + this.ay2 * this.ay2 + this.az2 * this.az2) * m12;
  90088. this.k12 = (this.ax2 * this.ax3 + this.ay2 * this.ay3 + this.az2 * this.az3) * m12;
  90089. this.k20 = (this.ax3 * this.ax1 + this.ay3 * this.ay1 + this.az3 * this.az1) * m12;
  90090. this.k21 = (this.ax3 * this.ax2 + this.ay3 * this.ay2 + this.az3 * this.az2) * m12;
  90091. this.k22 = (this.ax3 * this.ax3 + this.ay3 * this.ay3 + this.az3 * this.az3) * m12;
  90092. this.k00 += this.t1x1 * this.a1x1 + this.t1y1 * this.a1y1 + this.t1z1 * this.a1z1;
  90093. this.k01 += this.t1x1 * this.a1x2 + this.t1y1 * this.a1y2 + this.t1z1 * this.a1z2;
  90094. this.k02 += this.t1x1 * this.a1x3 + this.t1y1 * this.a1y3 + this.t1z1 * this.a1z3;
  90095. this.k10 += this.t1x2 * this.a1x1 + this.t1y2 * this.a1y1 + this.t1z2 * this.a1z1;
  90096. this.k11 += this.t1x2 * this.a1x2 + this.t1y2 * this.a1y2 + this.t1z2 * this.a1z2;
  90097. this.k12 += this.t1x2 * this.a1x3 + this.t1y2 * this.a1y3 + this.t1z2 * this.a1z3;
  90098. this.k20 += this.t1x3 * this.a1x1 + this.t1y3 * this.a1y1 + this.t1z3 * this.a1z1;
  90099. this.k21 += this.t1x3 * this.a1x2 + this.t1y3 * this.a1y2 + this.t1z3 * this.a1z2;
  90100. this.k22 += this.t1x3 * this.a1x3 + this.t1y3 * this.a1y3 + this.t1z3 * this.a1z3;
  90101. this.k00 += this.t2x1 * this.a2x1 + this.t2y1 * this.a2y1 + this.t2z1 * this.a2z1;
  90102. this.k01 += this.t2x1 * this.a2x2 + this.t2y1 * this.a2y2 + this.t2z1 * this.a2z2;
  90103. this.k02 += this.t2x1 * this.a2x3 + this.t2y1 * this.a2y3 + this.t2z1 * this.a2z3;
  90104. this.k10 += this.t2x2 * this.a2x1 + this.t2y2 * this.a2y1 + this.t2z2 * this.a2z1;
  90105. this.k11 += this.t2x2 * this.a2x2 + this.t2y2 * this.a2y2 + this.t2z2 * this.a2z2;
  90106. this.k12 += this.t2x2 * this.a2x3 + this.t2y2 * this.a2y3 + this.t2z2 * this.a2z3;
  90107. this.k20 += this.t2x3 * this.a2x1 + this.t2y3 * this.a2y1 + this.t2z3 * this.a2z1;
  90108. this.k21 += this.t2x3 * this.a2x2 + this.t2y3 * this.a2y2 + this.t2z3 * this.a2z2;
  90109. this.k22 += this.t2x3 * this.a2x3 + this.t2y3 * this.a2y3 + this.t2z3 * this.a2z3;
  90110. this.kv00 = this.k00;
  90111. this.kv11 = this.k11;
  90112. this.kv22 = this.k22;
  90113. this.dv00 = 1 / this.kv00;
  90114. this.dv11 = 1 / this.kv11;
  90115. this.dv22 = 1 / this.kv22;
  90116. if (enableSpring1 && this.limitState1 != 2) {
  90117. var omega = 6.2831853 * frequency1;
  90118. var k = omega * omega * timeStep;
  90119. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  90120. this.cfm1 = this.kv00 * dmp;
  90121. this.limitVelocity1 *= k * dmp;
  90122. } else {
  90123. this.cfm1 = 0;
  90124. this.limitVelocity1 *= invTimeStep * 0.05;
  90125. }
  90126. if (enableSpring2 && this.limitState2 != 2) {
  90127. omega = 6.2831853 * frequency2;
  90128. k = omega * omega * timeStep;
  90129. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  90130. this.cfm2 = this.kv11 * dmp;
  90131. this.limitVelocity2 *= k * dmp;
  90132. } else {
  90133. this.cfm2 = 0;
  90134. this.limitVelocity2 *= invTimeStep * 0.05;
  90135. }
  90136. if (enableSpring3 && this.limitState3 != 2) {
  90137. omega = 6.2831853 * frequency3;
  90138. k = omega * omega * timeStep;
  90139. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  90140. this.cfm3 = this.kv22 * dmp;
  90141. this.limitVelocity3 *= k * dmp;
  90142. } else {
  90143. this.cfm3 = 0;
  90144. this.limitVelocity3 *= invTimeStep * 0.05;
  90145. }
  90146. this.k00 += this.cfm1;
  90147. this.k11 += this.cfm2;
  90148. this.k22 += this.cfm3;
  90149. var inv = 1 / (
  90150. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  90151. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  90152. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  90153. );
  90154. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  90155. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  90156. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  90157. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  90158. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  90159. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  90160. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  90161. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  90162. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  90163. // warm starting
  90164. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  90165. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  90166. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  90167. this.l1.x += totalImpulse1 * this.l1x1 + totalImpulse2 * this.l1x2 + totalImpulse3 * this.l1x3;
  90168. this.l1.y += totalImpulse1 * this.l1y1 + totalImpulse2 * this.l1y2 + totalImpulse3 * this.l1y3;
  90169. this.l1.z += totalImpulse1 * this.l1z1 + totalImpulse2 * this.l1z2 + totalImpulse3 * this.l1z3;
  90170. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  90171. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  90172. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  90173. this.l2.x -= totalImpulse1 * this.l2x1 + totalImpulse2 * this.l2x2 + totalImpulse3 * this.l2x3;
  90174. this.l2.y -= totalImpulse1 * this.l2y1 + totalImpulse2 * this.l2y2 + totalImpulse3 * this.l2y3;
  90175. this.l2.z -= totalImpulse1 * this.l2z1 + totalImpulse2 * this.l2z2 + totalImpulse3 * this.l2z3;
  90176. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  90177. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  90178. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  90179. },
  90180. solve: function () {
  90181. 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;
  90182. 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;
  90183. 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;
  90184. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  90185. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  90186. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  90187. var oldMotorImpulse1 = this.motorImpulse1;
  90188. var oldMotorImpulse2 = this.motorImpulse2;
  90189. var oldMotorImpulse3 = this.motorImpulse3;
  90190. var dMotorImpulse1 = 0;
  90191. var dMotorImpulse2 = 0;
  90192. var dMotorImpulse3 = 0;
  90193. if (this.enableMotor1) {
  90194. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  90195. this.motorImpulse1 += dMotorImpulse1;
  90196. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  90197. this.motorImpulse1 = this.maxMotorImpulse1;
  90198. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  90199. this.motorImpulse1 = -this.maxMotorImpulse1;
  90200. }
  90201. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  90202. }
  90203. if (this.enableMotor2) {
  90204. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  90205. this.motorImpulse2 += dMotorImpulse2;
  90206. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  90207. this.motorImpulse2 = this.maxMotorImpulse2;
  90208. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  90209. this.motorImpulse2 = -this.maxMotorImpulse2;
  90210. }
  90211. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  90212. }
  90213. if (this.enableMotor3) {
  90214. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  90215. this.motorImpulse3 += dMotorImpulse3;
  90216. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  90217. this.motorImpulse3 = this.maxMotorImpulse3;
  90218. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  90219. this.motorImpulse3 = -this.maxMotorImpulse3;
  90220. }
  90221. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  90222. }
  90223. // apply motor impulse to relative velocity
  90224. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  90225. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  90226. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  90227. // subtract target velocity and applied impulse
  90228. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  90229. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  90230. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  90231. var oldLimitImpulse1 = this.limitImpulse1;
  90232. var oldLimitImpulse2 = this.limitImpulse2;
  90233. var oldLimitImpulse3 = this.limitImpulse3;
  90234. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  90235. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  90236. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  90237. this.limitImpulse1 += dLimitImpulse1;
  90238. this.limitImpulse2 += dLimitImpulse2;
  90239. this.limitImpulse3 += dLimitImpulse3;
  90240. // clamp
  90241. var clampState = 0;
  90242. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  90243. dLimitImpulse1 = -oldLimitImpulse1;
  90244. rvn2 += dLimitImpulse1 * this.k10;
  90245. rvn3 += dLimitImpulse1 * this.k20;
  90246. clampState |= 1;
  90247. }
  90248. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  90249. dLimitImpulse2 = -oldLimitImpulse2;
  90250. rvn1 += dLimitImpulse2 * this.k01;
  90251. rvn3 += dLimitImpulse2 * this.k21;
  90252. clampState |= 2;
  90253. }
  90254. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  90255. dLimitImpulse3 = -oldLimitImpulse3;
  90256. rvn1 += dLimitImpulse3 * this.k02;
  90257. rvn2 += dLimitImpulse3 * this.k12;
  90258. clampState |= 4;
  90259. }
  90260. // update un-clamped impulse
  90261. // TODO: isolate division
  90262. var det;
  90263. switch (clampState) {
  90264. case 1:// update 2 3
  90265. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  90266. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  90267. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  90268. break;
  90269. case 2:// update 1 3
  90270. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  90271. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  90272. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  90273. break;
  90274. case 3:// update 3
  90275. dLimitImpulse3 = rvn3 / this.k22;
  90276. break;
  90277. case 4:// update 1 2
  90278. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  90279. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  90280. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  90281. break;
  90282. case 5:// update 2
  90283. dLimitImpulse2 = rvn2 / this.k11;
  90284. break;
  90285. case 6:// update 1
  90286. dLimitImpulse1 = rvn1 / this.k00;
  90287. break;
  90288. }
  90289. this.limitImpulse1 = oldLimitImpulse1 + dLimitImpulse1;
  90290. this.limitImpulse2 = oldLimitImpulse2 + dLimitImpulse2;
  90291. this.limitImpulse3 = oldLimitImpulse3 + dLimitImpulse3;
  90292. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  90293. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  90294. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  90295. // apply impulse
  90296. this.l1.x += dImpulse1 * this.l1x1 + dImpulse2 * this.l1x2 + dImpulse3 * this.l1x3;
  90297. this.l1.y += dImpulse1 * this.l1y1 + dImpulse2 * this.l1y2 + dImpulse3 * this.l1y3;
  90298. this.l1.z += dImpulse1 * this.l1z1 + dImpulse2 * this.l1z2 + dImpulse3 * this.l1z3;
  90299. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  90300. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  90301. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  90302. this.l2.x -= dImpulse1 * this.l2x1 + dImpulse2 * this.l2x2 + dImpulse3 * this.l2x3;
  90303. this.l2.y -= dImpulse1 * this.l2y1 + dImpulse2 * this.l2y2 + dImpulse3 * this.l2y3;
  90304. this.l2.z -= dImpulse1 * this.l2z1 + dImpulse2 * this.l2z2 + dImpulse3 * this.l2z3;
  90305. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  90306. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  90307. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  90308. }
  90309. }
  90310. /**
  90311. * A translational constraint for various joints.
  90312. * @author saharan
  90313. */
  90314. OIMO.TranslationalConstraint = function (joint, limitMotor) {
  90315. this.cfm = NaN;
  90316. this.m1 = NaN;
  90317. this.m2 = NaN;
  90318. this.i1e00 = NaN;
  90319. this.i1e01 = NaN;
  90320. this.i1e02 = NaN;
  90321. this.i1e10 = NaN;
  90322. this.i1e11 = NaN;
  90323. this.i1e12 = NaN;
  90324. this.i1e20 = NaN;
  90325. this.i1e21 = NaN;
  90326. this.i1e22 = NaN;
  90327. this.i2e00 = NaN;
  90328. this.i2e01 = NaN;
  90329. this.i2e02 = NaN;
  90330. this.i2e10 = NaN;
  90331. this.i2e11 = NaN;
  90332. this.i2e12 = NaN;
  90333. this.i2e20 = NaN;
  90334. this.i2e21 = NaN;
  90335. this.i2e22 = NaN;
  90336. this.motorDenom = NaN;
  90337. this.invMotorDenom = NaN;
  90338. this.invDenom = NaN;
  90339. this.ax = NaN;
  90340. this.ay = NaN;
  90341. this.az = NaN;
  90342. this.r1x = NaN;
  90343. this.r1y = NaN;
  90344. this.r1z = NaN;
  90345. this.r2x = NaN;
  90346. this.r2y = NaN;
  90347. this.r2z = NaN;
  90348. this.t1x = NaN;
  90349. this.t1y = NaN;
  90350. this.t1z = NaN;
  90351. this.t2x = NaN;
  90352. this.t2y = NaN;
  90353. this.t2z = NaN;
  90354. this.l1x = NaN;
  90355. this.l1y = NaN;
  90356. this.l1z = NaN;
  90357. this.l2x = NaN;
  90358. this.l2y = NaN;
  90359. this.l2z = NaN;
  90360. this.a1x = NaN;
  90361. this.a1y = NaN;
  90362. this.a1z = NaN;
  90363. this.a2x = NaN;
  90364. this.a2y = NaN;
  90365. this.a2z = NaN;
  90366. this.lowerLimit = NaN;
  90367. this.upperLimit = NaN;
  90368. this.limitVelocity = NaN;
  90369. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  90370. this.enableMotor = false;
  90371. this.motorSpeed = NaN;
  90372. this.maxMotorForce = NaN;
  90373. this.maxMotorImpulse = NaN;
  90374. this.limitMotor = limitMotor;
  90375. this.b1 = joint.body1;
  90376. this.b2 = joint.body2;
  90377. this.p1 = joint.anchorPoint1;
  90378. this.p2 = joint.anchorPoint2;
  90379. this.r1 = joint.relativeAnchorPoint1;
  90380. this.r2 = joint.relativeAnchorPoint2;
  90381. this.l1 = this.b1.linearVelocity;
  90382. this.l2 = this.b2.linearVelocity;
  90383. this.a1 = this.b1.angularVelocity;
  90384. this.a2 = this.b2.angularVelocity;
  90385. this.i1 = this.b1.inverseInertia;
  90386. this.i2 = this.b2.inverseInertia;
  90387. this.limitImpulse = 0;
  90388. this.motorImpulse = 0;
  90389. }
  90390. OIMO.TranslationalConstraint.prototype = {
  90391. constructor: OIMO.TranslationalConstraint,
  90392. preSolve: function (timeStep, invTimeStep) {
  90393. this.ax = this.limitMotor.axis.x;
  90394. this.ay = this.limitMotor.axis.y;
  90395. this.az = this.limitMotor.axis.z;
  90396. this.lowerLimit = this.limitMotor.lowerLimit;
  90397. this.upperLimit = this.limitMotor.upperLimit;
  90398. this.motorSpeed = this.limitMotor.motorSpeed;
  90399. this.maxMotorForce = this.limitMotor.maxMotorForce;
  90400. this.enableMotor = this.maxMotorForce > 0;
  90401. this.m1 = this.b1.inverseMass;
  90402. this.m2 = this.b2.inverseMass;
  90403. var ti1 = this.i1.elements;
  90404. var ti2 = this.i2.elements;
  90405. this.i1e00 = ti1[0];
  90406. this.i1e01 = ti1[1];
  90407. this.i1e02 = ti1[2];
  90408. this.i1e10 = ti1[3];
  90409. this.i1e11 = ti1[4];
  90410. this.i1e12 = ti1[5];
  90411. this.i1e20 = ti1[6];
  90412. this.i1e21 = ti1[7];
  90413. this.i1e22 = ti1[8];
  90414. this.i2e00 = ti2[0];
  90415. this.i2e01 = ti2[1];
  90416. this.i2e02 = ti2[2];
  90417. this.i2e10 = ti2[3];
  90418. this.i2e11 = ti2[4];
  90419. this.i2e12 = ti2[5];
  90420. this.i2e20 = ti2[6];
  90421. this.i2e21 = ti2[7];
  90422. this.i2e22 = ti2[8];
  90423. var dx = this.p2.x - this.p1.x;
  90424. var dy = this.p2.y - this.p1.y;
  90425. var dz = this.p2.z - this.p1.z;
  90426. var d = dx * this.ax + dy * this.ay + dz * this.az;
  90427. var frequency = this.limitMotor.frequency;
  90428. var enableSpring = frequency > 0;
  90429. var enableLimit = this.lowerLimit <= this.upperLimit;
  90430. if (enableSpring && d > 20 || d < -20) {
  90431. enableSpring = false;
  90432. }
  90433. if (enableLimit) {
  90434. if (this.lowerLimit == this.upperLimit) {
  90435. if (this.limitState != 0) {
  90436. this.limitState = 0;
  90437. this.limitImpulse = 0;
  90438. }
  90439. this.limitVelocity = this.lowerLimit - d;
  90440. if (!enableSpring) d = this.lowerLimit;
  90441. } else if (d < this.lowerLimit) {
  90442. if (this.limitState != -1) {
  90443. this.limitState = -1;
  90444. this.limitImpulse = 0;
  90445. }
  90446. this.limitVelocity = this.lowerLimit - d;
  90447. if (!enableSpring) d = this.lowerLimit;
  90448. } else if (d > this.upperLimit) {
  90449. if (this.limitState != 1) {
  90450. this.limitState = 1;
  90451. this.limitImpulse = 0;
  90452. }
  90453. this.limitVelocity = this.upperLimit - d;
  90454. if (!enableSpring) d = this.upperLimit;
  90455. } else {
  90456. this.limitState = 2;
  90457. this.limitImpulse = 0;
  90458. this.limitVelocity = 0;
  90459. }
  90460. if (!enableSpring) {
  90461. if (this.limitVelocity > 0.005) this.limitVelocity -= 0.005;
  90462. else if (this.limitVelocity < -0.005) this.limitVelocity += 0.005;
  90463. else this.limitVelocity = 0;
  90464. }
  90465. } else {
  90466. this.limitState = 2;
  90467. this.limitImpulse = 0;
  90468. }
  90469. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  90470. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  90471. } else {
  90472. this.motorImpulse = 0;
  90473. this.maxMotorImpulse = 0;
  90474. }
  90475. var rdx = d * this.ax;
  90476. var rdy = d * this.ay;
  90477. var rdz = d * this.az;
  90478. var w1 = this.m1 / (this.m1 + this.m2);
  90479. var w2 = 1 - w1;
  90480. this.r1x = this.r1.x + rdx * w1;
  90481. this.r1y = this.r1.y + rdy * w1;
  90482. this.r1z = this.r1.z + rdz * w1;
  90483. this.r2x = this.r2.x - rdx * w2;
  90484. this.r2y = this.r2.y - rdy * w2;
  90485. this.r2z = this.r2.z - rdz * w2;
  90486. this.t1x = this.r1y * this.az - this.r1z * this.ay;
  90487. this.t1y = this.r1z * this.ax - this.r1x * this.az;
  90488. this.t1z = this.r1x * this.ay - this.r1y * this.ax;
  90489. this.t2x = this.r2y * this.az - this.r2z * this.ay;
  90490. this.t2y = this.r2z * this.ax - this.r2x * this.az;
  90491. this.t2z = this.r2x * this.ay - this.r2y * this.ax;
  90492. this.l1x = this.ax * this.m1;
  90493. this.l1y = this.ay * this.m1;
  90494. this.l1z = this.az * this.m1;
  90495. this.l2x = this.ax * this.m2;
  90496. this.l2y = this.ay * this.m2;
  90497. this.l2z = this.az * this.m2;
  90498. this.a1x = this.t1x * this.i1e00 + this.t1y * this.i1e01 + this.t1z * this.i1e02;
  90499. this.a1y = this.t1x * this.i1e10 + this.t1y * this.i1e11 + this.t1z * this.i1e12;
  90500. this.a1z = this.t1x * this.i1e20 + this.t1y * this.i1e21 + this.t1z * this.i1e22;
  90501. this.a2x = this.t2x * this.i2e00 + this.t2y * this.i2e01 + this.t2z * this.i2e02;
  90502. this.a2y = this.t2x * this.i2e10 + this.t2y * this.i2e11 + this.t2z * this.i2e12;
  90503. this.a2z = this.t2x * this.i2e20 + this.t2y * this.i2e21 + this.t2z * this.i2e22;
  90504. this.motorDenom =
  90505. this.m1 + this.m2 +
  90506. this.ax * (this.a1y * this.r1z - this.a1z * this.r1y + this.a2y * this.r2z - this.a2z * this.r2y) +
  90507. this.ay * (this.a1z * this.r1x - this.a1x * this.r1z + this.a2z * this.r2x - this.a2x * this.r2z) +
  90508. this.az * (this.a1x * this.r1y - this.a1y * this.r1x + this.a2x * this.r2y - this.a2y * this.r2x);
  90509. this.invMotorDenom = 1 / this.motorDenom;
  90510. if (enableSpring && this.limitState != 2) {
  90511. var omega = 6.2831853 * frequency;
  90512. var k = omega * omega * timeStep;
  90513. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  90514. this.cfm = this.motorDenom * dmp;
  90515. this.limitVelocity *= k * dmp;
  90516. } else {
  90517. this.cfm = 0;
  90518. this.limitVelocity *= invTimeStep * 0.05;
  90519. }
  90520. this.invDenom = 1 / (this.motorDenom + this.cfm);
  90521. var totalImpulse = this.limitImpulse + this.motorImpulse;
  90522. this.l1.x += totalImpulse * this.l1x;
  90523. this.l1.y += totalImpulse * this.l1y;
  90524. this.l1.z += totalImpulse * this.l1z;
  90525. this.a1.x += totalImpulse * this.a1x;
  90526. this.a1.y += totalImpulse * this.a1y;
  90527. this.a1.z += totalImpulse * this.a1z;
  90528. this.l2.x -= totalImpulse * this.l2x;
  90529. this.l2.y -= totalImpulse * this.l2y;
  90530. this.l2.z -= totalImpulse * this.l2z;
  90531. this.a2.x -= totalImpulse * this.a2x;
  90532. this.a2.y -= totalImpulse * this.a2y;
  90533. this.a2.z -= totalImpulse * this.a2z;
  90534. },
  90535. solve: function () {
  90536. var rvn =
  90537. this.ax * (this.l2.x - this.l1.x) + this.ay * (this.l2.y - this.l1.y) + this.az * (this.l2.z - this.l1.z) +
  90538. 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;
  90539. // motor part
  90540. var newMotorImpulse;
  90541. if (this.enableMotor) {
  90542. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  90543. var oldMotorImpulse = this.motorImpulse;
  90544. this.motorImpulse += newMotorImpulse;
  90545. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  90546. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  90547. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  90548. rvn -= newMotorImpulse * this.motorDenom;
  90549. } else newMotorImpulse = 0;
  90550. // limit part
  90551. var newLimitImpulse;
  90552. if (this.limitState != 2) {
  90553. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  90554. var oldLimitImpulse = this.limitImpulse;
  90555. this.limitImpulse += newLimitImpulse;
  90556. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  90557. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  90558. } else newLimitImpulse = 0;
  90559. var totalImpulse = newLimitImpulse + newMotorImpulse;
  90560. this.l1.x += totalImpulse * this.l1x;
  90561. this.l1.y += totalImpulse * this.l1y;
  90562. this.l1.z += totalImpulse * this.l1z;
  90563. this.a1.x += totalImpulse * this.a1x;
  90564. this.a1.y += totalImpulse * this.a1y;
  90565. this.a1.z += totalImpulse * this.a1z;
  90566. this.l2.x -= totalImpulse * this.l2x;
  90567. this.l2.y -= totalImpulse * this.l2y;
  90568. this.l2.z -= totalImpulse * this.l2z;
  90569. this.a2.x -= totalImpulse * this.a2x;
  90570. this.a2.y -= totalImpulse * this.a2y;
  90571. this.a2.z -= totalImpulse * this.a2z;
  90572. }
  90573. }
  90574. /**
  90575. * A contact is a pair of shapes whose axis-aligned bounding boxes are overlapping.
  90576. * @author saharan
  90577. */
  90578. OIMO.Contact = function () {
  90579. // The first shape.
  90580. this.shape1 = null;
  90581. // The second shape.
  90582. this.shape2 = null;
  90583. // The first rigid body.
  90584. this.body1 = null;
  90585. // The second rigid body.
  90586. this.body2 = null;
  90587. // The previous contact in the world.
  90588. this.prev = null;
  90589. // The next contact in the world.
  90590. this.next = null;
  90591. // Internal
  90592. this.persisting = false;
  90593. // Whether both the rigid bodies are sleeping or not.
  90594. this.sleeping = false;
  90595. // The collision detector between two shapes.
  90596. this.detector = null;
  90597. // The contact constraint of the contact.
  90598. this.constraint = null;
  90599. // Whether the shapes are touching or not.
  90600. this.touching = false;
  90601. this.b1Link = new OIMO.ContactLink(this);
  90602. this.b2Link = new OIMO.ContactLink(this);
  90603. this.s1Link = new OIMO.ContactLink(this);
  90604. this.s2Link = new OIMO.ContactLink(this);
  90605. // The contact manifold of the contact.
  90606. this.manifold = new OIMO.ContactManifold();
  90607. this.buffer = [];// vector 4
  90608. this.buffer.length = 4;
  90609. this.buffer[0] = new OIMO.ImpulseDataBuffer();
  90610. this.buffer[1] = new OIMO.ImpulseDataBuffer();
  90611. this.buffer[2] = new OIMO.ImpulseDataBuffer();
  90612. this.buffer[3] = new OIMO.ImpulseDataBuffer();
  90613. this.points = this.manifold.points;
  90614. this.constraint = new OIMO.ContactConstraint(this.manifold);
  90615. }
  90616. OIMO.Contact.prototype = {
  90617. constructor: OIMO.Contact,
  90618. mixRestitution: function (restitution1, restitution2) {
  90619. return OIMO.sqrt(restitution1 * restitution2);
  90620. },
  90621. mixFriction: function (friction1, friction2) {
  90622. return OIMO.sqrt(friction1 * friction2);
  90623. },
  90624. /**
  90625. * Update the contact manifold.
  90626. */
  90627. updateManifold: function () {
  90628. this.constraint.restitution = this.mixRestitution(this.shape1.restitution, this.shape2.restitution);
  90629. this.constraint.friction = this.mixFriction(this.shape1.friction, this.shape2.friction);
  90630. var numBuffers = this.manifold.numPoints;
  90631. var i = numBuffers;
  90632. while (i--) {
  90633. //for(var i=0;i<numBuffers;i++){
  90634. var b = this.buffer[i];
  90635. var p = this.points[i];
  90636. b.lp1X = p.localPoint1.x;
  90637. b.lp1Y = p.localPoint1.y;
  90638. b.lp1Z = p.localPoint1.z;
  90639. b.lp2X = p.localPoint2.x;
  90640. b.lp2Y = p.localPoint2.y;
  90641. b.lp2Z = p.localPoint2.z;
  90642. b.impulse = p.normalImpulse;
  90643. }
  90644. this.manifold.numPoints = 0;
  90645. this.detector.detectCollision(this.shape1, this.shape2, this.manifold);
  90646. var num = this.manifold.numPoints;
  90647. if (num == 0) {
  90648. this.touching = false;
  90649. return;
  90650. }
  90651. this.touching = true;
  90652. i = num;
  90653. while (i--) {
  90654. //for(i=0; i<num; i++){
  90655. p = this.points[i];
  90656. var lp1x = p.localPoint1.x;
  90657. var lp1y = p.localPoint1.y;
  90658. var lp1z = p.localPoint1.z;
  90659. var lp2x = p.localPoint2.x;
  90660. var lp2y = p.localPoint2.y;
  90661. var lp2z = p.localPoint2.z;
  90662. var index = -1;
  90663. var minDistance = 0.0004;
  90664. var j = numBuffers;
  90665. while (j--) {
  90666. //for(var j=0;j<numBuffers;j++){
  90667. b = this.buffer[j];
  90668. var dx = b.lp1X - lp1x;
  90669. var dy = b.lp1Y - lp1y;
  90670. var dz = b.lp1Z - lp1z;
  90671. var distance1 = dx * dx + dy * dy + dz * dz;
  90672. dx = b.lp2X - lp2x;
  90673. dy = b.lp2Y - lp2y;
  90674. dz = b.lp2Z - lp2z;
  90675. var distance2 = dx * dx + dy * dy + dz * dz;
  90676. if (distance1 < distance2) {
  90677. if (distance1 < minDistance) {
  90678. minDistance = distance1;
  90679. index = j;
  90680. }
  90681. } else {
  90682. if (distance2 < minDistance) {
  90683. minDistance = distance2;
  90684. index = j;
  90685. }
  90686. }
  90687. }
  90688. if (index != -1) {
  90689. var tmp = this.buffer[index];
  90690. this.buffer[index] = this.buffer[--numBuffers];
  90691. this.buffer[numBuffers] = tmp;
  90692. p.normalImpulse = tmp.impulse;
  90693. p.warmStarted = true;
  90694. } else {
  90695. p.normalImpulse = 0;
  90696. p.warmStarted = false;
  90697. }
  90698. }
  90699. },
  90700. /**
  90701. * Attach the contact to the shapes.
  90702. * @param shape1
  90703. * @param shape2
  90704. */
  90705. attach: function (shape1, shape2) {
  90706. this.shape1 = shape1;
  90707. this.shape2 = shape2;
  90708. this.body1 = shape1.parent;
  90709. this.body2 = shape2.parent;
  90710. this.manifold.body1 = this.body1;
  90711. this.manifold.body2 = this.body2;
  90712. this.constraint.body1 = this.body1;
  90713. this.constraint.body2 = this.body2;
  90714. this.constraint.attach();
  90715. this.s1Link.shape = shape2;
  90716. this.s1Link.body = this.body2;
  90717. this.s2Link.shape = shape1;
  90718. this.s2Link.body = this.body1;
  90719. if (shape1.contactLink != null) (this.s1Link.next = shape1.contactLink).prev = this.s1Link;
  90720. else this.s1Link.next = null;
  90721. shape1.contactLink = this.s1Link;
  90722. shape1.numContacts++;
  90723. if (shape2.contactLink != null) (this.s2Link.next = shape2.contactLink).prev = this.s2Link;
  90724. else this.s2Link.next = null;
  90725. shape2.contactLink = this.s2Link;
  90726. shape2.numContacts++;
  90727. this.b1Link.shape = shape2;
  90728. this.b1Link.body = this.body2;
  90729. this.b2Link.shape = shape1;
  90730. this.b2Link.body = this.body1;
  90731. if (this.body1.contactLink != null) (this.b1Link.next = this.body1.contactLink).prev = this.b1Link;
  90732. else this.b1Link.next = null;
  90733. this.body1.contactLink = this.b1Link;
  90734. this.body1.numContacts++;
  90735. if (this.body2.contactLink != null) (this.b2Link.next = this.body2.contactLink).prev = this.b2Link;
  90736. else this.b2Link.next = null;
  90737. this.body2.contactLink = this.b2Link;
  90738. this.body2.numContacts++;
  90739. this.prev = null;
  90740. this.next = null;
  90741. this.persisting = true;
  90742. this.sleeping = this.body1.sleeping && this.body2.sleeping;
  90743. this.manifold.numPoints = 0;
  90744. },
  90745. /**
  90746. * Detach the contact from the shapes.
  90747. */
  90748. detach: function () {
  90749. var prev = this.s1Link.prev;
  90750. var next = this.s1Link.next;
  90751. if (prev !== null) prev.next = next;
  90752. if (next !== null) next.prev = prev;
  90753. if (this.shape1.contactLink == this.s1Link) this.shape1.contactLink = next;
  90754. this.s1Link.prev = null;
  90755. this.s1Link.next = null;
  90756. this.s1Link.shape = null;
  90757. this.s1Link.body = null;
  90758. this.shape1.numContacts--;
  90759. prev = this.s2Link.prev;
  90760. next = this.s2Link.next;
  90761. if (prev !== null) prev.next = next;
  90762. if (next !== null) next.prev = prev;
  90763. if (this.shape2.contactLink == this.s2Link) this.shape2.contactLink = next;
  90764. this.s2Link.prev = null;
  90765. this.s2Link.next = null;
  90766. this.s2Link.shape = null;
  90767. this.s2Link.body = null;
  90768. this.shape2.numContacts--;
  90769. prev = this.b1Link.prev;
  90770. next = this.b1Link.next;
  90771. if (prev !== null) prev.next = next;
  90772. if (next !== null) next.prev = prev;
  90773. if (this.body1.contactLink == this.b1Link) this.body1.contactLink = next;
  90774. this.b1Link.prev = null;
  90775. this.b1Link.next = null;
  90776. this.b1Link.shape = null;
  90777. this.b1Link.body = null;
  90778. this.body1.numContacts--;
  90779. prev = this.b2Link.prev;
  90780. next = this.b2Link.next;
  90781. if (prev !== null) prev.next = next;
  90782. if (next !== null) next.prev = prev;
  90783. if (this.body2.contactLink == this.b2Link) this.body2.contactLink = next;
  90784. this.b2Link.prev = null;
  90785. this.b2Link.next = null;
  90786. this.b2Link.shape = null;
  90787. this.b2Link.body = null;
  90788. this.body2.numContacts--;
  90789. this.manifold.body1 = null;
  90790. this.manifold.body2 = null;
  90791. this.constraint.body1 = null;
  90792. this.constraint.body2 = null;
  90793. this.constraint.detach();
  90794. this.shape1 = null;
  90795. this.shape2 = null;
  90796. this.body1 = null;
  90797. this.body2 = null;
  90798. }
  90799. }
  90800. /**
  90801. * ...
  90802. * @author saharan
  90803. */
  90804. OIMO.ContactConstraint = function (manifold) {
  90805. OIMO.Constraint.call(this);
  90806. // The contact manifold of the constraint.
  90807. this.manifold = manifold;
  90808. // The coefficient of restitution of the constraint.
  90809. this.restitution = NaN;
  90810. // The coefficient of friction of the constraint.
  90811. this.friction = NaN;
  90812. this.p1 = null;
  90813. this.p2 = null;
  90814. this.lv1 = null;
  90815. this.lv2 = null;
  90816. this.av1 = null;
  90817. this.av2 = null;
  90818. this.i1 = null;
  90819. this.i2 = null;
  90820. this.ii1 = null;
  90821. this.ii2 = null;
  90822. this.m1 = NaN;
  90823. this.m2 = NaN;
  90824. this.num = 0;
  90825. this.ps = manifold.points;
  90826. this.cs = new OIMO.ContactPointDataBuffer();
  90827. this.cs.next = new OIMO.ContactPointDataBuffer();
  90828. this.cs.next.next = new OIMO.ContactPointDataBuffer();
  90829. this.cs.next.next.next = new OIMO.ContactPointDataBuffer();
  90830. }
  90831. OIMO.ContactConstraint.prototype = Object.create(OIMO.Constraint.prototype);
  90832. /**
  90833. * Attach the constraint to the bodies.
  90834. */
  90835. OIMO.ContactConstraint.prototype.attach = function () {
  90836. this.p1 = this.body1.position;
  90837. this.p2 = this.body2.position;
  90838. this.lv1 = this.body1.linearVelocity;
  90839. this.av1 = this.body1.angularVelocity;
  90840. this.lv2 = this.body2.linearVelocity;
  90841. this.av2 = this.body2.angularVelocity;
  90842. this.i1 = this.body1.inverseInertia;
  90843. this.i2 = this.body2.inverseInertia;
  90844. }
  90845. /**
  90846. * Detach the constraint from the bodies.
  90847. */
  90848. OIMO.ContactConstraint.prototype.detach = function () {
  90849. this.p1 = null;
  90850. this.p2 = null;
  90851. this.lv1 = null;
  90852. this.lv2 = null;
  90853. this.av1 = null;
  90854. this.av2 = null;
  90855. this.i1 = null;
  90856. this.i2 = null;
  90857. }
  90858. OIMO.ContactConstraint.prototype.preSolve = function (timeStep, invTimeStep) {
  90859. this.m1 = this.body1.inverseMass;
  90860. this.m2 = this.body2.inverseMass;
  90861. this.ii1 = this.i1.clone();
  90862. this.ii2 = this.i2.clone();
  90863. var ii1 = this.ii1.elements;
  90864. var ii2 = this.ii2.elements;
  90865. var p1x = this.p1.x;
  90866. var p1y = this.p1.y;
  90867. var p1z = this.p1.z;
  90868. var p2x = this.p2.x;
  90869. var p2y = this.p2.y;
  90870. var p2z = this.p2.z;
  90871. var m1m2 = this.m1 + this.m2;
  90872. this.num = this.manifold.numPoints;
  90873. var c = this.cs;
  90874. for (var i = 0; i < this.num; i++) {
  90875. var p = this.ps[i];
  90876. var tmp1X;
  90877. var tmp1Y;
  90878. var tmp1Z;
  90879. var tmp2X;
  90880. var tmp2Y;
  90881. var tmp2Z;
  90882. tmp1X = p.position.x;
  90883. tmp1Y = p.position.y;
  90884. tmp1Z = p.position.z;
  90885. var rp1X = tmp1X - p1x;
  90886. var rp1Y = tmp1Y - p1y;
  90887. var rp1Z = tmp1Z - p1z;
  90888. var rp2X = tmp1X - p2x;
  90889. var rp2Y = tmp1Y - p2y;
  90890. var rp2Z = tmp1Z - p2z;
  90891. c.rp1X = rp1X;
  90892. c.rp1Y = rp1Y;
  90893. c.rp1Z = rp1Z;
  90894. c.rp2X = rp2X;
  90895. c.rp2Y = rp2Y;
  90896. c.rp2Z = rp2Z;
  90897. c.norImp = p.normalImpulse;
  90898. c.tanImp = p.tangentImpulse;
  90899. c.binImp = p.binormalImpulse;
  90900. var norX = p.normal.x;
  90901. var norY = p.normal.y;
  90902. var norZ = p.normal.z;
  90903. var rvX = (this.lv2.x + this.av2.y * rp2Z - this.av2.z * rp2Y) - (this.lv1.x + this.av1.y * rp1Z - this.av1.z * rp1Y);
  90904. var rvY = (this.lv2.y + this.av2.z * rp2X - this.av2.x * rp2Z) - (this.lv1.y + this.av1.z * rp1X - this.av1.x * rp1Z);
  90905. var rvZ = (this.lv2.z + this.av2.x * rp2Y - this.av2.y * rp2X) - (this.lv1.z + this.av1.x * rp1Y - this.av1.y * rp1X);
  90906. var rvn = norX * rvX + norY * rvY + norZ * rvZ;
  90907. var tanX = rvX - rvn * norX;
  90908. var tanY = rvY - rvn * norY;
  90909. var tanZ = rvZ - rvn * norZ;
  90910. var len = tanX * tanX + tanY * tanY + tanZ * tanZ;
  90911. if (len > 0.04) {
  90912. len = 1 / OIMO.sqrt(len);
  90913. } else {
  90914. tanX = norY * norX - norZ * norZ;
  90915. tanY = -norZ * norY - norX * norX;
  90916. tanZ = norX * norZ + norY * norY;
  90917. len = 1 / OIMO.sqrt(tanX * tanX + tanY * tanY + tanZ * tanZ);
  90918. }
  90919. tanX *= len;
  90920. tanY *= len;
  90921. tanZ *= len;
  90922. var binX = norY * tanZ - norZ * tanY;
  90923. var binY = norZ * tanX - norX * tanZ;
  90924. var binZ = norX * tanY - norY * tanX;
  90925. c.norX = norX;
  90926. c.norY = norY;
  90927. c.norZ = norZ;
  90928. c.tanX = tanX;
  90929. c.tanY = tanY;
  90930. c.tanZ = tanZ;
  90931. c.binX = binX;
  90932. c.binY = binY;
  90933. c.binZ = binZ;
  90934. c.norU1X = norX * this.m1;
  90935. c.norU1Y = norY * this.m1;
  90936. c.norU1Z = norZ * this.m1;
  90937. c.norU2X = norX * this.m2;
  90938. c.norU2Y = norY * this.m2;
  90939. c.norU2Z = norZ * this.m2;
  90940. c.tanU1X = tanX * this.m1;
  90941. c.tanU1Y = tanY * this.m1;
  90942. c.tanU1Z = tanZ * this.m1;
  90943. c.tanU2X = tanX * this.m2;
  90944. c.tanU2Y = tanY * this.m2;
  90945. c.tanU2Z = tanZ * this.m2;
  90946. c.binU1X = binX * this.m1;
  90947. c.binU1Y = binY * this.m1;
  90948. c.binU1Z = binZ * this.m1;
  90949. c.binU2X = binX * this.m2;
  90950. c.binU2Y = binY * this.m2;
  90951. c.binU2Z = binZ * this.m2;
  90952. var norT1X = rp1Y * norZ - rp1Z * norY;
  90953. var norT1Y = rp1Z * norX - rp1X * norZ;
  90954. var norT1Z = rp1X * norY - rp1Y * norX;
  90955. var norT2X = rp2Y * norZ - rp2Z * norY;
  90956. var norT2Y = rp2Z * norX - rp2X * norZ;
  90957. var norT2Z = rp2X * norY - rp2Y * norX;
  90958. var tanT1X = rp1Y * tanZ - rp1Z * tanY;
  90959. var tanT1Y = rp1Z * tanX - rp1X * tanZ;
  90960. var tanT1Z = rp1X * tanY - rp1Y * tanX;
  90961. var tanT2X = rp2Y * tanZ - rp2Z * tanY;
  90962. var tanT2Y = rp2Z * tanX - rp2X * tanZ;
  90963. var tanT2Z = rp2X * tanY - rp2Y * tanX;
  90964. var binT1X = rp1Y * binZ - rp1Z * binY;
  90965. var binT1Y = rp1Z * binX - rp1X * binZ;
  90966. var binT1Z = rp1X * binY - rp1Y * binX;
  90967. var binT2X = rp2Y * binZ - rp2Z * binY;
  90968. var binT2Y = rp2Z * binX - rp2X * binZ;
  90969. var binT2Z = rp2X * binY - rp2Y * binX;
  90970. var norTU1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  90971. var norTU1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  90972. var norTU1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  90973. var norTU2X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  90974. var norTU2Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  90975. var norTU2Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  90976. var tanTU1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  90977. var tanTU1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  90978. var tanTU1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  90979. var tanTU2X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  90980. var tanTU2Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  90981. var tanTU2Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  90982. var binTU1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  90983. var binTU1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  90984. var binTU1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  90985. var binTU2X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  90986. var binTU2Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  90987. var binTU2Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  90988. c.norT1X = norT1X;
  90989. c.norT1Y = norT1Y;
  90990. c.norT1Z = norT1Z;
  90991. c.tanT1X = tanT1X;
  90992. c.tanT1Y = tanT1Y;
  90993. c.tanT1Z = tanT1Z;
  90994. c.binT1X = binT1X;
  90995. c.binT1Y = binT1Y;
  90996. c.binT1Z = binT1Z;
  90997. c.norT2X = norT2X;
  90998. c.norT2Y = norT2Y;
  90999. c.norT2Z = norT2Z;
  91000. c.tanT2X = tanT2X;
  91001. c.tanT2Y = tanT2Y;
  91002. c.tanT2Z = tanT2Z;
  91003. c.binT2X = binT2X;
  91004. c.binT2Y = binT2Y;
  91005. c.binT2Z = binT2Z;
  91006. c.norTU1X = norTU1X;
  91007. c.norTU1Y = norTU1Y;
  91008. c.norTU1Z = norTU1Z;
  91009. c.tanTU1X = tanTU1X;
  91010. c.tanTU1Y = tanTU1Y;
  91011. c.tanTU1Z = tanTU1Z;
  91012. c.binTU1X = binTU1X;
  91013. c.binTU1Y = binTU1Y;
  91014. c.binTU1Z = binTU1Z;
  91015. c.norTU2X = norTU2X;
  91016. c.norTU2Y = norTU2Y;
  91017. c.norTU2Z = norTU2Z;
  91018. c.tanTU2X = tanTU2X;
  91019. c.tanTU2Y = tanTU2Y;
  91020. c.tanTU2Z = tanTU2Z;
  91021. c.binTU2X = binTU2X;
  91022. c.binTU2Y = binTU2Y;
  91023. c.binTU2Z = binTU2Z;
  91024. tmp1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  91025. tmp1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  91026. tmp1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  91027. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  91028. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  91029. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  91030. tmp1X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  91031. tmp1Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  91032. tmp1Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  91033. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  91034. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  91035. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  91036. var norDen = 1 / (m1m2 + norX * tmp2X + norY * tmp2Y + norZ * tmp2Z);
  91037. tmp1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  91038. tmp1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  91039. tmp1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  91040. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  91041. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  91042. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  91043. tmp1X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  91044. tmp1Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  91045. tmp1Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  91046. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  91047. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  91048. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  91049. var tanDen = 1 / (m1m2 + tanX * tmp2X + tanY * tmp2Y + tanZ * tmp2Z);
  91050. tmp1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  91051. tmp1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  91052. tmp1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  91053. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  91054. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  91055. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  91056. tmp1X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  91057. tmp1Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  91058. tmp1Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  91059. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  91060. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  91061. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  91062. var binDen = 1 / (m1m2 + binX * tmp2X + binY * tmp2Y + binZ * tmp2Z);
  91063. c.norDen = norDen;
  91064. c.tanDen = tanDen;
  91065. c.binDen = binDen;
  91066. if (p.warmStarted) {
  91067. var norImp = p.normalImpulse;
  91068. this.lv1.x += c.norU1X * norImp;
  91069. this.lv1.y += c.norU1Y * norImp;
  91070. this.lv1.z += c.norU1Z * norImp;
  91071. this.av1.x += norTU1X * norImp;
  91072. this.av1.y += norTU1Y * norImp;
  91073. this.av1.z += norTU1Z * norImp;
  91074. this.lv2.x -= c.norU2X * norImp;
  91075. this.lv2.y -= c.norU2Y * norImp;
  91076. this.lv2.z -= c.norU2Z * norImp;
  91077. this.av2.x -= norTU2X * norImp;
  91078. this.av2.y -= norTU2Y * norImp;
  91079. this.av2.z -= norTU2Z * norImp;
  91080. c.norImp = norImp;
  91081. c.tanImp = 0;
  91082. c.binImp = 0;
  91083. rvn = 0; // disable bouncing
  91084. } else {
  91085. c.norImp = 0;
  91086. c.tanImp = 0;
  91087. c.binImp = 0;
  91088. }
  91089. if (rvn > -1) {
  91090. rvn = 0; // disable bouncing
  91091. }
  91092. var norTar = this.restitution * -rvn;
  91093. var sepV = -(p.penetration + 0.005) * invTimeStep * 0.05; // allow 0.5cm error
  91094. if (norTar < sepV) norTar = sepV;
  91095. c.norTar = norTar;
  91096. c.last = i == this.num - 1;
  91097. c = c.next;
  91098. }
  91099. }
  91100. OIMO.ContactConstraint.prototype.solve = function () {
  91101. var lv1x = this.lv1.x;
  91102. var lv1y = this.lv1.y;
  91103. var lv1z = this.lv1.z;
  91104. var lv2x = this.lv2.x;
  91105. var lv2y = this.lv2.y;
  91106. var lv2z = this.lv2.z;
  91107. var av1x = this.av1.x;
  91108. var av1y = this.av1.y;
  91109. var av1z = this.av1.z;
  91110. var av2x = this.av2.x;
  91111. var av2y = this.av2.y;
  91112. var av2z = this.av2.z;
  91113. var c = this.cs;
  91114. while (true) {
  91115. var oldImp1;
  91116. var newImp1;
  91117. var oldImp2;
  91118. var newImp2;
  91119. var rvn;
  91120. var norImp = c.norImp;
  91121. var tanImp = c.tanImp;
  91122. var binImp = c.binImp;
  91123. var max = -norImp * this.friction;
  91124. var rvX = lv2x - lv1x;
  91125. var rvY = lv2y - lv1y;
  91126. var rvZ = lv2z - lv1z;
  91127. rvn =
  91128. rvX * c.tanX + rvY * c.tanY + rvZ * c.tanZ +
  91129. av2x * c.tanT2X + av2y * c.tanT2Y + av2z * c.tanT2Z -
  91130. av1x * c.tanT1X - av1y * c.tanT1Y - av1z * c.tanT1Z
  91131. ;
  91132. oldImp1 = tanImp;
  91133. newImp1 = rvn * c.tanDen;
  91134. tanImp += newImp1;
  91135. rvn =
  91136. rvX * c.binX + rvY * c.binY + rvZ * c.binZ +
  91137. av2x * c.binT2X + av2y * c.binT2Y + av2z * c.binT2Z -
  91138. av1x * c.binT1X - av1y * c.binT1Y - av1z * c.binT1Z
  91139. ;
  91140. oldImp2 = binImp;
  91141. newImp2 = rvn * c.binDen;
  91142. binImp += newImp2;
  91143. // cone friction clamp
  91144. var len = tanImp * tanImp + binImp * binImp;
  91145. if (len > max * max) {
  91146. len = max / OIMO.sqrt(len);
  91147. tanImp *= len;
  91148. binImp *= len;
  91149. }
  91150. newImp1 = tanImp - oldImp1;
  91151. newImp2 = binImp - oldImp2;
  91152. lv1x += c.tanU1X * newImp1 + c.binU1X * newImp2;
  91153. lv1y += c.tanU1Y * newImp1 + c.binU1Y * newImp2;
  91154. lv1z += c.tanU1Z * newImp1 + c.binU1Z * newImp2;
  91155. av1x += c.tanTU1X * newImp1 + c.binTU1X * newImp2;
  91156. av1y += c.tanTU1Y * newImp1 + c.binTU1Y * newImp2;
  91157. av1z += c.tanTU1Z * newImp1 + c.binTU1Z * newImp2;
  91158. lv2x -= c.tanU2X * newImp1 + c.binU2X * newImp2;
  91159. lv2y -= c.tanU2Y * newImp1 + c.binU2Y * newImp2;
  91160. lv2z -= c.tanU2Z * newImp1 + c.binU2Z * newImp2;
  91161. av2x -= c.tanTU2X * newImp1 + c.binTU2X * newImp2;
  91162. av2y -= c.tanTU2Y * newImp1 + c.binTU2Y * newImp2;
  91163. av2z -= c.tanTU2Z * newImp1 + c.binTU2Z * newImp2;
  91164. // restitution part
  91165. rvn =
  91166. (lv2x - lv1x) * c.norX + (lv2y - lv1y) * c.norY + (lv2z - lv1z) * c.norZ +
  91167. av2x * c.norT2X + av2y * c.norT2Y + av2z * c.norT2Z -
  91168. av1x * c.norT1X - av1y * c.norT1Y - av1z * c.norT1Z;
  91169. oldImp1 = norImp;
  91170. newImp1 = (rvn - c.norTar) * c.norDen;
  91171. norImp += newImp1;
  91172. if (norImp > 0) norImp = 0;
  91173. newImp1 = norImp - oldImp1;
  91174. lv1x += c.norU1X * newImp1;
  91175. lv1y += c.norU1Y * newImp1;
  91176. lv1z += c.norU1Z * newImp1;
  91177. av1x += c.norTU1X * newImp1;
  91178. av1y += c.norTU1Y * newImp1;
  91179. av1z += c.norTU1Z * newImp1;
  91180. lv2x -= c.norU2X * newImp1;
  91181. lv2y -= c.norU2Y * newImp1;
  91182. lv2z -= c.norU2Z * newImp1;
  91183. av2x -= c.norTU2X * newImp1;
  91184. av2y -= c.norTU2Y * newImp1;
  91185. av2z -= c.norTU2Z * newImp1;
  91186. c.norImp = norImp;
  91187. c.tanImp = tanImp;
  91188. c.binImp = binImp;
  91189. if (c.last) break;
  91190. c = c.next;
  91191. }
  91192. this.lv1.x = lv1x;
  91193. this.lv1.y = lv1y;
  91194. this.lv1.z = lv1z;
  91195. this.lv2.x = lv2x;
  91196. this.lv2.y = lv2y;
  91197. this.lv2.z = lv2z;
  91198. this.av1.x = av1x;
  91199. this.av1.y = av1y;
  91200. this.av1.z = av1z;
  91201. this.av2.x = av2x;
  91202. this.av2.y = av2y;
  91203. this.av2.z = av2z;
  91204. }
  91205. OIMO.ContactConstraint.prototype.postSolve = function () {
  91206. var c = this.cs;
  91207. var i = this.num;
  91208. while (i--) {
  91209. //for(var i=0;i<this.num;i++){
  91210. var p = this.ps[i];
  91211. p.normal.x = c.norX;
  91212. p.normal.y = c.norY;
  91213. p.normal.z = c.norZ;
  91214. p.tangent.x = c.tanX;
  91215. p.tangent.y = c.tanY;
  91216. p.tangent.z = c.tanZ;
  91217. p.binormal.x = c.binX;
  91218. p.binormal.y = c.binY;
  91219. p.binormal.z = c.binZ;
  91220. p.normalImpulse = c.norImp;
  91221. p.tangentImpulse = c.tanImp;
  91222. p.binormalImpulse = c.binImp;
  91223. p.normalDenominator = c.norDen;
  91224. p.tangentDenominator = c.tanDen;
  91225. p.binormalDenominator = c.binDen;
  91226. c = c.next;
  91227. }
  91228. }
  91229. /**
  91230. * A link list of contacts.
  91231. * @author saharan
  91232. */
  91233. OIMO.ContactLink = function (contact) {
  91234. // The previous contact link.
  91235. this.prev = null;
  91236. // The next contact link.
  91237. this.next = null;
  91238. // The shape of the contact.
  91239. this.shape = null;
  91240. // The other rigid body.
  91241. this.body = null;
  91242. // The contact of the link.
  91243. this.contact = contact;
  91244. }
  91245. /**
  91246. * A contact manifold between two shapes.
  91247. * @author saharan
  91248. */
  91249. OIMO.ContactManifold = function () {
  91250. // The first rigid body.
  91251. this.body1 = null;
  91252. // The second rigid body.
  91253. this.body2 = null;
  91254. // The number of manifold points.
  91255. this.numPoints = 0;
  91256. // The manifold points.
  91257. this.points = [];
  91258. this.points.length = 4;
  91259. this.points[0] = new OIMO.ManifoldPoint();
  91260. this.points[1] = new OIMO.ManifoldPoint();
  91261. this.points[2] = new OIMO.ManifoldPoint();
  91262. this.points[3] = new OIMO.ManifoldPoint();
  91263. }
  91264. OIMO.ContactManifold.prototype = {
  91265. constructor: OIMO.ContactManifold,
  91266. /**
  91267. * Reset the manifold.
  91268. * @param shape1
  91269. * @param shape2
  91270. */
  91271. reset: function (shape1, shape2) {
  91272. this.body1 = shape1.parent;
  91273. this.body2 = shape2.parent;
  91274. this.numPoints = 0;
  91275. },
  91276. /**
  91277. * Add a point into this manifold.
  91278. * @param x
  91279. * @param y
  91280. * @param z
  91281. * @param normalX
  91282. * @param normalY
  91283. * @param normalZ
  91284. * @param penetration
  91285. * @param flip
  91286. */
  91287. addPoint: function (x, y, z, normalX, normalY, normalZ, penetration, flip) {
  91288. var p = this.points[this.numPoints++];
  91289. p.position.x = x;
  91290. p.position.y = y;
  91291. p.position.z = z;
  91292. var r = this.body1.rotation;
  91293. var rx = x - this.body1.position.x;
  91294. var ry = y - this.body1.position.y;
  91295. var rz = z - this.body1.position.z;
  91296. var tr = r.elements;
  91297. p.localPoint1.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  91298. p.localPoint1.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  91299. p.localPoint1.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  91300. r = this.body2.rotation;
  91301. rx = x - this.body2.position.x;
  91302. ry = y - this.body2.position.y;
  91303. rz = z - this.body2.position.z;
  91304. p.localPoint2.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  91305. p.localPoint2.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  91306. p.localPoint2.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  91307. p.normalImpulse = 0;
  91308. if (flip) {
  91309. p.normal.x = -normalX;
  91310. p.normal.y = -normalY;
  91311. p.normal.z = -normalZ;
  91312. } else {
  91313. p.normal.x = normalX;
  91314. p.normal.y = normalY;
  91315. p.normal.z = normalZ;
  91316. }
  91317. p.penetration = penetration;
  91318. p.warmStarted = false;
  91319. }
  91320. }
  91321. OIMO.ContactPointDataBuffer = function () {
  91322. this.norX = NaN;
  91323. this.norY = NaN;
  91324. this.norZ = NaN;
  91325. this.tanX = NaN;
  91326. this.tanY = NaN;
  91327. this.tanZ = NaN;
  91328. this.binX = NaN;
  91329. this.binY = NaN;
  91330. this.binZ = NaN;
  91331. this.rp1X = NaN;
  91332. this.rp1Y = NaN;
  91333. this.rp1Z = NaN;
  91334. this.rp2X = NaN;
  91335. this.rp2Y = NaN;
  91336. this.rp2Z = NaN;
  91337. this.norU1X = NaN;
  91338. this.norU1Y = NaN;
  91339. this.norU1Z = NaN;
  91340. this.norU2X = NaN;
  91341. this.norU2Y = NaN;
  91342. this.norU2Z = NaN;
  91343. this.tanU1X = NaN;
  91344. this.tanU1Y = NaN;
  91345. this.tanU1Z = NaN;
  91346. this.tanU2X = NaN;
  91347. this.tanU2Y = NaN;
  91348. this.tanU2Z = NaN;
  91349. this.binU1X = NaN;
  91350. this.binU1Y = NaN;
  91351. this.binU1Z = NaN;
  91352. this.binU2X = NaN;
  91353. this.binU2Y = NaN;
  91354. this.binU2Z = NaN;
  91355. this.norT1X = NaN;
  91356. this.norT1Y = NaN;
  91357. this.norT1Z = NaN;
  91358. this.norT2X = NaN;
  91359. this.norT2Y = NaN;
  91360. this.norT2Z = NaN;
  91361. this.tanT1X = NaN;
  91362. this.tanT1Y = NaN;
  91363. this.tanT1Z = NaN;
  91364. this.tanT2X = NaN;
  91365. this.tanT2Y = NaN;
  91366. this.tanT2Z = NaN;
  91367. this.binT1X = NaN;
  91368. this.binT1Y = NaN;
  91369. this.binT1Z = NaN;
  91370. this.binT2X = NaN;
  91371. this.binT2Y = NaN;
  91372. this.binT2Z = NaN;
  91373. this.norTU1X = NaN;
  91374. this.norTU1Y = NaN;
  91375. this.norTU1Z = NaN;
  91376. this.norTU2X = NaN;
  91377. this.norTU2Y = NaN;
  91378. this.norTU2Z = NaN;
  91379. this.tanTU1X = NaN;
  91380. this.tanTU1Y = NaN;
  91381. this.tanTU1Z = NaN;
  91382. this.tanTU2X = NaN;
  91383. this.tanTU2Y = NaN;
  91384. this.tanTU2Z = NaN;
  91385. this.binTU1X = NaN;
  91386. this.binTU1Y = NaN;
  91387. this.binTU1Z = NaN;
  91388. this.binTU2X = NaN;
  91389. this.binTU2Y = NaN;
  91390. this.binTU2Z = NaN;
  91391. this.norImp = NaN;
  91392. this.tanImp = NaN;
  91393. this.binImp = NaN;
  91394. this.norDen = NaN;
  91395. this.tanDen = NaN;
  91396. this.binDen = NaN;
  91397. this.norTar = NaN;
  91398. this.next = null;
  91399. this.last = false;
  91400. }
  91401. OIMO.ImpulseDataBuffer = function () {
  91402. this.lp1X = NaN;
  91403. this.lp1Y = NaN;
  91404. this.lp1Z = NaN;
  91405. this.lp2X = NaN;
  91406. this.lp2Y = NaN;
  91407. this.lp2Z = NaN;
  91408. this.impulse = NaN;
  91409. }
  91410. /**
  91411. * The class holds details of the contact point.
  91412. * @author saharan
  91413. */
  91414. OIMO.ManifoldPoint = function () {
  91415. // Whether this manifold point is persisting or not.
  91416. this.warmStarted = false;
  91417. // The position of this manifold point.
  91418. this.position = new OIMO.Vec3();
  91419. // The position in the first shape's coordinate.
  91420. this.localPoint1 = new OIMO.Vec3();
  91421. // The position in the second shape's coordinate.
  91422. this.localPoint2 = new OIMO.Vec3();
  91423. // The normal vector of this manifold point.
  91424. this.normal = new OIMO.Vec3();
  91425. // The tangent vector of this manifold point.
  91426. this.tangent = new OIMO.Vec3();
  91427. // The binormal vector of this manifold point.
  91428. this.binormal = new OIMO.Vec3();
  91429. // The impulse in normal direction.
  91430. this.normalImpulse = 0;
  91431. // The impulse in tangent direction.
  91432. this.tangentImpulse = 0;
  91433. // The impulse in binormal direction.
  91434. this.binormalImpulse = 0;
  91435. // The denominator in normal direction.
  91436. this.normalDenominator = 0;
  91437. // The denominator in tangent direction.
  91438. this.tangentDenominator = 0;
  91439. // The denominator in binormal direction.
  91440. this.binormalDenominator = 0;
  91441. // The depth of penetration.
  91442. this.penetration = 0;
  91443. }
  91444. /**
  91445. * This class holds mass information of a shape.
  91446. * @author saharan
  91447. */
  91448. OIMO.MassInfo = function () {
  91449. // Mass of the shape.
  91450. this.mass = 0;
  91451. // The moment inertia of the shape.
  91452. this.inertia = new OIMO.Mat33();
  91453. };
  91454. /**
  91455. * A shape is used to detect collisions of rigid bodies.
  91456. * @author saharan
  91457. * @author lo-th
  91458. */
  91459. OIMO.Shape = function (config) {
  91460. this.type = OIMO.SHAPE_NULL;
  91461. // The global identification of the shape should be unique to the shape.
  91462. this.id = OIMO.nextID++;
  91463. // The previous shape in parent rigid body.
  91464. this.prev = null;
  91465. // The next shape in parent rigid body.
  91466. this.next = null;
  91467. // The proxy of the shape used for broad-phase collision detection.
  91468. this.proxy = null;
  91469. // The parent rigid body of the shape.
  91470. this.parent = null;
  91471. // The linked list of the contacts with the shape.
  91472. this.contactLink = null;
  91473. // The number of the contacts with the shape.
  91474. this.numContacts = 0;
  91475. // The center of gravity of the shape in world coordinate system.
  91476. this.position = new OIMO.Vec3();
  91477. // The rotation matrix of the shape in world coordinate system
  91478. this.rotation = new OIMO.Mat33();
  91479. // The position of the shape in parent's coordinate system.
  91480. this.relativePosition = new OIMO.Vec3().copy(config.relativePosition);
  91481. // The rotation matrix of the shape in parent's coordinate system.
  91482. this.relativeRotation = new OIMO.Mat33().copy(config.relativeRotation);
  91483. // The axis-aligned bounding box of the shape.
  91484. this.aabb = new OIMO.AABB();
  91485. // The density of the shape.
  91486. this.density = config.density;
  91487. // The coefficient of friction of the shape.
  91488. this.friction = config.friction;
  91489. // The coefficient of restitution of the shape.
  91490. this.restitution = config.restitution;
  91491. // The bits of the collision groups to which the shape belongs.
  91492. this.belongsTo = config.belongsTo;
  91493. // The bits of the collision groups with which the shape collides.
  91494. this.collidesWith = config.collidesWith;
  91495. };
  91496. OIMO.Shape.prototype = {
  91497. constructor: OIMO.Shape,
  91498. // Calculate the mass information of the shape.
  91499. calculateMassInfo: function (out) {
  91500. OIMO.Error("Shape", "Inheritance error.");
  91501. },
  91502. // Update the proxy of the shape.
  91503. updateProxy: function () {
  91504. OIMO.Error("Shape", "Inheritance error.");
  91505. }
  91506. };
  91507. /**
  91508. * A shape configuration holds common configuration data for constructing a shape.
  91509. * Shape configurations can be reused safely.
  91510. * @author saharan
  91511. */
  91512. OIMO.ShapeConfig = function () {
  91513. // The position of the shape in parent's coordinate system.
  91514. this.relativePosition = new OIMO.Vec3();
  91515. // The rotation matrix of the shape in parent's coordinate system.
  91516. this.relativeRotation = new OIMO.Mat33();
  91517. // The coefficient of friction of the shape.
  91518. this.friction = 0.4;
  91519. // The coefficient of restitution of the shape.
  91520. this.restitution = 0.2;
  91521. // The density of the shape.
  91522. this.density = 1;
  91523. // The bits of the collision groups to which the shape belongs.
  91524. this.belongsTo = 1;
  91525. // The bits of the collision groups with which the shape collides.
  91526. this.collidesWith = 0xffffffff;
  91527. };
  91528. /**
  91529. * A box shape.
  91530. * @author saharan
  91531. * @author lo-th
  91532. */
  91533. OIMO.BoxShape = function (config, Width, Height, Depth) {
  91534. OIMO.Shape.call(this, config);
  91535. this.type = OIMO.SHAPE_BOX;
  91536. // The width of the box.
  91537. this.width = Width;
  91538. // The height of the box.
  91539. this.height = Height;
  91540. // The depth of the box.
  91541. this.depth = Depth;
  91542. // The half-width of the box.
  91543. this.halfWidth = Width * 0.5;
  91544. // The half-height of the box.
  91545. this.halfHeight = Height * 0.5;
  91546. // The half-depth of the box.
  91547. this.halfDepth = Depth * 0.5;
  91548. this.dimentions = new OIMO_ARRAY_TYPE(18);
  91549. this.elements = new OIMO_ARRAY_TYPE(24);
  91550. };
  91551. OIMO.BoxShape.prototype = Object.create(OIMO.Shape.prototype);
  91552. OIMO.BoxShape.prototype.constructor = OIMO.BoxShape;
  91553. OIMO.BoxShape.prototype.calculateMassInfo = function (out) {
  91554. var mass = this.width * this.height * this.depth * this.density;
  91555. var divid = 1 / 12;
  91556. out.mass = mass;
  91557. out.inertia.set(
  91558. mass * (this.height * this.height + this.depth * this.depth) * divid, 0, 0,
  91559. 0, mass * (this.width * this.width + this.depth * this.depth) * divid, 0,
  91560. 0, 0, mass * (this.width * this.width + this.height * this.height) * divid
  91561. );
  91562. };
  91563. OIMO.BoxShape.prototype.updateProxy = function () {
  91564. var te = this.rotation.elements;
  91565. var di = this.dimentions;
  91566. // Width
  91567. di[0] = te[0];
  91568. di[1] = te[3];
  91569. di[2] = te[6];
  91570. // Height
  91571. di[3] = te[1];
  91572. di[4] = te[4];
  91573. di[5] = te[7];
  91574. // Depth
  91575. di[6] = te[2];
  91576. di[7] = te[5];
  91577. di[8] = te[8];
  91578. // halp Width
  91579. di[9] = te[0] * this.halfWidth;
  91580. di[10] = te[3] * this.halfWidth;
  91581. di[11] = te[6] * this.halfWidth;
  91582. // halp Height
  91583. di[12] = te[1] * this.halfHeight;
  91584. di[13] = te[4] * this.halfHeight;
  91585. di[14] = te[7] * this.halfHeight;
  91586. // halp Depth
  91587. di[15] = te[2] * this.halfDepth;
  91588. di[16] = te[5] * this.halfDepth;
  91589. di[17] = te[8] * this.halfDepth;
  91590. var wx = di[9];
  91591. var wy = di[10];
  91592. var wz = di[11];
  91593. var hx = di[12];
  91594. var hy = di[13];
  91595. var hz = di[14];
  91596. var dx = di[15];
  91597. var dy = di[16];
  91598. var dz = di[17];
  91599. var x = this.position.x;
  91600. var y = this.position.y;
  91601. var z = this.position.z;
  91602. var v = this.elements;
  91603. //v1
  91604. v[0] = x + wx + hx + dx;
  91605. v[1] = y + wy + hy + dy;
  91606. v[2] = z + wz + hz + dz;
  91607. //v2
  91608. v[3] = x + wx + hx - dx;
  91609. v[4] = y + wy + hy - dy;
  91610. v[5] = z + wz + hz - dz;
  91611. //v3
  91612. v[6] = x + wx - hx + dx;
  91613. v[7] = y + wy - hy + dy;
  91614. v[8] = z + wz - hz + dz;
  91615. //v4
  91616. v[9] = x + wx - hx - dx;
  91617. v[10] = y + wy - hy - dy;
  91618. v[11] = z + wz - hz - dz;
  91619. //v5
  91620. v[12] = x - wx + hx + dx;
  91621. v[13] = y - wy + hy + dy;
  91622. v[14] = z - wz + hz + dz;
  91623. //v6
  91624. v[15] = x - wx + hx - dx;
  91625. v[16] = y - wy + hy - dy;
  91626. v[17] = z - wz + hz - dz;
  91627. //v7
  91628. v[18] = x - wx - hx + dx;
  91629. v[19] = y - wy - hy + dy;
  91630. v[20] = z - wz - hz + dz;
  91631. //v8
  91632. v[21] = x - wx - hx - dx;
  91633. v[22] = y - wy - hy - dy;
  91634. v[23] = z - wz - hz - dz;
  91635. var w = di[9] < 0 ? -di[9] : di[9];
  91636. var h = di[10] < 0 ? -di[10] : di[10];
  91637. var d = di[11] < 0 ? -di[11] : di[11];
  91638. w = di[12] < 0 ? w - di[12] : w + di[12];
  91639. h = di[13] < 0 ? h - di[13] : h + di[13];
  91640. d = di[14] < 0 ? d - di[14] : d + di[14];
  91641. w = di[15] < 0 ? w - di[15] : w + di[15];
  91642. h = di[16] < 0 ? h - di[16] : h + di[16];
  91643. d = di[17] < 0 ? d - di[17] : d + di[17];
  91644. var p = OIMO.AABB_PROX;
  91645. this.aabb.set(
  91646. this.position.x - w - p, this.position.x + w + p,
  91647. this.position.y - h - p, this.position.y + h + p,
  91648. this.position.z - d - p, this.position.z + d + p
  91649. );
  91650. if (this.proxy != null) this.proxy.update();
  91651. };
  91652. /**
  91653. * A sphere shape.
  91654. * @author saharan
  91655. * @author lo-th
  91656. */
  91657. OIMO.SphereShape = function (config, radius) {
  91658. OIMO.Shape.call(this, config);
  91659. this.type = OIMO.SHAPE_SPHERE;
  91660. // The radius of the shape.
  91661. this.radius = radius;
  91662. };
  91663. OIMO.SphereShape.prototype = Object.create(OIMO.Shape.prototype);
  91664. OIMO.SphereShape.prototype.constructor = OIMO.SphereShape;
  91665. OIMO.SphereShape.prototype.calculateMassInfo = function (out) {
  91666. var mass = 1.333 * OIMO.PI * this.radius * this.radius * this.radius * this.density;
  91667. out.mass = mass;
  91668. var inertia = mass * this.radius * this.radius * 0.4;
  91669. out.inertia.set(inertia, 0, 0, 0, inertia, 0, 0, 0, inertia);
  91670. };
  91671. OIMO.SphereShape.prototype.updateProxy = function () {
  91672. var p = OIMO.AABB_PROX;
  91673. this.aabb.set(
  91674. this.position.x - this.radius - p, this.position.x + this.radius + p,
  91675. this.position.y - this.radius - p, this.position.y + this.radius + p,
  91676. this.position.z - this.radius - p, this.position.z + this.radius + p
  91677. );
  91678. if (this.proxy != null) this.proxy.update();
  91679. };
  91680. /**
  91681. * A cylinder shap.
  91682. * @author saharan
  91683. * @author lo-th
  91684. */
  91685. OIMO.CylinderShape = function (config, radius, height) {
  91686. OIMO.Shape.call(this, config);
  91687. this.type = OIMO.SHAPE_CYLINDER;
  91688. this.radius = radius;
  91689. this.height = height;
  91690. this.halfHeight = height * 0.5;
  91691. this.normalDirection = new OIMO.Vec3();
  91692. this.halfDirection = new OIMO.Vec3();
  91693. };
  91694. OIMO.CylinderShape.prototype = Object.create(OIMO.Shape.prototype);
  91695. OIMO.CylinderShape.prototype.constructor = OIMO.CylinderShape;
  91696. OIMO.CylinderShape.prototype.calculateMassInfo = function (out) {
  91697. var rsq = this.radius * this.radius;
  91698. var mass = OIMO.PI * rsq * this.height * this.density;
  91699. var inertiaXZ = ((0.25 * rsq) + (0.0833 * this.height * this.height)) * mass;
  91700. var inertiaY = 0.5 * rsq;
  91701. out.mass = mass;
  91702. out.inertia.set(inertiaXZ, 0, 0, 0, inertiaY, 0, 0, 0, inertiaXZ);
  91703. };
  91704. OIMO.CylinderShape.prototype.updateProxy = function () {
  91705. var te = this.rotation.elements;
  91706. var len, wx, hy, dz, xx, yy, zz, w, h, d, p;
  91707. xx = te[1] * te[1];
  91708. yy = te[4] * te[4];
  91709. zz = te[7] * te[7];
  91710. this.normalDirection.set(te[1], te[4], te[7]);
  91711. this.halfDirection.scale(this.normalDirection, this.halfHeight);
  91712. wx = 1 - xx;
  91713. len = OIMO.sqrt(wx * wx + xx * yy + xx * zz);
  91714. if (len > 0) len = this.radius / len;
  91715. wx *= len;
  91716. hy = 1 - yy;
  91717. len = OIMO.sqrt(yy * xx + hy * hy + yy * zz);
  91718. if (len > 0) len = this.radius / len;
  91719. hy *= len;
  91720. dz = 1 - zz;
  91721. len = OIMO.sqrt(zz * xx + zz * yy + dz * dz);
  91722. if (len > 0) len = this.radius / len;
  91723. dz *= len;
  91724. w = this.halfDirection.x < 0 ? -this.halfDirection.x : this.halfDirection.x;
  91725. h = this.halfDirection.y < 0 ? -this.halfDirection.y : this.halfDirection.y;
  91726. d = this.halfDirection.z < 0 ? -this.halfDirection.z : this.halfDirection.z;
  91727. w = wx < 0 ? w - wx : w + wx;
  91728. h = hy < 0 ? h - hy : h + hy;
  91729. d = dz < 0 ? d - dz : d + dz;
  91730. p = OIMO.AABB_PROX;
  91731. this.aabb.set(
  91732. this.position.x - w - p, this.position.x + w + p,
  91733. this.position.y - h - p, this.position.y + h + p,
  91734. this.position.z - d - p, this.position.z + d + p
  91735. );
  91736. if (this.proxy != null) this.proxy.update();
  91737. };
  91738. /**
  91739. * A tetra shape.
  91740. * @author xprogram
  91741. */
  91742. OIMO.TetraShape = function (config, p1, p2, p3, p4) {
  91743. OIMO.Shape.call(this, config);
  91744. this.type = OIMO.SHAPE_TETRA;
  91745. // Vertices and faces of tetra
  91746. this.verts = [p1, p2, p3, p4];
  91747. this.faces = [
  91748. mtri(0, 1, 2),
  91749. mtri(1, 2, 3),
  91750. mtri(2, 3, 4),
  91751. mtri(4, 0, 1),
  91752. ];
  91753. };
  91754. OIMO.TetraShape.prototype = Object.create(OIMO.Shape.prototype);
  91755. OIMO.TetraShape.prototype.constructor = OIMO.TetraShape;
  91756. OIMO.TetraShape.prototype.calculateMassInfo = function () {
  91757. // I guess you could calculate box mass and split it
  91758. // in half for the tetra...
  91759. };
  91760. OIMO.TetraShape.prototype.updateProxy = function () {
  91761. this.aabb.setFromPoints(this.verts);
  91762. if (this.proxy !== null)
  91763. this.proxy.update();
  91764. };
  91765. function mtri(a, b, c) {
  91766. return { a: a, b: b, c: c };
  91767. }
  91768. OIMO.CollisionDetector = function () {
  91769. this.flip = false;
  91770. };
  91771. OIMO.CollisionDetector.prototype = {
  91772. constructor: OIMO.CollisionDetector,
  91773. detectCollision: function (shape1, shape2, manifold) {
  91774. OIMO.Error("CollisionDetector", "Inheritance error.");
  91775. }
  91776. };
  91777. /**
  91778. * A collision detector which detects collisions between two boxes.
  91779. * @author saharan
  91780. */
  91781. OIMO.BoxBoxCollisionDetector = function () {
  91782. OIMO.CollisionDetector.call(this);
  91783. this.clipVertices1 = new OIMO_ARRAY_TYPE(24); // 8 vertices x,y,z
  91784. this.clipVertices2 = new OIMO_ARRAY_TYPE(24);
  91785. this.used = new OIMO_ARRAY_TYPE(8);
  91786. this.INF = 1 / 0;
  91787. };
  91788. OIMO.BoxBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  91789. OIMO.BoxBoxCollisionDetector.prototype.constructor = OIMO.BoxBoxCollisionDetector;
  91790. OIMO.BoxBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  91791. // What you are doing
  91792. // · I to prepare a separate axis of the fifteen
  91793. //-Six in each of three normal vectors of the xyz direction of the box both
  91794. // · Remaining nine 3x3 a vector perpendicular to the side of the box 2 and the side of the box 1
  91795. // · Calculate the depth to the separation axis
  91796. // Calculates the distance using the inner product and put the amount of embedment
  91797. // · However a vertical separation axis and side to weight a little to avoid vibration
  91798. // And end when there is a separate axis that is remote even one
  91799. // · I look for separation axis with little to dent most
  91800. // Men and if separation axis of the first six - end collision
  91801. // Heng If it separate axis of nine other - side collision
  91802. // Heng - case of a side collision
  91803. // · Find points of two sides on which you made ​​the separation axis
  91804. // Calculates the point of closest approach of a straight line consisting of separate axis points obtained, and the collision point
  91805. //-Surface - the case of the plane crash
  91806. //-Box A, box B and the other a box of better made ​​a separate axis
  91807. // • 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
  91808. // When viewed from the front surface A, and the cut part exceeding the area of the surface A is a surface B
  91809. //-Plane B becomes the 3-8 triangle, I a candidate for the collision point the vertex of surface B
  91810. // • If more than one candidate 5 exists, scraping up to four
  91811. // For potential collision points of all, to examine the distance between the surface A
  91812. // • If you were on the inside surface of A, and the collision point
  91813. var b1;
  91814. var b2;
  91815. if (shape1.id < shape2.id) {
  91816. b1 = (shape1);
  91817. b2 = (shape2);
  91818. } else {
  91819. b1 = (shape2);
  91820. b2 = (shape1);
  91821. }
  91822. var V1 = b1.elements;
  91823. var V2 = b2.elements;
  91824. var D1 = b1.dimentions;
  91825. var D2 = b2.dimentions;
  91826. var p1 = b1.position;
  91827. var p2 = b2.position;
  91828. var p1x = p1.x;
  91829. var p1y = p1.y;
  91830. var p1z = p1.z;
  91831. var p2x = p2.x;
  91832. var p2y = p2.y;
  91833. var p2z = p2.z;
  91834. // diff
  91835. var dx = p2x - p1x;
  91836. var dy = p2y - p1y;
  91837. var dz = p2z - p1z;
  91838. // distance
  91839. var w1 = b1.halfWidth;
  91840. var h1 = b1.halfHeight;
  91841. var d1 = b1.halfDepth;
  91842. var w2 = b2.halfWidth;
  91843. var h2 = b2.halfHeight;
  91844. var d2 = b2.halfDepth;
  91845. // direction
  91846. // ----------------------------
  91847. // 15 separating axes
  91848. // 1~6: face
  91849. // 7~f: edge
  91850. // http://marupeke296.com/COL_3D_No13_OBBvsOBB.html
  91851. // ----------------------------
  91852. var a1x = D1[0];
  91853. var a1y = D1[1];
  91854. var a1z = D1[2];
  91855. var a2x = D1[3];
  91856. var a2y = D1[4];
  91857. var a2z = D1[5];
  91858. var a3x = D1[6];
  91859. var a3y = D1[7];
  91860. var a3z = D1[8];
  91861. var d1x = D1[9];
  91862. var d1y = D1[10];
  91863. var d1z = D1[11];
  91864. var d2x = D1[12];
  91865. var d2y = D1[13];
  91866. var d2z = D1[14];
  91867. var d3x = D1[15];
  91868. var d3y = D1[16];
  91869. var d3z = D1[17];
  91870. var a4x = D2[0];
  91871. var a4y = D2[1];
  91872. var a4z = D2[2];
  91873. var a5x = D2[3];
  91874. var a5y = D2[4];
  91875. var a5z = D2[5];
  91876. var a6x = D2[6];
  91877. var a6y = D2[7];
  91878. var a6z = D2[8];
  91879. var d4x = D2[9];
  91880. var d4y = D2[10];
  91881. var d4z = D2[11];
  91882. var d5x = D2[12];
  91883. var d5y = D2[13];
  91884. var d5z = D2[14];
  91885. var d6x = D2[15];
  91886. var d6y = D2[16];
  91887. var d6z = D2[17];
  91888. var a7x = a1y * a4z - a1z * a4y;
  91889. var a7y = a1z * a4x - a1x * a4z;
  91890. var a7z = a1x * a4y - a1y * a4x;
  91891. var a8x = a1y * a5z - a1z * a5y;
  91892. var a8y = a1z * a5x - a1x * a5z;
  91893. var a8z = a1x * a5y - a1y * a5x;
  91894. var a9x = a1y * a6z - a1z * a6y;
  91895. var a9y = a1z * a6x - a1x * a6z;
  91896. var a9z = a1x * a6y - a1y * a6x;
  91897. var aax = a2y * a4z - a2z * a4y;
  91898. var aay = a2z * a4x - a2x * a4z;
  91899. var aaz = a2x * a4y - a2y * a4x;
  91900. var abx = a2y * a5z - a2z * a5y;
  91901. var aby = a2z * a5x - a2x * a5z;
  91902. var abz = a2x * a5y - a2y * a5x;
  91903. var acx = a2y * a6z - a2z * a6y;
  91904. var acy = a2z * a6x - a2x * a6z;
  91905. var acz = a2x * a6y - a2y * a6x;
  91906. var adx = a3y * a4z - a3z * a4y;
  91907. var ady = a3z * a4x - a3x * a4z;
  91908. var adz = a3x * a4y - a3y * a4x;
  91909. var aex = a3y * a5z - a3z * a5y;
  91910. var aey = a3z * a5x - a3x * a5z;
  91911. var aez = a3x * a5y - a3y * a5x;
  91912. var afx = a3y * a6z - a3z * a6y;
  91913. var afy = a3z * a6x - a3x * a6z;
  91914. var afz = a3x * a6y - a3y * a6x;
  91915. // right or left flags
  91916. var right1;
  91917. var right2;
  91918. var right3;
  91919. var right4;
  91920. var right5;
  91921. var right6;
  91922. var right7;
  91923. var right8;
  91924. var right9;
  91925. var righta;
  91926. var rightb;
  91927. var rightc;
  91928. var rightd;
  91929. var righte;
  91930. var rightf;
  91931. // overlapping distances
  91932. var overlap1;
  91933. var overlap2;
  91934. var overlap3;
  91935. var overlap4;
  91936. var overlap5;
  91937. var overlap6;
  91938. var overlap7;
  91939. var overlap8;
  91940. var overlap9;
  91941. var overlapa;
  91942. var overlapb;
  91943. var overlapc;
  91944. var overlapd;
  91945. var overlape;
  91946. var overlapf;
  91947. // invalid flags
  91948. var invalid7 = false;
  91949. var invalid8 = false;
  91950. var invalid9 = false;
  91951. var invalida = false;
  91952. var invalidb = false;
  91953. var invalidc = false;
  91954. var invalidd = false;
  91955. var invalide = false;
  91956. var invalidf = false;
  91957. // temporary variables
  91958. var len;
  91959. var len1;
  91960. var len2;
  91961. var dot1;
  91962. var dot2;
  91963. var dot3;
  91964. // try axis 1
  91965. len = a1x * dx + a1y * dy + a1z * dz;
  91966. right1 = len > 0;
  91967. if (!right1) len = -len;
  91968. len1 = w1;
  91969. dot1 = a1x * a4x + a1y * a4y + a1z * a4z;
  91970. dot2 = a1x * a5x + a1y * a5y + a1z * a5z;
  91971. dot3 = a1x * a6x + a1y * a6y + a1z * a6z;
  91972. if (dot1 < 0) dot1 = -dot1;
  91973. if (dot2 < 0) dot2 = -dot2;
  91974. if (dot3 < 0) dot3 = -dot3;
  91975. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  91976. overlap1 = len - len1 - len2;
  91977. if (overlap1 > 0) return;
  91978. // try axis 2
  91979. len = a2x * dx + a2y * dy + a2z * dz;
  91980. right2 = len > 0;
  91981. if (!right2) len = -len;
  91982. len1 = h1;
  91983. dot1 = a2x * a4x + a2y * a4y + a2z * a4z;
  91984. dot2 = a2x * a5x + a2y * a5y + a2z * a5z;
  91985. dot3 = a2x * a6x + a2y * a6y + a2z * a6z;
  91986. if (dot1 < 0) dot1 = -dot1;
  91987. if (dot2 < 0) dot2 = -dot2;
  91988. if (dot3 < 0) dot3 = -dot3;
  91989. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  91990. overlap2 = len - len1 - len2;
  91991. if (overlap2 > 0) return;
  91992. // try axis 3
  91993. len = a3x * dx + a3y * dy + a3z * dz;
  91994. right3 = len > 0;
  91995. if (!right3) len = -len;
  91996. len1 = d1;
  91997. dot1 = a3x * a4x + a3y * a4y + a3z * a4z;
  91998. dot2 = a3x * a5x + a3y * a5y + a3z * a5z;
  91999. dot3 = a3x * a6x + a3y * a6y + a3z * a6z;
  92000. if (dot1 < 0) dot1 = -dot1;
  92001. if (dot2 < 0) dot2 = -dot2;
  92002. if (dot3 < 0) dot3 = -dot3;
  92003. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  92004. overlap3 = len - len1 - len2;
  92005. if (overlap3 > 0) return;
  92006. // try axis 4
  92007. len = a4x * dx + a4y * dy + a4z * dz;
  92008. right4 = len > 0;
  92009. if (!right4) len = -len;
  92010. dot1 = a4x * a1x + a4y * a1y + a4z * a1z;
  92011. dot2 = a4x * a2x + a4y * a2y + a4z * a2z;
  92012. dot3 = a4x * a3x + a4y * a3y + a4z * a3z;
  92013. if (dot1 < 0) dot1 = -dot1;
  92014. if (dot2 < 0) dot2 = -dot2;
  92015. if (dot3 < 0) dot3 = -dot3;
  92016. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  92017. len2 = w2;
  92018. overlap4 = (len - len1 - len2) * 1.0;
  92019. if (overlap4 > 0) return;
  92020. // try axis 5
  92021. len = a5x * dx + a5y * dy + a5z * dz;
  92022. right5 = len > 0;
  92023. if (!right5) len = -len;
  92024. dot1 = a5x * a1x + a5y * a1y + a5z * a1z;
  92025. dot2 = a5x * a2x + a5y * a2y + a5z * a2z;
  92026. dot3 = a5x * a3x + a5y * a3y + a5z * a3z;
  92027. if (dot1 < 0) dot1 = -dot1;
  92028. if (dot2 < 0) dot2 = -dot2;
  92029. if (dot3 < 0) dot3 = -dot3;
  92030. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  92031. len2 = h2;
  92032. overlap5 = (len - len1 - len2) * 1.0;
  92033. if (overlap5 > 0) return;
  92034. // try axis 6
  92035. len = a6x * dx + a6y * dy + a6z * dz;
  92036. right6 = len > 0;
  92037. if (!right6) len = -len;
  92038. dot1 = a6x * a1x + a6y * a1y + a6z * a1z;
  92039. dot2 = a6x * a2x + a6y * a2y + a6z * a2z;
  92040. dot3 = a6x * a3x + a6y * a3y + a6z * a3z;
  92041. if (dot1 < 0) dot1 = -dot1;
  92042. if (dot2 < 0) dot2 = -dot2;
  92043. if (dot3 < 0) dot3 = -dot3;
  92044. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  92045. len2 = d2;
  92046. overlap6 = (len - len1 - len2) * 1.0;
  92047. if (overlap6 > 0) return;
  92048. // try axis 7
  92049. len = a7x * a7x + a7y * a7y + a7z * a7z;
  92050. if (len > 1e-5) {
  92051. len = 1 / OIMO.sqrt(len);
  92052. a7x *= len;
  92053. a7y *= len;
  92054. a7z *= len;
  92055. len = a7x * dx + a7y * dy + a7z * dz;
  92056. right7 = len > 0;
  92057. if (!right7) len = -len;
  92058. dot1 = a7x * a2x + a7y * a2y + a7z * a2z;
  92059. dot2 = a7x * a3x + a7y * a3y + a7z * a3z;
  92060. if (dot1 < 0) dot1 = -dot1;
  92061. if (dot2 < 0) dot2 = -dot2;
  92062. len1 = dot1 * h1 + dot2 * d1;
  92063. dot1 = a7x * a5x + a7y * a5y + a7z * a5z;
  92064. dot2 = a7x * a6x + a7y * a6y + a7z * a6z;
  92065. if (dot1 < 0) dot1 = -dot1;
  92066. if (dot2 < 0) dot2 = -dot2;
  92067. len2 = dot1 * h2 + dot2 * d2;
  92068. overlap7 = len - len1 - len2;
  92069. if (overlap7 > 0) return;
  92070. } else {
  92071. right7 = false;
  92072. overlap7 = 0;
  92073. invalid7 = true;
  92074. }
  92075. // try axis 8
  92076. len = a8x * a8x + a8y * a8y + a8z * a8z;
  92077. if (len > 1e-5) {
  92078. len = 1 / OIMO.sqrt(len);
  92079. a8x *= len;
  92080. a8y *= len;
  92081. a8z *= len;
  92082. len = a8x * dx + a8y * dy + a8z * dz;
  92083. right8 = len > 0;
  92084. if (!right8) len = -len;
  92085. dot1 = a8x * a2x + a8y * a2y + a8z * a2z;
  92086. dot2 = a8x * a3x + a8y * a3y + a8z * a3z;
  92087. if (dot1 < 0) dot1 = -dot1;
  92088. if (dot2 < 0) dot2 = -dot2;
  92089. len1 = dot1 * h1 + dot2 * d1;
  92090. dot1 = a8x * a4x + a8y * a4y + a8z * a4z;
  92091. dot2 = a8x * a6x + a8y * a6y + a8z * a6z;
  92092. if (dot1 < 0) dot1 = -dot1;
  92093. if (dot2 < 0) dot2 = -dot2;
  92094. len2 = dot1 * w2 + dot2 * d2;
  92095. overlap8 = len - len1 - len2;
  92096. if (overlap8 > 0) return;
  92097. } else {
  92098. right8 = false;
  92099. overlap8 = 0;
  92100. invalid8 = true;
  92101. }
  92102. // try axis 9
  92103. len = a9x * a9x + a9y * a9y + a9z * a9z;
  92104. if (len > 1e-5) {
  92105. len = 1 / OIMO.sqrt(len);
  92106. a9x *= len;
  92107. a9y *= len;
  92108. a9z *= len;
  92109. len = a9x * dx + a9y * dy + a9z * dz;
  92110. right9 = len > 0;
  92111. if (!right9) len = -len;
  92112. dot1 = a9x * a2x + a9y * a2y + a9z * a2z;
  92113. dot2 = a9x * a3x + a9y * a3y + a9z * a3z;
  92114. if (dot1 < 0) dot1 = -dot1;
  92115. if (dot2 < 0) dot2 = -dot2;
  92116. len1 = dot1 * h1 + dot2 * d1;
  92117. dot1 = a9x * a4x + a9y * a4y + a9z * a4z;
  92118. dot2 = a9x * a5x + a9y * a5y + a9z * a5z;
  92119. if (dot1 < 0) dot1 = -dot1;
  92120. if (dot2 < 0) dot2 = -dot2;
  92121. len2 = dot1 * w2 + dot2 * h2;
  92122. overlap9 = len - len1 - len2;
  92123. if (overlap9 > 0) return;
  92124. } else {
  92125. right9 = false;
  92126. overlap9 = 0;
  92127. invalid9 = true;
  92128. }
  92129. // try axis 10
  92130. len = aax * aax + aay * aay + aaz * aaz;
  92131. if (len > 1e-5) {
  92132. len = 1 / OIMO.sqrt(len);
  92133. aax *= len;
  92134. aay *= len;
  92135. aaz *= len;
  92136. len = aax * dx + aay * dy + aaz * dz;
  92137. righta = len > 0;
  92138. if (!righta) len = -len;
  92139. dot1 = aax * a1x + aay * a1y + aaz * a1z;
  92140. dot2 = aax * a3x + aay * a3y + aaz * a3z;
  92141. if (dot1 < 0) dot1 = -dot1;
  92142. if (dot2 < 0) dot2 = -dot2;
  92143. len1 = dot1 * w1 + dot2 * d1;
  92144. dot1 = aax * a5x + aay * a5y + aaz * a5z;
  92145. dot2 = aax * a6x + aay * a6y + aaz * a6z;
  92146. if (dot1 < 0) dot1 = -dot1;
  92147. if (dot2 < 0) dot2 = -dot2;
  92148. len2 = dot1 * h2 + dot2 * d2;
  92149. overlapa = len - len1 - len2;
  92150. if (overlapa > 0) return;
  92151. } else {
  92152. righta = false;
  92153. overlapa = 0;
  92154. invalida = true;
  92155. }
  92156. // try axis 11
  92157. len = abx * abx + aby * aby + abz * abz;
  92158. if (len > 1e-5) {
  92159. len = 1 / OIMO.sqrt(len);
  92160. abx *= len;
  92161. aby *= len;
  92162. abz *= len;
  92163. len = abx * dx + aby * dy + abz * dz;
  92164. rightb = len > 0;
  92165. if (!rightb) len = -len;
  92166. dot1 = abx * a1x + aby * a1y + abz * a1z;
  92167. dot2 = abx * a3x + aby * a3y + abz * a3z;
  92168. if (dot1 < 0) dot1 = -dot1;
  92169. if (dot2 < 0) dot2 = -dot2;
  92170. len1 = dot1 * w1 + dot2 * d1;
  92171. dot1 = abx * a4x + aby * a4y + abz * a4z;
  92172. dot2 = abx * a6x + aby * a6y + abz * a6z;
  92173. if (dot1 < 0) dot1 = -dot1;
  92174. if (dot2 < 0) dot2 = -dot2;
  92175. len2 = dot1 * w2 + dot2 * d2;
  92176. overlapb = len - len1 - len2;
  92177. if (overlapb > 0) return;
  92178. } else {
  92179. rightb = false;
  92180. overlapb = 0;
  92181. invalidb = true;
  92182. }
  92183. // try axis 12
  92184. len = acx * acx + acy * acy + acz * acz;
  92185. if (len > 1e-5) {
  92186. len = 1 / OIMO.sqrt(len);
  92187. acx *= len;
  92188. acy *= len;
  92189. acz *= len;
  92190. len = acx * dx + acy * dy + acz * dz;
  92191. rightc = len > 0;
  92192. if (!rightc) len = -len;
  92193. dot1 = acx * a1x + acy * a1y + acz * a1z;
  92194. dot2 = acx * a3x + acy * a3y + acz * a3z;
  92195. if (dot1 < 0) dot1 = -dot1;
  92196. if (dot2 < 0) dot2 = -dot2;
  92197. len1 = dot1 * w1 + dot2 * d1;
  92198. dot1 = acx * a4x + acy * a4y + acz * a4z;
  92199. dot2 = acx * a5x + acy * a5y + acz * a5z;
  92200. if (dot1 < 0) dot1 = -dot1;
  92201. if (dot2 < 0) dot2 = -dot2;
  92202. len2 = dot1 * w2 + dot2 * h2;
  92203. overlapc = len - len1 - len2;
  92204. if (overlapc > 0) return;
  92205. } else {
  92206. rightc = false;
  92207. overlapc = 0;
  92208. invalidc = true;
  92209. }
  92210. // try axis 13
  92211. len = adx * adx + ady * ady + adz * adz;
  92212. if (len > 1e-5) {
  92213. len = 1 / OIMO.sqrt(len);
  92214. adx *= len;
  92215. ady *= len;
  92216. adz *= len;
  92217. len = adx * dx + ady * dy + adz * dz;
  92218. rightd = len > 0;
  92219. if (!rightd) len = -len;
  92220. dot1 = adx * a1x + ady * a1y + adz * a1z;
  92221. dot2 = adx * a2x + ady * a2y + adz * a2z;
  92222. if (dot1 < 0) dot1 = -dot1;
  92223. if (dot2 < 0) dot2 = -dot2;
  92224. len1 = dot1 * w1 + dot2 * h1;
  92225. dot1 = adx * a5x + ady * a5y + adz * a5z;
  92226. dot2 = adx * a6x + ady * a6y + adz * a6z;
  92227. if (dot1 < 0) dot1 = -dot1;
  92228. if (dot2 < 0) dot2 = -dot2;
  92229. len2 = dot1 * h2 + dot2 * d2;
  92230. overlapd = len - len1 - len2;
  92231. if (overlapd > 0) return;
  92232. } else {
  92233. rightd = false;
  92234. overlapd = 0;
  92235. invalidd = true;
  92236. }
  92237. // try axis 14
  92238. len = aex * aex + aey * aey + aez * aez;
  92239. if (len > 1e-5) {
  92240. len = 1 / OIMO.sqrt(len);
  92241. aex *= len;
  92242. aey *= len;
  92243. aez *= len;
  92244. len = aex * dx + aey * dy + aez * dz;
  92245. righte = len > 0;
  92246. if (!righte) len = -len;
  92247. dot1 = aex * a1x + aey * a1y + aez * a1z;
  92248. dot2 = aex * a2x + aey * a2y + aez * a2z;
  92249. if (dot1 < 0) dot1 = -dot1;
  92250. if (dot2 < 0) dot2 = -dot2;
  92251. len1 = dot1 * w1 + dot2 * h1;
  92252. dot1 = aex * a4x + aey * a4y + aez * a4z;
  92253. dot2 = aex * a6x + aey * a6y + aez * a6z;
  92254. if (dot1 < 0) dot1 = -dot1;
  92255. if (dot2 < 0) dot2 = -dot2;
  92256. len2 = dot1 * w2 + dot2 * d2;
  92257. overlape = len - len1 - len2;
  92258. if (overlape > 0) return;
  92259. } else {
  92260. righte = false;
  92261. overlape = 0;
  92262. invalide = true;
  92263. }
  92264. // try axis 15
  92265. len = afx * afx + afy * afy + afz * afz;
  92266. if (len > 1e-5) {
  92267. len = 1 / OIMO.sqrt(len);
  92268. afx *= len;
  92269. afy *= len;
  92270. afz *= len;
  92271. len = afx * dx + afy * dy + afz * dz;
  92272. rightf = len > 0;
  92273. if (!rightf) len = -len;
  92274. dot1 = afx * a1x + afy * a1y + afz * a1z;
  92275. dot2 = afx * a2x + afy * a2y + afz * a2z;
  92276. if (dot1 < 0) dot1 = -dot1;
  92277. if (dot2 < 0) dot2 = -dot2;
  92278. len1 = dot1 * w1 + dot2 * h1;
  92279. dot1 = afx * a4x + afy * a4y + afz * a4z;
  92280. dot2 = afx * a5x + afy * a5y + afz * a5z;
  92281. if (dot1 < 0) dot1 = -dot1;
  92282. if (dot2 < 0) dot2 = -dot2;
  92283. len2 = dot1 * w2 + dot2 * h2;
  92284. overlapf = len - len1 - len2;
  92285. if (overlapf > 0) return;
  92286. } else {
  92287. rightf = false;
  92288. overlapf = 0;
  92289. invalidf = true;
  92290. }
  92291. // boxes are overlapping
  92292. var depth = overlap1;
  92293. var depth2 = overlap1;
  92294. var minIndex = 0;
  92295. var right = right1;
  92296. if (overlap2 > depth2) {
  92297. depth = overlap2;
  92298. depth2 = overlap2;
  92299. minIndex = 1;
  92300. right = right2;
  92301. }
  92302. if (overlap3 > depth2) {
  92303. depth = overlap3;
  92304. depth2 = overlap3;
  92305. minIndex = 2;
  92306. right = right3;
  92307. }
  92308. if (overlap4 > depth2) {
  92309. depth = overlap4;
  92310. depth2 = overlap4;
  92311. minIndex = 3;
  92312. right = right4;
  92313. }
  92314. if (overlap5 > depth2) {
  92315. depth = overlap5;
  92316. depth2 = overlap5;
  92317. minIndex = 4;
  92318. right = right5;
  92319. }
  92320. if (overlap6 > depth2) {
  92321. depth = overlap6;
  92322. depth2 = overlap6;
  92323. minIndex = 5;
  92324. right = right6;
  92325. }
  92326. if (overlap7 - 0.01 > depth2 && !invalid7) {
  92327. depth = overlap7;
  92328. depth2 = overlap7 - 0.01;
  92329. minIndex = 6;
  92330. right = right7;
  92331. }
  92332. if (overlap8 - 0.01 > depth2 && !invalid8) {
  92333. depth = overlap8;
  92334. depth2 = overlap8 - 0.01;
  92335. minIndex = 7;
  92336. right = right8;
  92337. }
  92338. if (overlap9 - 0.01 > depth2 && !invalid9) {
  92339. depth = overlap9;
  92340. depth2 = overlap9 - 0.01;
  92341. minIndex = 8;
  92342. right = right9;
  92343. }
  92344. if (overlapa - 0.01 > depth2 && !invalida) {
  92345. depth = overlapa;
  92346. depth2 = overlapa - 0.01;
  92347. minIndex = 9;
  92348. right = righta;
  92349. }
  92350. if (overlapb - 0.01 > depth2 && !invalidb) {
  92351. depth = overlapb;
  92352. depth2 = overlapb - 0.01;
  92353. minIndex = 10;
  92354. right = rightb;
  92355. }
  92356. if (overlapc - 0.01 > depth2 && !invalidc) {
  92357. depth = overlapc;
  92358. depth2 = overlapc - 0.01;
  92359. minIndex = 11;
  92360. right = rightc;
  92361. }
  92362. if (overlapd - 0.01 > depth2 && !invalidd) {
  92363. depth = overlapd;
  92364. depth2 = overlapd - 0.01;
  92365. minIndex = 12;
  92366. right = rightd;
  92367. }
  92368. if (overlape - 0.01 > depth2 && !invalide) {
  92369. depth = overlape;
  92370. depth2 = overlape - 0.01;
  92371. minIndex = 13;
  92372. right = righte;
  92373. }
  92374. if (overlapf - 0.01 > depth2 && !invalidf) {
  92375. depth = overlapf;
  92376. minIndex = 14;
  92377. right = rightf;
  92378. }
  92379. // normal
  92380. var nx = 0;
  92381. var ny = 0;
  92382. var nz = 0;
  92383. // edge line or face side normal
  92384. var n1x = 0;
  92385. var n1y = 0;
  92386. var n1z = 0;
  92387. var n2x = 0;
  92388. var n2y = 0;
  92389. var n2z = 0;
  92390. // center of current face
  92391. var cx = 0;
  92392. var cy = 0;
  92393. var cz = 0;
  92394. // face side
  92395. var s1x = 0;
  92396. var s1y = 0;
  92397. var s1z = 0;
  92398. var s2x = 0;
  92399. var s2y = 0;
  92400. var s2z = 0;
  92401. // swap b1 b2
  92402. var swap = false;
  92403. //_______________________________________
  92404. if (minIndex == 0) {// b1.x * b2
  92405. if (right) {
  92406. cx = p1x + d1x; cy = p1y + d1y; cz = p1z + d1z;
  92407. nx = a1x; ny = a1y; nz = a1z;
  92408. } else {
  92409. cx = p1x - d1x; cy = p1y - d1y; cz = p1z - d1z;
  92410. nx = -a1x; ny = -a1y; nz = -a1z;
  92411. }
  92412. s1x = d2x; s1y = d2y; s1z = d2z;
  92413. n1x = -a2x; n1y = -a2y; n1z = -a2z;
  92414. s2x = d3x; s2y = d3y; s2z = d3z;
  92415. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  92416. }
  92417. else if (minIndex == 1) {// b1.y * b2
  92418. if (right) {
  92419. cx = p1x + d2x; cy = p1y + d2y; cz = p1z + d2z;
  92420. nx = a2x; ny = a2y; nz = a2z;
  92421. } else {
  92422. cx = p1x - d2x; cy = p1y - d2y; cz = p1z - d2z;
  92423. nx = -a2x; ny = -a2y; nz = -a2z;
  92424. }
  92425. s1x = d1x; s1y = d1y; s1z = d1z;
  92426. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  92427. s2x = d3x; s2y = d3y; s2z = d3z;
  92428. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  92429. }
  92430. else if (minIndex == 2) {// b1.z * b2
  92431. if (right) {
  92432. cx = p1x + d3x; cy = p1y + d3y; cz = p1z + d3z;
  92433. nx = a3x; ny = a3y; nz = a3z;
  92434. } else {
  92435. cx = p1x - d3x; cy = p1y - d3y; cz = p1z - d3z;
  92436. nx = -a3x; ny = -a3y; nz = -a3z;
  92437. }
  92438. s1x = d1x; s1y = d1y; s1z = d1z;
  92439. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  92440. s2x = d2x; s2y = d2y; s2z = d2z;
  92441. n2x = -a2x; n2y = -a2y; n2z = -a2z;
  92442. }
  92443. else if (minIndex == 3) {// b2.x * b1
  92444. swap = true;
  92445. if (!right) {
  92446. cx = p2x + d4x; cy = p2y + d4y; cz = p2z + d4z;
  92447. nx = a4x; ny = a4y; nz = a4z;
  92448. } else {
  92449. cx = p2x - d4x; cy = p2y - d4y; cz = p2z - d4z;
  92450. nx = -a4x; ny = -a4y; nz = -a4z;
  92451. }
  92452. s1x = d5x; s1y = d5y; s1z = d5z;
  92453. n1x = -a5x; n1y = -a5y; n1z = -a5z;
  92454. s2x = d6x; s2y = d6y; s2z = d6z;
  92455. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  92456. }
  92457. else if (minIndex == 4) {// b2.y * b1
  92458. swap = true;
  92459. if (!right) {
  92460. cx = p2x + d5x; cy = p2y + d5y; cz = p2z + d5z;
  92461. nx = a5x; ny = a5y; nz = a5z;
  92462. } else {
  92463. cx = p2x - d5x; cy = p2y - d5y; cz = p2z - d5z;
  92464. nx = -a5x; ny = -a5y; nz = -a5z;
  92465. }
  92466. s1x = d4x; s1y = d4y; s1z = d4z;
  92467. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  92468. s2x = d6x; s2y = d6y; s2z = d6z;
  92469. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  92470. }
  92471. else if (minIndex == 5) {// b2.z * b1
  92472. swap = true;
  92473. if (!right) {
  92474. cx = p2x + d6x; cy = p2y + d6y; cz = p2z + d6z;
  92475. nx = a6x; ny = a6y; nz = a6z;
  92476. } else {
  92477. cx = p2x - d6x; cy = p2y - d6y; cz = p2z - d6z;
  92478. nx = -a6x; ny = -a6y; nz = -a6z;
  92479. }
  92480. s1x = d4x; s1y = d4y; s1z = d4z;
  92481. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  92482. s2x = d5x; s2y = d5y; s2z = d5z;
  92483. n2x = -a5x; n2y = -a5y; n2z = -a5z;
  92484. }
  92485. else if (minIndex == 6) {// b1.x * b2.x
  92486. nx = a7x; ny = a7y; nz = a7z;
  92487. n1x = a1x; n1y = a1y; n1z = a1z;
  92488. n2x = a4x; n2y = a4y; n2z = a4z;
  92489. }
  92490. else if (minIndex == 7) {// b1.x * b2.y
  92491. nx = a8x; ny = a8y; nz = a8z;
  92492. n1x = a1x; n1y = a1y; n1z = a1z;
  92493. n2x = a5x; n2y = a5y; n2z = a5z;
  92494. }
  92495. else if (minIndex == 8) {// b1.x * b2.z
  92496. nx = a9x; ny = a9y; nz = a9z;
  92497. n1x = a1x; n1y = a1y; n1z = a1z;
  92498. n2x = a6x; n2y = a6y; n2z = a6z;
  92499. }
  92500. else if (minIndex == 9) {// b1.y * b2.x
  92501. nx = aax; ny = aay; nz = aaz;
  92502. n1x = a2x; n1y = a2y; n1z = a2z;
  92503. n2x = a4x; n2y = a4y; n2z = a4z
  92504. }
  92505. else if (minIndex == 10) {// b1.y * b2.y
  92506. nx = abx; ny = aby; nz = abz;
  92507. n1x = a2x; n1y = a2y; n1z = a2z;
  92508. n2x = a5x; n2y = a5y; n2z = a5z;
  92509. }
  92510. else if (minIndex == 11) {// b1.y * b2.z
  92511. nx = acx; ny = acy; nz = acz;
  92512. n1x = a2x; n1y = a2y; n1z = a2z;
  92513. n2x = a6x; n2y = a6y; n2z = a6z;
  92514. }
  92515. else if (minIndex == 12) {// b1.z * b2.x
  92516. nx = adx; ny = ady; nz = adz;
  92517. n1x = a3x; n1y = a3y; n1z = a3z;
  92518. n2x = a4x; n2y = a4y; n2z = a4z;
  92519. }
  92520. else if (minIndex == 13) {// b1.z * b2.y
  92521. nx = aex; ny = aey; nz = aez;
  92522. n1x = a3x; n1y = a3y; n1z = a3z;
  92523. n2x = a5x; n2y = a5y; n2z = a5z;
  92524. }
  92525. else if (minIndex == 14) {// b1.z * b2.z
  92526. nx = afx; ny = afy; nz = afz;
  92527. n1x = a3x; n1y = a3y; n1z = a3z;
  92528. n2x = a6x; n2y = a6y; n2z = a6z;
  92529. }
  92530. //__________________________________________
  92531. var v;
  92532. if (minIndex > 5) {
  92533. if (!right) {
  92534. nx = -nx; ny = -ny; nz = -nz;
  92535. }
  92536. var distance;
  92537. var maxDistance;
  92538. var vx;
  92539. var vy;
  92540. var vz;
  92541. var v1x;
  92542. var v1y;
  92543. var v1z;
  92544. var v2x;
  92545. var v2y;
  92546. var v2z;
  92547. //vertex1;
  92548. v1x = V1[0]; v1y = V1[1]; v1z = V1[2];
  92549. maxDistance = nx * v1x + ny * v1y + nz * v1z;
  92550. //vertex2;
  92551. vx = V1[3]; vy = V1[4]; vz = V1[5];
  92552. distance = nx * vx + ny * vy + nz * vz;
  92553. if (distance > maxDistance) {
  92554. maxDistance = distance;
  92555. v1x = vx; v1y = vy; v1z = vz;
  92556. }
  92557. //vertex3;
  92558. vx = V1[6]; vy = V1[7]; vz = V1[8];
  92559. distance = nx * vx + ny * vy + nz * vz;
  92560. if (distance > maxDistance) {
  92561. maxDistance = distance;
  92562. v1x = vx; v1y = vy; v1z = vz;
  92563. }
  92564. //vertex4;
  92565. vx = V1[9]; vy = V1[10]; vz = V1[11];
  92566. distance = nx * vx + ny * vy + nz * vz;
  92567. if (distance > maxDistance) {
  92568. maxDistance = distance;
  92569. v1x = vx; v1y = vy; v1z = vz;
  92570. }
  92571. //vertex5;
  92572. vx = V1[12]; vy = V1[13]; vz = V1[14];
  92573. distance = nx * vx + ny * vy + nz * vz;
  92574. if (distance > maxDistance) {
  92575. maxDistance = distance;
  92576. v1x = vx; v1y = vy; v1z = vz;
  92577. }
  92578. //vertex6;
  92579. vx = V1[15]; vy = V1[16]; vz = V1[17];
  92580. distance = nx * vx + ny * vy + nz * vz;
  92581. if (distance > maxDistance) {
  92582. maxDistance = distance;
  92583. v1x = vx; v1y = vy; v1z = vz;
  92584. }
  92585. //vertex7;
  92586. vx = V1[18]; vy = V1[19]; vz = V1[20];
  92587. distance = nx * vx + ny * vy + nz * vz;
  92588. if (distance > maxDistance) {
  92589. maxDistance = distance;
  92590. v1x = vx; v1y = vy; v1z = vz;
  92591. }
  92592. //vertex8;
  92593. vx = V1[21]; vy = V1[22]; vz = V1[23];
  92594. distance = nx * vx + ny * vy + nz * vz;
  92595. if (distance > maxDistance) {
  92596. maxDistance = distance;
  92597. v1x = vx; v1y = vy; v1z = vz;
  92598. }
  92599. //vertex1;
  92600. v2x = V2[0]; v2y = V2[1]; v2z = V2[2];
  92601. maxDistance = nx * v2x + ny * v2y + nz * v2z;
  92602. //vertex2;
  92603. vx = V2[3]; vy = V2[4]; vz = V2[5];
  92604. distance = nx * vx + ny * vy + nz * vz;
  92605. if (distance < maxDistance) {
  92606. maxDistance = distance;
  92607. v2x = vx; v2y = vy; v2z = vz;
  92608. }
  92609. //vertex3;
  92610. vx = V2[6]; vy = V2[7]; vz = V2[8];
  92611. distance = nx * vx + ny * vy + nz * vz;
  92612. if (distance < maxDistance) {
  92613. maxDistance = distance;
  92614. v2x = vx; v2y = vy; v2z = vz;
  92615. }
  92616. //vertex4;
  92617. vx = V2[9]; vy = V2[10]; vz = V2[11];
  92618. distance = nx * vx + ny * vy + nz * vz;
  92619. if (distance < maxDistance) {
  92620. maxDistance = distance;
  92621. v2x = vx; v2y = vy; v2z = vz;
  92622. }
  92623. //vertex5;
  92624. vx = V2[12]; vy = V2[13]; vz = V2[14];
  92625. distance = nx * vx + ny * vy + nz * vz;
  92626. if (distance < maxDistance) {
  92627. maxDistance = distance;
  92628. v2x = vx; v2y = vy; v2z = vz;
  92629. }
  92630. //vertex6;
  92631. vx = V2[15]; vy = V2[16]; vz = V2[17];
  92632. distance = nx * vx + ny * vy + nz * vz;
  92633. if (distance < maxDistance) {
  92634. maxDistance = distance;
  92635. v2x = vx; v2y = vy; v2z = vz;
  92636. }
  92637. //vertex7;
  92638. vx = V2[18]; vy = V2[19]; vz = V2[20];
  92639. distance = nx * vx + ny * vy + nz * vz;
  92640. if (distance < maxDistance) {
  92641. maxDistance = distance;
  92642. v2x = vx; v2y = vy; v2z = vz;
  92643. }
  92644. //vertex8;
  92645. vx = V2[21]; vy = V2[22]; vz = V2[23];
  92646. distance = nx * vx + ny * vy + nz * vz;
  92647. if (distance < maxDistance) {
  92648. maxDistance = distance;
  92649. v2x = vx; v2y = vy; v2z = vz;
  92650. }
  92651. vx = v2x - v1x; vy = v2y - v1y; vz = v2z - v1z;
  92652. dot1 = n1x * n2x + n1y * n2y + n1z * n2z;
  92653. var t = (vx * (n1x - n2x * dot1) + vy * (n1y - n2y * dot1) + vz * (n1z - n2z * dot1)) / (1 - dot1 * dot1);
  92654. 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);
  92655. return;
  92656. }
  92657. // now detect face-face collision...
  92658. // target quad
  92659. var q1x;
  92660. var q1y;
  92661. var q1z;
  92662. var q2x;
  92663. var q2y;
  92664. var q2z;
  92665. var q3x;
  92666. var q3y;
  92667. var q3z;
  92668. var q4x;
  92669. var q4y;
  92670. var q4z;
  92671. // search support face and vertex
  92672. var minDot = 1;
  92673. var dot = 0;
  92674. var minDotIndex = 0;
  92675. if (swap) {
  92676. dot = a1x * nx + a1y * ny + a1z * nz;
  92677. if (dot < minDot) {
  92678. minDot = dot;
  92679. minDotIndex = 0;
  92680. }
  92681. if (-dot < minDot) {
  92682. minDot = -dot;
  92683. minDotIndex = 1;
  92684. }
  92685. dot = a2x * nx + a2y * ny + a2z * nz;
  92686. if (dot < minDot) {
  92687. minDot = dot;
  92688. minDotIndex = 2;
  92689. }
  92690. if (-dot < minDot) {
  92691. minDot = -dot;
  92692. minDotIndex = 3;
  92693. }
  92694. dot = a3x * nx + a3y * ny + a3z * nz;
  92695. if (dot < minDot) {
  92696. minDot = dot;
  92697. minDotIndex = 4;
  92698. }
  92699. if (-dot < minDot) {
  92700. minDot = -dot;
  92701. minDotIndex = 5;
  92702. }
  92703. if (minDotIndex == 0) {// x+ face
  92704. q1x = V1[0]; q1y = V1[1]; q1z = V1[2];//vertex1
  92705. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex3
  92706. q3x = V1[9]; q3y = V1[10]; q3z = V1[11];//vertex4
  92707. q4x = V1[3]; q4y = V1[4]; q4z = V1[5];//vertex2
  92708. }
  92709. else if (minDotIndex == 1) {// x- face
  92710. q1x = V1[15]; q1y = V1[16]; q1z = V1[17];//vertex6
  92711. q2x = V1[21]; q2y = V1[22]; q2z = V1[23];//vertex8
  92712. q3x = V1[18]; q3y = V1[19]; q3z = V1[20];//vertex7
  92713. q4x = V1[12]; q4y = V1[13]; q4z = V1[14];//vertex5
  92714. }
  92715. else if (minDotIndex == 2) {// y+ face
  92716. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  92717. q2x = V1[0]; q2y = V1[1]; q2z = V1[2];//vertex1
  92718. q3x = V1[3]; q3y = V1[4]; q3z = V1[5];//vertex2
  92719. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  92720. }
  92721. else if (minDotIndex == 3) {// y- face
  92722. q1x = V1[21]; q1y = V1[22]; q1z = V1[23];//vertex8
  92723. q2x = V1[9]; q2y = V1[10]; q2z = V1[11];//vertex4
  92724. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  92725. q4x = V1[18]; q4y = V1[19]; q4z = V1[20];//vertex7
  92726. }
  92727. else if (minDotIndex == 4) {// z+ face
  92728. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  92729. q2x = V1[18]; q2y = V1[19]; q2z = V1[20];//vertex7
  92730. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  92731. q4x = V1[0]; q4y = V1[1]; q4z = V1[2];//vertex1
  92732. }
  92733. else if (minDotIndex == 5) {// z- face
  92734. q1x = V1[3]; q1y = V1[4]; q1z = V1[5];//vertex2
  92735. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex4
  92736. q3x = V1[21]; q3y = V1[22]; q3z = V1[23];//vertex8
  92737. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  92738. }
  92739. } else {
  92740. dot = a4x * nx + a4y * ny + a4z * nz;
  92741. if (dot < minDot) {
  92742. minDot = dot;
  92743. minDotIndex = 0;
  92744. }
  92745. if (-dot < minDot) {
  92746. minDot = -dot;
  92747. minDotIndex = 1;
  92748. }
  92749. dot = a5x * nx + a5y * ny + a5z * nz;
  92750. if (dot < minDot) {
  92751. minDot = dot;
  92752. minDotIndex = 2;
  92753. }
  92754. if (-dot < minDot) {
  92755. minDot = -dot;
  92756. minDotIndex = 3;
  92757. }
  92758. dot = a6x * nx + a6y * ny + a6z * nz;
  92759. if (dot < minDot) {
  92760. minDot = dot;
  92761. minDotIndex = 4;
  92762. }
  92763. if (-dot < minDot) {
  92764. minDot = -dot;
  92765. minDotIndex = 5;
  92766. }
  92767. //______________________________________________________
  92768. if (minDotIndex == 0) {// x+ face
  92769. q1x = V2[0]; q1y = V2[1]; q1z = V2[2];//vertex1
  92770. q2x = V2[6]; q2y = V2[7]; q2z = V2[8];//vertex3
  92771. q3x = V2[9]; q3y = V2[10]; q3z = V2[11];//vertex4
  92772. q4x = V2[3]; q4y = V2[4]; q4z = V2[5];//vertex2
  92773. }
  92774. else if (minDotIndex == 1) {// x- face
  92775. q1x = V2[15]; q1y = V2[16]; q1z = V2[17];//vertex6
  92776. q2x = V2[21]; q2y = V2[22]; q2z = V2[23]; //vertex8
  92777. q3x = V2[18]; q3y = V2[19]; q3z = V2[20];//vertex7
  92778. q4x = V2[12]; q4y = V2[13]; q4z = V2[14];//vertex5
  92779. }
  92780. else if (minDotIndex == 2) {// y+ face
  92781. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  92782. q2x = V2[0]; q2y = V2[1]; q2z = V2[2];//vertex1
  92783. q3x = V2[3]; q3y = V2[4]; q3z = V2[5];//vertex2
  92784. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  92785. }
  92786. else if (minDotIndex == 3) {// y- face
  92787. q1x = V2[21]; q1y = V2[22]; q1z = V2[23];//vertex8
  92788. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  92789. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  92790. q4x = V2[18]; q4y = V2[19]; q4z = V2[20];//vertex7
  92791. }
  92792. else if (minDotIndex == 4) {// z+ face
  92793. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  92794. q2x = V2[18]; q2y = V2[19]; q2z = V2[20];//vertex7
  92795. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  92796. q4x = V2[0]; q4y = V2[1]; q4z = V2[2];//vertex1
  92797. }
  92798. else if (minDotIndex == 5) {// z- face
  92799. q1x = V2[3]; q1y = V2[4]; q1z = V2[5];//vertex2
  92800. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  92801. q3x = V2[21]; q3y = V2[22]; q3z = V2[23];//vertex8
  92802. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  92803. }
  92804. }
  92805. // clip vertices
  92806. var numClipVertices;
  92807. var numAddedClipVertices;
  92808. var index;
  92809. var x1;
  92810. var y1;
  92811. var z1;
  92812. var x2;
  92813. var y2;
  92814. var z2;
  92815. this.clipVertices1[0] = q1x;
  92816. this.clipVertices1[1] = q1y;
  92817. this.clipVertices1[2] = q1z;
  92818. this.clipVertices1[3] = q2x;
  92819. this.clipVertices1[4] = q2y;
  92820. this.clipVertices1[5] = q2z;
  92821. this.clipVertices1[6] = q3x;
  92822. this.clipVertices1[7] = q3y;
  92823. this.clipVertices1[8] = q3z;
  92824. this.clipVertices1[9] = q4x;
  92825. this.clipVertices1[10] = q4y;
  92826. this.clipVertices1[11] = q4z;
  92827. numAddedClipVertices = 0;
  92828. x1 = this.clipVertices1[9];
  92829. y1 = this.clipVertices1[10];
  92830. z1 = this.clipVertices1[11];
  92831. dot1 = (x1 - cx - s1x) * n1x + (y1 - cy - s1y) * n1y + (z1 - cz - s1z) * n1z;
  92832. //var i = 4;
  92833. //while(i--){
  92834. for (var i = 0; i < 4; i++) {
  92835. index = i * 3;
  92836. x2 = this.clipVertices1[index];
  92837. y2 = this.clipVertices1[index + 1];
  92838. z2 = this.clipVertices1[index + 2];
  92839. dot2 = (x2 - cx - s1x) * n1x + (y2 - cy - s1y) * n1y + (z2 - cz - s1z) * n1z;
  92840. if (dot1 > 0) {
  92841. if (dot2 > 0) {
  92842. index = numAddedClipVertices * 3;
  92843. numAddedClipVertices++;
  92844. this.clipVertices2[index] = x2;
  92845. this.clipVertices2[index + 1] = y2;
  92846. this.clipVertices2[index + 2] = z2;
  92847. } else {
  92848. index = numAddedClipVertices * 3;
  92849. numAddedClipVertices++;
  92850. t = dot1 / (dot1 - dot2);
  92851. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  92852. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  92853. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  92854. }
  92855. } else {
  92856. if (dot2 > 0) {
  92857. index = numAddedClipVertices * 3;
  92858. numAddedClipVertices++;
  92859. t = dot1 / (dot1 - dot2);
  92860. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  92861. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  92862. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  92863. index = numAddedClipVertices * 3;
  92864. numAddedClipVertices++;
  92865. this.clipVertices2[index] = x2;
  92866. this.clipVertices2[index + 1] = y2;
  92867. this.clipVertices2[index + 2] = z2;
  92868. }
  92869. }
  92870. x1 = x2;
  92871. y1 = y2;
  92872. z1 = z2;
  92873. dot1 = dot2;
  92874. }
  92875. numClipVertices = numAddedClipVertices;
  92876. if (numClipVertices == 0) return;
  92877. numAddedClipVertices = 0;
  92878. index = (numClipVertices - 1) * 3;
  92879. x1 = this.clipVertices2[index];
  92880. y1 = this.clipVertices2[index + 1];
  92881. z1 = this.clipVertices2[index + 2];
  92882. dot1 = (x1 - cx - s2x) * n2x + (y1 - cy - s2y) * n2y + (z1 - cz - s2z) * n2z;
  92883. //i = numClipVertices;
  92884. //while(i--){
  92885. for (i = 0; i < numClipVertices; i++) {
  92886. index = i * 3;
  92887. x2 = this.clipVertices2[index];
  92888. y2 = this.clipVertices2[index + 1];
  92889. z2 = this.clipVertices2[index + 2];
  92890. dot2 = (x2 - cx - s2x) * n2x + (y2 - cy - s2y) * n2y + (z2 - cz - s2z) * n2z;
  92891. if (dot1 > 0) {
  92892. if (dot2 > 0) {
  92893. index = numAddedClipVertices * 3;
  92894. numAddedClipVertices++;
  92895. this.clipVertices1[index] = x2;
  92896. this.clipVertices1[index + 1] = y2;
  92897. this.clipVertices1[index + 2] = z2;
  92898. } else {
  92899. index = numAddedClipVertices * 3;
  92900. numAddedClipVertices++;
  92901. t = dot1 / (dot1 - dot2);
  92902. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  92903. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  92904. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  92905. }
  92906. } else {
  92907. if (dot2 > 0) {
  92908. index = numAddedClipVertices * 3;
  92909. numAddedClipVertices++;
  92910. t = dot1 / (dot1 - dot2);
  92911. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  92912. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  92913. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  92914. index = numAddedClipVertices * 3;
  92915. numAddedClipVertices++;
  92916. this.clipVertices1[index] = x2;
  92917. this.clipVertices1[index + 1] = y2;
  92918. this.clipVertices1[index + 2] = z2;
  92919. }
  92920. }
  92921. x1 = x2;
  92922. y1 = y2;
  92923. z1 = z2;
  92924. dot1 = dot2;
  92925. }
  92926. numClipVertices = numAddedClipVertices;
  92927. if (numClipVertices == 0) return;
  92928. numAddedClipVertices = 0;
  92929. index = (numClipVertices - 1) * 3;
  92930. x1 = this.clipVertices1[index];
  92931. y1 = this.clipVertices1[index + 1];
  92932. z1 = this.clipVertices1[index + 2];
  92933. dot1 = (x1 - cx + s1x) * -n1x + (y1 - cy + s1y) * -n1y + (z1 - cz + s1z) * -n1z;
  92934. //i = numClipVertices;
  92935. //while(i--){
  92936. for (i = 0; i < numClipVertices; i++) {
  92937. index = i * 3;
  92938. x2 = this.clipVertices1[index];
  92939. y2 = this.clipVertices1[index + 1];
  92940. z2 = this.clipVertices1[index + 2];
  92941. dot2 = (x2 - cx + s1x) * -n1x + (y2 - cy + s1y) * -n1y + (z2 - cz + s1z) * -n1z;
  92942. if (dot1 > 0) {
  92943. if (dot2 > 0) {
  92944. index = numAddedClipVertices * 3;
  92945. numAddedClipVertices++;
  92946. this.clipVertices2[index] = x2;
  92947. this.clipVertices2[index + 1] = y2;
  92948. this.clipVertices2[index + 2] = z2;
  92949. } else {
  92950. index = numAddedClipVertices * 3;
  92951. numAddedClipVertices++;
  92952. t = dot1 / (dot1 - dot2);
  92953. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  92954. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  92955. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  92956. }
  92957. } else {
  92958. if (dot2 > 0) {
  92959. index = numAddedClipVertices * 3;
  92960. numAddedClipVertices++;
  92961. t = dot1 / (dot1 - dot2);
  92962. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  92963. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  92964. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  92965. index = numAddedClipVertices * 3;
  92966. numAddedClipVertices++;
  92967. this.clipVertices2[index] = x2;
  92968. this.clipVertices2[index + 1] = y2;
  92969. this.clipVertices2[index + 2] = z2;
  92970. }
  92971. }
  92972. x1 = x2;
  92973. y1 = y2;
  92974. z1 = z2;
  92975. dot1 = dot2;
  92976. }
  92977. numClipVertices = numAddedClipVertices;
  92978. if (numClipVertices == 0) return;
  92979. numAddedClipVertices = 0;
  92980. index = (numClipVertices - 1) * 3;
  92981. x1 = this.clipVertices2[index];
  92982. y1 = this.clipVertices2[index + 1];
  92983. z1 = this.clipVertices2[index + 2];
  92984. dot1 = (x1 - cx + s2x) * -n2x + (y1 - cy + s2y) * -n2y + (z1 - cz + s2z) * -n2z;
  92985. //i = numClipVertices;
  92986. //while(i--){
  92987. for (i = 0; i < numClipVertices; i++) {
  92988. index = i * 3;
  92989. x2 = this.clipVertices2[index];
  92990. y2 = this.clipVertices2[index + 1];
  92991. z2 = this.clipVertices2[index + 2];
  92992. dot2 = (x2 - cx + s2x) * -n2x + (y2 - cy + s2y) * -n2y + (z2 - cz + s2z) * -n2z;
  92993. if (dot1 > 0) {
  92994. if (dot2 > 0) {
  92995. index = numAddedClipVertices * 3;
  92996. numAddedClipVertices++;
  92997. this.clipVertices1[index] = x2;
  92998. this.clipVertices1[index + 1] = y2;
  92999. this.clipVertices1[index + 2] = z2;
  93000. } else {
  93001. index = numAddedClipVertices * 3;
  93002. numAddedClipVertices++;
  93003. t = dot1 / (dot1 - dot2);
  93004. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  93005. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  93006. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  93007. }
  93008. } else {
  93009. if (dot2 > 0) {
  93010. index = numAddedClipVertices * 3;
  93011. numAddedClipVertices++;
  93012. t = dot1 / (dot1 - dot2);
  93013. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  93014. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  93015. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  93016. index = numAddedClipVertices * 3;
  93017. numAddedClipVertices++;
  93018. this.clipVertices1[index] = x2;
  93019. this.clipVertices1[index + 1] = y2;
  93020. this.clipVertices1[index + 2] = z2;
  93021. }
  93022. }
  93023. x1 = x2;
  93024. y1 = y2;
  93025. z1 = z2;
  93026. dot1 = dot2;
  93027. }
  93028. numClipVertices = numAddedClipVertices;
  93029. if (swap) {
  93030. var tb = b1;
  93031. b1 = b2;
  93032. b2 = tb;
  93033. }
  93034. if (numClipVertices == 0) return;
  93035. var flipped = b1 != shape1;
  93036. if (numClipVertices > 4) {
  93037. x1 = (q1x + q2x + q3x + q4x) * 0.25;
  93038. y1 = (q1y + q2y + q3y + q4y) * 0.25;
  93039. z1 = (q1z + q2z + q3z + q4z) * 0.25;
  93040. n1x = q1x - x1;
  93041. n1y = q1y - y1;
  93042. n1z = q1z - z1;
  93043. n2x = q2x - x1;
  93044. n2y = q2y - y1;
  93045. n2z = q2z - z1;
  93046. var index1 = 0;
  93047. var index2 = 0;
  93048. var index3 = 0;
  93049. var index4 = 0;
  93050. var maxDot = -this.INF;
  93051. minDot = this.INF;
  93052. //i = numClipVertices;
  93053. //while(i--){
  93054. for (i = 0; i < numClipVertices; i++) {
  93055. this.used[i] = false;
  93056. index = i * 3;
  93057. x1 = this.clipVertices1[index];
  93058. y1 = this.clipVertices1[index + 1];
  93059. z1 = this.clipVertices1[index + 2];
  93060. dot = x1 * n1x + y1 * n1y + z1 * n1z;
  93061. if (dot < minDot) {
  93062. minDot = dot;
  93063. index1 = i;
  93064. }
  93065. if (dot > maxDot) {
  93066. maxDot = dot;
  93067. index3 = i;
  93068. }
  93069. }
  93070. this.used[index1] = true;
  93071. this.used[index3] = true;
  93072. maxDot = -this.INF;
  93073. minDot = this.INF;
  93074. //i = numClipVertices;
  93075. //while(i--){
  93076. for (i = 0; i < numClipVertices; i++) {
  93077. if (this.used[i]) continue;
  93078. index = i * 3;
  93079. x1 = this.clipVertices1[index];
  93080. y1 = this.clipVertices1[index + 1];
  93081. z1 = this.clipVertices1[index + 2];
  93082. dot = x1 * n2x + y1 * n2y + z1 * n2z;
  93083. if (dot < minDot) {
  93084. minDot = dot;
  93085. index2 = i;
  93086. }
  93087. if (dot > maxDot) {
  93088. maxDot = dot;
  93089. index4 = i;
  93090. }
  93091. }
  93092. index = index1 * 3;
  93093. x1 = this.clipVertices1[index];
  93094. y1 = this.clipVertices1[index + 1];
  93095. z1 = this.clipVertices1[index + 2];
  93096. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  93097. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  93098. index = index2 * 3;
  93099. x1 = this.clipVertices1[index];
  93100. y1 = this.clipVertices1[index + 1];
  93101. z1 = this.clipVertices1[index + 2];
  93102. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  93103. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  93104. index = index3 * 3;
  93105. x1 = this.clipVertices1[index];
  93106. y1 = this.clipVertices1[index + 1];
  93107. z1 = this.clipVertices1[index + 2];
  93108. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  93109. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  93110. index = index4 * 3;
  93111. x1 = this.clipVertices1[index];
  93112. y1 = this.clipVertices1[index + 1];
  93113. z1 = this.clipVertices1[index + 2];
  93114. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  93115. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  93116. } else {
  93117. //i = numClipVertices;
  93118. //while(i--){
  93119. for (i = 0; i < numClipVertices; i++) {
  93120. index = i * 3;
  93121. x1 = this.clipVertices1[index];
  93122. y1 = this.clipVertices1[index + 1];
  93123. z1 = this.clipVertices1[index + 2];
  93124. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  93125. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  93126. }
  93127. }
  93128. };
  93129. /**
  93130. * A collision detector which detects collisions between sphere and box.
  93131. * @author saharan
  93132. */
  93133. OIMO.SphereBoxCollisionDetector = function (flip) {
  93134. OIMO.CollisionDetector.call(this);
  93135. this.flip = flip;
  93136. };
  93137. OIMO.SphereBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  93138. OIMO.SphereBoxCollisionDetector.prototype.constructor = OIMO.SphereBoxCollisionDetector;
  93139. OIMO.SphereBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  93140. var s;
  93141. var b;
  93142. if (this.flip) {
  93143. s = (shape2);
  93144. b = (shape1);
  93145. } else {
  93146. s = (shape1);
  93147. b = (shape2);
  93148. }
  93149. var D = b.dimentions;
  93150. var ps = s.position;
  93151. var psx = ps.x;
  93152. var psy = ps.y;
  93153. var psz = ps.z;
  93154. var pb = b.position;
  93155. var pbx = pb.x;
  93156. var pby = pb.y;
  93157. var pbz = pb.z;
  93158. var rad = s.radius;
  93159. var hw = b.halfWidth;
  93160. var hh = b.halfHeight;
  93161. var hd = b.halfDepth;
  93162. var dx = psx - pbx;
  93163. var dy = psy - pby;
  93164. var dz = psz - pbz;
  93165. var sx = D[0] * dx + D[1] * dy + D[2] * dz;
  93166. var sy = D[3] * dx + D[4] * dy + D[5] * dz;
  93167. var sz = D[6] * dx + D[7] * dy + D[8] * dz;
  93168. var cx;
  93169. var cy;
  93170. var cz;
  93171. var len;
  93172. var invLen;
  93173. var overlap = 0;
  93174. if (sx > hw) {
  93175. sx = hw;
  93176. } else if (sx < -hw) {
  93177. sx = -hw;
  93178. } else {
  93179. overlap = 1;
  93180. }
  93181. if (sy > hh) {
  93182. sy = hh;
  93183. } else if (sy < -hh) {
  93184. sy = -hh;
  93185. } else {
  93186. overlap |= 2;
  93187. }
  93188. if (sz > hd) {
  93189. sz = hd;
  93190. } else if (sz < -hd) {
  93191. sz = -hd;
  93192. } else {
  93193. overlap |= 4;
  93194. }
  93195. if (overlap == 7) {
  93196. // center of sphere is in the box
  93197. if (sx < 0) {
  93198. dx = hw + sx;
  93199. } else {
  93200. dx = hw - sx;
  93201. }
  93202. if (sy < 0) {
  93203. dy = hh + sy;
  93204. } else {
  93205. dy = hh - sy;
  93206. }
  93207. if (sz < 0) {
  93208. dz = hd + sz;
  93209. } else {
  93210. dz = hd - sz;
  93211. }
  93212. if (dx < dy) {
  93213. if (dx < dz) {
  93214. len = dx - hw;
  93215. if (sx < 0) {
  93216. sx = -hw;
  93217. dx = D[0];
  93218. dy = D[1];
  93219. dz = D[2];
  93220. } else {
  93221. sx = hw;
  93222. dx = -D[0];
  93223. dy = -D[1];
  93224. dz = -D[2];
  93225. }
  93226. } else {
  93227. len = dz - hd;
  93228. if (sz < 0) {
  93229. sz = -hd;
  93230. dx = D[6];
  93231. dy = D[7];
  93232. dz = D[8];
  93233. } else {
  93234. sz = hd;
  93235. dx = -D[6];
  93236. dy = -D[7];
  93237. dz = -D[8];
  93238. }
  93239. }
  93240. } else {
  93241. if (dy < dz) {
  93242. len = dy - hh;
  93243. if (sy < 0) {
  93244. sy = -hh;
  93245. dx = D[3];
  93246. dy = D[4];
  93247. dz = D[5];
  93248. } else {
  93249. sy = hh;
  93250. dx = -D[3];
  93251. dy = -D[4];
  93252. dz = -D[5];
  93253. }
  93254. } else {
  93255. len = dz - hd;
  93256. if (sz < 0) {
  93257. sz = -hd;
  93258. dx = D[6];
  93259. dy = D[7];
  93260. dz = D[8];
  93261. } else {
  93262. sz = hd;
  93263. dx = -D[6];
  93264. dy = -D[7];
  93265. dz = -D[8];
  93266. }
  93267. }
  93268. }
  93269. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  93270. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  93271. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  93272. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  93273. } else {
  93274. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  93275. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  93276. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  93277. dx = cx - ps.x;
  93278. dy = cy - ps.y;
  93279. dz = cz - ps.z;
  93280. len = dx * dx + dy * dy + dz * dz;
  93281. if (len > 0 && len < rad * rad) {
  93282. len = OIMO.sqrt(len);
  93283. invLen = 1 / len;
  93284. dx *= invLen;
  93285. dy *= invLen;
  93286. dz *= invLen;
  93287. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  93288. }
  93289. }
  93290. };
  93291. /**
  93292. * A collision detector which detects collisions between two spheres.
  93293. * @author saharan
  93294. */
  93295. OIMO.SphereSphereCollisionDetector = function () {
  93296. OIMO.CollisionDetector.call(this);
  93297. };
  93298. OIMO.SphereSphereCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  93299. OIMO.SphereSphereCollisionDetector.prototype.constructor = OIMO.SphereSphereCollisionDetector;
  93300. OIMO.SphereSphereCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  93301. var s1 = shape1;
  93302. var s2 = shape2;
  93303. var p1 = s1.position;
  93304. var p2 = s2.position;
  93305. var dx = p2.x - p1.x;
  93306. var dy = p2.y - p1.y;
  93307. var dz = p2.z - p1.z;
  93308. var len = dx * dx + dy * dy + dz * dz;
  93309. var r1 = s1.radius;
  93310. var r2 = s2.radius;
  93311. var rad = r1 + r2;
  93312. if (len > 0 && len < rad * rad) {
  93313. len = OIMO.sqrt(len);
  93314. var invLen = 1 / len;
  93315. dx *= invLen;
  93316. dy *= invLen;
  93317. dz *= invLen;
  93318. manifold.addPoint(p1.x + dx * r1, p1.y + dy * r1, p1.z + dz * r1, dx, dy, dz, len - rad, false);
  93319. }
  93320. };
  93321. OIMO.BoxCylinderCollisionDetector = function (flip) {
  93322. OIMO.CollisionDetector.call(this);
  93323. this.flip = flip;
  93324. };
  93325. OIMO.BoxCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  93326. OIMO.BoxCylinderCollisionDetector.prototype.constructor = OIMO.BoxCylinderCollisionDetector;
  93327. OIMO.BoxCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  93328. var t1x;
  93329. var t1y;
  93330. var t1z;
  93331. var t2x;
  93332. var t2y;
  93333. var t2z;
  93334. var sup = new OIMO.Vec3();
  93335. var len;
  93336. var p1x;
  93337. var p1y;
  93338. var p1z;
  93339. var p2x;
  93340. var p2y;
  93341. var p2z;
  93342. var v01x = c1.position.x;
  93343. var v01y = c1.position.y;
  93344. var v01z = c1.position.z;
  93345. var v02x = c2.position.x;
  93346. var v02y = c2.position.y;
  93347. var v02z = c2.position.z;
  93348. var v0x = v02x - v01x;
  93349. var v0y = v02y - v01y;
  93350. var v0z = v02z - v01z;
  93351. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  93352. var nx = -v0x;
  93353. var ny = -v0y;
  93354. var nz = -v0z;
  93355. this.supportPointB(c1, -nx, -ny, -nz, sup);
  93356. var v11x = sup.x;
  93357. var v11y = sup.y;
  93358. var v11z = sup.z;
  93359. this.supportPointC(c2, nx, ny, nz, sup);
  93360. var v12x = sup.x;
  93361. var v12y = sup.y;
  93362. var v12z = sup.z;
  93363. var v1x = v12x - v11x;
  93364. var v1y = v12y - v11y;
  93365. var v1z = v12z - v11z;
  93366. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  93367. return false;
  93368. }
  93369. nx = v1y * v0z - v1z * v0y;
  93370. ny = v1z * v0x - v1x * v0z;
  93371. nz = v1x * v0y - v1y * v0x;
  93372. if (nx * nx + ny * ny + nz * nz == 0) {
  93373. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  93374. sep.normalize(sep);
  93375. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  93376. return true;
  93377. }
  93378. this.supportPointB(c1, -nx, -ny, -nz, sup);
  93379. var v21x = sup.x;
  93380. var v21y = sup.y;
  93381. var v21z = sup.z;
  93382. this.supportPointC(c2, nx, ny, nz, sup);
  93383. var v22x = sup.x;
  93384. var v22y = sup.y;
  93385. var v22z = sup.z;
  93386. var v2x = v22x - v21x;
  93387. var v2y = v22y - v21y;
  93388. var v2z = v22z - v21z;
  93389. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  93390. return false;
  93391. }
  93392. t1x = v1x - v0x;
  93393. t1y = v1y - v0y;
  93394. t1z = v1z - v0z;
  93395. t2x = v2x - v0x;
  93396. t2y = v2y - v0y;
  93397. t2z = v2z - v0z;
  93398. nx = t1y * t2z - t1z * t2y;
  93399. ny = t1z * t2x - t1x * t2z;
  93400. nz = t1x * t2y - t1y * t2x;
  93401. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  93402. t1x = v1x;
  93403. t1y = v1y;
  93404. t1z = v1z;
  93405. v1x = v2x;
  93406. v1y = v2y;
  93407. v1z = v2z;
  93408. v2x = t1x;
  93409. v2y = t1y;
  93410. v2z = t1z;
  93411. t1x = v11x;
  93412. t1y = v11y;
  93413. t1z = v11z;
  93414. v11x = v21x;
  93415. v11y = v21y;
  93416. v11z = v21z;
  93417. v21x = t1x;
  93418. v21y = t1y;
  93419. v21z = t1z;
  93420. t1x = v12x;
  93421. t1y = v12y;
  93422. t1z = v12z;
  93423. v12x = v22x;
  93424. v12y = v22y;
  93425. v12z = v22z;
  93426. v22x = t1x;
  93427. v22y = t1y;
  93428. v22z = t1z;
  93429. nx = -nx;
  93430. ny = -ny;
  93431. nz = -nz;
  93432. }
  93433. var iterations = 0;
  93434. while (true) {
  93435. if (++iterations > 100) {
  93436. return false;
  93437. }
  93438. this.supportPointB(c1, -nx, -ny, -nz, sup);
  93439. var v31x = sup.x;
  93440. var v31y = sup.y;
  93441. var v31z = sup.z;
  93442. this.supportPointC(c2, nx, ny, nz, sup);
  93443. var v32x = sup.x;
  93444. var v32y = sup.y;
  93445. var v32z = sup.z;
  93446. var v3x = v32x - v31x;
  93447. var v3y = v32y - v31y;
  93448. var v3z = v32z - v31z;
  93449. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  93450. return false;
  93451. }
  93452. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  93453. v2x = v3x;
  93454. v2y = v3y;
  93455. v2z = v3z;
  93456. v21x = v31x;
  93457. v21y = v31y;
  93458. v21z = v31z;
  93459. v22x = v32x;
  93460. v22y = v32y;
  93461. v22z = v32z;
  93462. t1x = v1x - v0x;
  93463. t1y = v1y - v0y;
  93464. t1z = v1z - v0z;
  93465. t2x = v3x - v0x;
  93466. t2y = v3y - v0y;
  93467. t2z = v3z - v0z;
  93468. nx = t1y * t2z - t1z * t2y;
  93469. ny = t1z * t2x - t1x * t2z;
  93470. nz = t1x * t2y - t1y * t2x;
  93471. continue;
  93472. }
  93473. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  93474. v1x = v3x;
  93475. v1y = v3y;
  93476. v1z = v3z;
  93477. v11x = v31x;
  93478. v11y = v31y;
  93479. v11z = v31z;
  93480. v12x = v32x;
  93481. v12y = v32y;
  93482. v12z = v32z;
  93483. t1x = v3x - v0x;
  93484. t1y = v3y - v0y;
  93485. t1z = v3z - v0z;
  93486. t2x = v2x - v0x;
  93487. t2y = v2y - v0y;
  93488. t2z = v2z - v0z;
  93489. nx = t1y * t2z - t1z * t2y;
  93490. ny = t1z * t2x - t1x * t2z;
  93491. nz = t1x * t2y - t1y * t2x;
  93492. continue;
  93493. }
  93494. var hit = false;
  93495. while (true) {
  93496. t1x = v2x - v1x;
  93497. t1y = v2y - v1y;
  93498. t1z = v2z - v1z;
  93499. t2x = v3x - v1x;
  93500. t2y = v3y - v1y;
  93501. t2z = v3z - v1z;
  93502. nx = t1y * t2z - t1z * t2y;
  93503. ny = t1z * t2x - t1x * t2z;
  93504. nz = t1x * t2y - t1y * t2x;
  93505. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  93506. nx *= len;
  93507. ny *= len;
  93508. nz *= len;
  93509. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  93510. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  93511. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  93512. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  93513. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  93514. var sum = b0 + b1 + b2 + b3;
  93515. if (sum <= 0) {
  93516. b0 = 0;
  93517. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  93518. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  93519. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  93520. sum = b1 + b2 + b3;
  93521. }
  93522. var inv = 1 / sum;
  93523. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  93524. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  93525. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  93526. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  93527. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  93528. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  93529. hit = true;
  93530. }
  93531. this.supportPointB(c1, -nx, -ny, -nz, sup);
  93532. var v41x = sup.x;
  93533. var v41y = sup.y;
  93534. var v41z = sup.z;
  93535. this.supportPointC(c2, nx, ny, nz, sup);
  93536. var v42x = sup.x;
  93537. var v42y = sup.y;
  93538. var v42z = sup.z;
  93539. var v4x = v42x - v41x;
  93540. var v4y = v42y - v41y;
  93541. var v4z = v42z - v41z;
  93542. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  93543. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  93544. if (hit) {
  93545. sep.init(-nx, -ny, -nz);
  93546. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  93547. dep.x = separation;
  93548. return true;
  93549. }
  93550. return false;
  93551. }
  93552. if (
  93553. (v4y * v1z - v4z * v1y) * v0x +
  93554. (v4z * v1x - v4x * v1z) * v0y +
  93555. (v4x * v1y - v4y * v1x) * v0z < 0
  93556. ) {
  93557. if (
  93558. (v4y * v2z - v4z * v2y) * v0x +
  93559. (v4z * v2x - v4x * v2z) * v0y +
  93560. (v4x * v2y - v4y * v2x) * v0z < 0
  93561. ) {
  93562. v1x = v4x;
  93563. v1y = v4y;
  93564. v1z = v4z;
  93565. v11x = v41x;
  93566. v11y = v41y;
  93567. v11z = v41z;
  93568. v12x = v42x;
  93569. v12y = v42y;
  93570. v12z = v42z;
  93571. } else {
  93572. v3x = v4x;
  93573. v3y = v4y;
  93574. v3z = v4z;
  93575. v31x = v41x;
  93576. v31y = v41y;
  93577. v31z = v41z;
  93578. v32x = v42x;
  93579. v32y = v42y;
  93580. v32z = v42z;
  93581. }
  93582. } else {
  93583. if (
  93584. (v4y * v3z - v4z * v3y) * v0x +
  93585. (v4z * v3x - v4x * v3z) * v0y +
  93586. (v4x * v3y - v4y * v3x) * v0z < 0
  93587. ) {
  93588. v2x = v4x;
  93589. v2y = v4y;
  93590. v2z = v4z;
  93591. v21x = v41x;
  93592. v21y = v41y;
  93593. v21z = v41z;
  93594. v22x = v42x;
  93595. v22y = v42y;
  93596. v22z = v42z;
  93597. } else {
  93598. v1x = v4x;
  93599. v1y = v4y;
  93600. v1z = v4z;
  93601. v11x = v41x;
  93602. v11y = v41y;
  93603. v11z = v41z;
  93604. v12x = v42x;
  93605. v12y = v42y;
  93606. v12z = v42z;
  93607. }
  93608. }
  93609. }
  93610. }
  93611. //return false;
  93612. };
  93613. OIMO.BoxCylinderCollisionDetector.prototype.supportPointB = function (c, dx, dy, dz, out) {
  93614. var rot = c.rotation.elements;
  93615. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  93616. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  93617. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  93618. var w = c.halfWidth;
  93619. var h = c.halfHeight;
  93620. var d = c.halfDepth;
  93621. var ox;
  93622. var oy;
  93623. var oz;
  93624. if (ldx < 0) ox = -w;
  93625. else ox = w;
  93626. if (ldy < 0) oy = -h;
  93627. else oy = h;
  93628. if (ldz < 0) oz = -d;
  93629. else oz = d;
  93630. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  93631. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  93632. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  93633. out.init(ldx, ldy, ldz);
  93634. };
  93635. OIMO.BoxCylinderCollisionDetector.prototype.supportPointC = function (c, dx, dy, dz, out) {
  93636. var rot = c.rotation.elements;
  93637. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  93638. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  93639. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  93640. var radx = ldx;
  93641. var radz = ldz;
  93642. var len = radx * radx + radz * radz;
  93643. var rad = c.radius;
  93644. var hh = c.halfHeight;
  93645. var ox;
  93646. var oy;
  93647. var oz;
  93648. if (len == 0) {
  93649. if (ldy < 0) {
  93650. ox = rad;
  93651. oy = -hh;
  93652. oz = 0;
  93653. } else {
  93654. ox = rad;
  93655. oy = hh;
  93656. oz = 0;
  93657. }
  93658. } else {
  93659. len = c.radius / OIMO.sqrt(len);
  93660. if (ldy < 0) {
  93661. ox = radx * len;
  93662. oy = -hh;
  93663. oz = radz * len;
  93664. } else {
  93665. ox = radx * len;
  93666. oy = hh;
  93667. oz = radz * len;
  93668. }
  93669. }
  93670. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  93671. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  93672. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  93673. out.init(ldx, ldy, ldz);
  93674. };
  93675. OIMO.BoxCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  93676. var b;
  93677. var c;
  93678. if (this.flip) {
  93679. b = shape2;
  93680. c = shape1;
  93681. } else {
  93682. b = shape1;
  93683. c = shape2;
  93684. }
  93685. var sep = new OIMO.Vec3();
  93686. var pos = new OIMO.Vec3();
  93687. var dep = new OIMO.Vec3();
  93688. var co;
  93689. if (!this.getSep(b, c, sep, pos, dep)) return;
  93690. var pbx = b.position.x;
  93691. var pby = b.position.y;
  93692. var pbz = b.position.z;
  93693. var pcx = c.position.x;
  93694. var pcy = c.position.y;
  93695. var pcz = c.position.z;
  93696. var bw = b.halfWidth;
  93697. var bh = b.halfHeight;
  93698. var bd = b.halfDepth;
  93699. var ch = c.halfHeight;
  93700. var r = c.radius;
  93701. var D = b.dimentions;
  93702. var nwx = D[0];//b.normalDirectionWidth.x;
  93703. var nwy = D[1];//b.normalDirectionWidth.y;
  93704. var nwz = D[2];//b.normalDirectionWidth.z;
  93705. var nhx = D[3];//b.normalDirectionHeight.x;
  93706. var nhy = D[4];//b.normalDirectionHeight.y;
  93707. var nhz = D[5];//b.normalDirectionHeight.z;
  93708. var ndx = D[6];//b.normalDirectionDepth.x;
  93709. var ndy = D[7];//b.normalDirectionDepth.y;
  93710. var ndz = D[8];//b.normalDirectionDepth.z;
  93711. var dwx = D[9];//b.halfDirectionWidth.x;
  93712. var dwy = D[10];//b.halfDirectionWidth.y;
  93713. var dwz = D[11];//b.halfDirectionWidth.z;
  93714. var dhx = D[12];//b.halfDirectionHeight.x;
  93715. var dhy = D[13];//b.halfDirectionHeight.y;
  93716. var dhz = D[14];//b.halfDirectionHeight.z;
  93717. var ddx = D[15];//b.halfDirectionDepth.x;
  93718. var ddy = D[16];//b.halfDirectionDepth.y;
  93719. var ddz = D[17];//b.halfDirectionDepth.z;
  93720. var ncx = c.normalDirection.x;
  93721. var ncy = c.normalDirection.y;
  93722. var ncz = c.normalDirection.z;
  93723. var dcx = c.halfDirection.x;
  93724. var dcy = c.halfDirection.y;
  93725. var dcz = c.halfDirection.z;
  93726. var nx = sep.x;
  93727. var ny = sep.y;
  93728. var nz = sep.z;
  93729. var dotw = nx * nwx + ny * nwy + nz * nwz;
  93730. var doth = nx * nhx + ny * nhy + nz * nhz;
  93731. var dotd = nx * ndx + ny * ndy + nz * ndz;
  93732. var dotc = nx * ncx + ny * ncy + nz * ncz;
  93733. var right1 = dotw > 0;
  93734. var right2 = doth > 0;
  93735. var right3 = dotd > 0;
  93736. var right4 = dotc > 0;
  93737. if (!right1) dotw = -dotw;
  93738. if (!right2) doth = -doth;
  93739. if (!right3) dotd = -dotd;
  93740. if (!right4) dotc = -dotc;
  93741. var state = 0;
  93742. if (dotc > 0.999) {
  93743. if (dotw > 0.999) {
  93744. if (dotw > dotc) state = 1;
  93745. else state = 4;
  93746. } else if (doth > 0.999) {
  93747. if (doth > dotc) state = 2;
  93748. else state = 4;
  93749. } else if (dotd > 0.999) {
  93750. if (dotd > dotc) state = 3;
  93751. else state = 4;
  93752. } else state = 4;
  93753. } else {
  93754. if (dotw > 0.999) state = 1;
  93755. else if (doth > 0.999) state = 2;
  93756. else if (dotd > 0.999) state = 3;
  93757. }
  93758. var cbx;
  93759. var cby;
  93760. var cbz;
  93761. var ccx;
  93762. var ccy;
  93763. var ccz;
  93764. var r00;
  93765. var r01;
  93766. var r02;
  93767. var r10;
  93768. var r11;
  93769. var r12;
  93770. var r20;
  93771. var r21;
  93772. var r22;
  93773. var px;
  93774. var py;
  93775. var pz;
  93776. var pd;
  93777. var dot;
  93778. var len;
  93779. var tx;
  93780. var ty;
  93781. var tz;
  93782. var td;
  93783. var dx;
  93784. var dy;
  93785. var dz;
  93786. var d1x;
  93787. var d1y;
  93788. var d1z;
  93789. var d2x;
  93790. var d2y;
  93791. var d2z;
  93792. var sx;
  93793. var sy;
  93794. var sz;
  93795. var sd;
  93796. var ex;
  93797. var ey;
  93798. var ez;
  93799. var ed;
  93800. var dot1;
  93801. var dot2;
  93802. var t1;
  93803. var t2;
  93804. var dir1x;
  93805. var dir1y;
  93806. var dir1z;
  93807. var dir2x;
  93808. var dir2y;
  93809. var dir2z;
  93810. var dir1l;
  93811. var dir2l;
  93812. if (state == 0) {
  93813. //manifold.addPoint(pos.x,pos.y,pos.z,nx,ny,nz,dep.x,b,c,0,0,false);
  93814. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, dep.x, this.flip);
  93815. } else if (state == 4) {
  93816. if (right4) {
  93817. ccx = pcx - dcx;
  93818. ccy = pcy - dcy;
  93819. ccz = pcz - dcz;
  93820. nx = -ncx;
  93821. ny = -ncy;
  93822. nz = -ncz;
  93823. } else {
  93824. ccx = pcx + dcx;
  93825. ccy = pcy + dcy;
  93826. ccz = pcz + dcz;
  93827. nx = ncx;
  93828. ny = ncy;
  93829. nz = ncz;
  93830. }
  93831. var v1x;
  93832. var v1y;
  93833. var v1z;
  93834. var v2x;
  93835. var v2y;
  93836. var v2z;
  93837. var v3x;
  93838. var v3y;
  93839. var v3z;
  93840. var v4x;
  93841. var v4y;
  93842. var v4z;
  93843. dot = 1;
  93844. state = 0;
  93845. dot1 = nwx * nx + nwy * ny + nwz * nz;
  93846. if (dot1 < dot) {
  93847. dot = dot1;
  93848. state = 0;
  93849. }
  93850. if (-dot1 < dot) {
  93851. dot = -dot1;
  93852. state = 1;
  93853. }
  93854. dot1 = nhx * nx + nhy * ny + nhz * nz;
  93855. if (dot1 < dot) {
  93856. dot = dot1;
  93857. state = 2;
  93858. }
  93859. if (-dot1 < dot) {
  93860. dot = -dot1;
  93861. state = 3;
  93862. }
  93863. dot1 = ndx * nx + ndy * ny + ndz * nz;
  93864. if (dot1 < dot) {
  93865. dot = dot1;
  93866. state = 4;
  93867. }
  93868. if (-dot1 < dot) {
  93869. dot = -dot1;
  93870. state = 5;
  93871. }
  93872. var v = b.elements;
  93873. switch (state) {
  93874. case 0:
  93875. //v=b.vertex1;
  93876. v1x = v[0];//v.x;
  93877. v1y = v[1];//v.y;
  93878. v1z = v[2];//v.z;
  93879. //v=b.vertex3;
  93880. v2x = v[6];//v.x;
  93881. v2y = v[7];//v.y;
  93882. v2z = v[8];//v.z;
  93883. //v=b.vertex4;
  93884. v3x = v[9];//v.x;
  93885. v3y = v[10];//v.y;
  93886. v3z = v[11];//v.z;
  93887. //v=b.vertex2;
  93888. v4x = v[3];//v.x;
  93889. v4y = v[4];//v.y;
  93890. v4z = v[5];//v.z;
  93891. break;
  93892. case 1:
  93893. //v=b.vertex6;
  93894. v1x = v[15];//v.x;
  93895. v1y = v[16];//v.y;
  93896. v1z = v[17];//v.z;
  93897. //v=b.vertex8;
  93898. v2x = v[21];//v.x;
  93899. v2y = v[22];//v.y;
  93900. v2z = v[23];//v.z;
  93901. //v=b.vertex7;
  93902. v3x = v[18];//v.x;
  93903. v3y = v[19];//v.y;
  93904. v3z = v[20];//v.z;
  93905. //v=b.vertex5;
  93906. v4x = v[12];//v.x;
  93907. v4y = v[13];//v.y;
  93908. v4z = v[14];//v.z;
  93909. break;
  93910. case 2:
  93911. //v=b.vertex5;
  93912. v1x = v[12];//v.x;
  93913. v1y = v[13];//v.y;
  93914. v1z = v[14];//v.z;
  93915. //v=b.vertex1;
  93916. v2x = v[0];//v.x;
  93917. v2y = v[1];//v.y;
  93918. v2z = v[2];//v.z;
  93919. //v=b.vertex2;
  93920. v3x = v[3];//v.x;
  93921. v3y = v[4];//v.y;
  93922. v3z = v[5];//v.z;
  93923. //v=b.vertex6;
  93924. v4x = v[15];//v.x;
  93925. v4y = v[16];//v.y;
  93926. v4z = v[17];//v.z;
  93927. break;
  93928. case 3:
  93929. //v=b.vertex8;
  93930. v1x = v[21];//v.x;
  93931. v1y = v[22];//v.y;
  93932. v1z = v[23];//v.z;
  93933. //v=b.vertex4;
  93934. v2x = v[9];//v.x;
  93935. v2y = v[10];//v.y;
  93936. v2z = v[11];//v.z;
  93937. //v=b.vertex3;
  93938. v3x = v[6];//v.x;
  93939. v3y = v[7];//v.y;
  93940. v3z = v[8];//v.z;
  93941. //v=b.vertex7;
  93942. v4x = v[18];//v.x;
  93943. v4y = v[19];//v.y;
  93944. v4z = v[20];//v.z;
  93945. break;
  93946. case 4:
  93947. //v=b.vertex5;
  93948. v1x = v[12];//v.x;
  93949. v1y = v[13];//v.y;
  93950. v1z = v[14];//v.z;
  93951. //v=b.vertex7;
  93952. v2x = v[18];//v.x;
  93953. v2y = v[19];//v.y;
  93954. v2z = v[20];//v.z;
  93955. //v=b.vertex3;
  93956. v3x = v[6];//v.x;
  93957. v3y = v[7];//v.y;
  93958. v3z = v[8];//v.z;
  93959. //v=b.vertex1;
  93960. v4x = v[0];//v.x;
  93961. v4y = v[1];//v.y;
  93962. v4z = v[2];//v.z;
  93963. break;
  93964. case 5:
  93965. //v=b.vertex2;
  93966. v1x = v[3];//v.x;
  93967. v1y = v[4];//v.y;
  93968. v1z = v[5];//v.z;
  93969. //v=b.vertex4;
  93970. v2x = v[9];//v.x;
  93971. v2y = v[10];//v.y;
  93972. v2z = v[11];//v.z;
  93973. //v=b.vertex8;
  93974. v3x = v[21];//v.x;
  93975. v3y = v[22];//v.y;
  93976. v3z = v[23];//v.z;
  93977. //v=b.vertex6;
  93978. v4x = v[15];//v.x;
  93979. v4y = v[16];//v.y;
  93980. v4z = v[17];//v.z;
  93981. break;
  93982. }
  93983. pd = nx * (v1x - ccx) + ny * (v1y - ccy) + nz * (v1z - ccz);
  93984. if (pd <= 0) manifold.addPoint(v1x, v1y, v1z, -nx, -ny, -nz, pd, this.flip);
  93985. pd = nx * (v2x - ccx) + ny * (v2y - ccy) + nz * (v2z - ccz);
  93986. if (pd <= 0) manifold.addPoint(v2x, v2y, v2z, -nx, -ny, -nz, pd, this.flip);
  93987. pd = nx * (v3x - ccx) + ny * (v3y - ccy) + nz * (v3z - ccz);
  93988. if (pd <= 0) manifold.addPoint(v3x, v3y, v3z, -nx, -ny, -nz, pd, this.flip);
  93989. pd = nx * (v4x - ccx) + ny * (v4y - ccy) + nz * (v4z - ccz);
  93990. if (pd <= 0) manifold.addPoint(v4x, v4y, v4z, -nx, -ny, -nz, pd, this.flip);
  93991. } else {
  93992. switch (state) {
  93993. case 1:
  93994. if (right1) {
  93995. cbx = pbx + dwx;
  93996. cby = pby + dwy;
  93997. cbz = pbz + dwz;
  93998. nx = nwx;
  93999. ny = nwy;
  94000. nz = nwz;
  94001. } else {
  94002. cbx = pbx - dwx;
  94003. cby = pby - dwy;
  94004. cbz = pbz - dwz;
  94005. nx = -nwx;
  94006. ny = -nwy;
  94007. nz = -nwz;
  94008. }
  94009. dir1x = nhx;
  94010. dir1y = nhy;
  94011. dir1z = nhz;
  94012. dir1l = bh;
  94013. dir2x = ndx;
  94014. dir2y = ndy;
  94015. dir2z = ndz;
  94016. dir2l = bd;
  94017. break;
  94018. case 2:
  94019. if (right2) {
  94020. cbx = pbx + dhx;
  94021. cby = pby + dhy;
  94022. cbz = pbz + dhz;
  94023. nx = nhx;
  94024. ny = nhy;
  94025. nz = nhz;
  94026. } else {
  94027. cbx = pbx - dhx;
  94028. cby = pby - dhy;
  94029. cbz = pbz - dhz;
  94030. nx = -nhx;
  94031. ny = -nhy;
  94032. nz = -nhz;
  94033. }
  94034. dir1x = nwx;
  94035. dir1y = nwy;
  94036. dir1z = nwz;
  94037. dir1l = bw;
  94038. dir2x = ndx;
  94039. dir2y = ndy;
  94040. dir2z = ndz;
  94041. dir2l = bd;
  94042. break;
  94043. case 3:
  94044. if (right3) {
  94045. cbx = pbx + ddx;
  94046. cby = pby + ddy;
  94047. cbz = pbz + ddz;
  94048. nx = ndx;
  94049. ny = ndy;
  94050. nz = ndz;
  94051. } else {
  94052. cbx = pbx - ddx;
  94053. cby = pby - ddy;
  94054. cbz = pbz - ddz;
  94055. nx = -ndx;
  94056. ny = -ndy;
  94057. nz = -ndz;
  94058. }
  94059. dir1x = nwx;
  94060. dir1y = nwy;
  94061. dir1z = nwz;
  94062. dir1l = bw;
  94063. dir2x = nhx;
  94064. dir2y = nhy;
  94065. dir2z = nhz;
  94066. dir2l = bh;
  94067. break;
  94068. }
  94069. dot = nx * ncx + ny * ncy + nz * ncz;
  94070. if (dot < 0) len = ch;
  94071. else len = -ch;
  94072. ccx = pcx + len * ncx;
  94073. ccy = pcy + len * ncy;
  94074. ccz = pcz + len * ncz;
  94075. if (dotc >= 0.999999) {
  94076. tx = -ny;
  94077. ty = nz;
  94078. tz = nx;
  94079. } else {
  94080. tx = nx;
  94081. ty = ny;
  94082. tz = nz;
  94083. }
  94084. len = tx * ncx + ty * ncy + tz * ncz;
  94085. dx = len * ncx - tx;
  94086. dy = len * ncy - ty;
  94087. dz = len * ncz - tz;
  94088. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  94089. if (len == 0) return;
  94090. len = r / len;
  94091. dx *= len;
  94092. dy *= len;
  94093. dz *= len;
  94094. tx = ccx + dx;
  94095. ty = ccy + dy;
  94096. tz = ccz + dz;
  94097. if (dot < -0.96 || dot > 0.96) {
  94098. r00 = ncx * ncx * 1.5 - 0.5;
  94099. r01 = ncx * ncy * 1.5 - ncz * 0.866025403;
  94100. r02 = ncx * ncz * 1.5 + ncy * 0.866025403;
  94101. r10 = ncy * ncx * 1.5 + ncz * 0.866025403;
  94102. r11 = ncy * ncy * 1.5 - 0.5;
  94103. r12 = ncy * ncz * 1.5 - ncx * 0.866025403;
  94104. r20 = ncz * ncx * 1.5 - ncy * 0.866025403;
  94105. r21 = ncz * ncy * 1.5 + ncx * 0.866025403;
  94106. r22 = ncz * ncz * 1.5 - 0.5;
  94107. px = tx;
  94108. py = ty;
  94109. pz = tz;
  94110. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  94111. tx = px - pd * nx - cbx;
  94112. ty = py - pd * ny - cby;
  94113. tz = pz - pd * nz - cbz;
  94114. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  94115. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  94116. if (sd < -dir1l) sd = -dir1l;
  94117. else if (sd > dir1l) sd = dir1l;
  94118. if (ed < -dir2l) ed = -dir2l;
  94119. else if (ed > dir2l) ed = dir2l;
  94120. tx = sd * dir1x + ed * dir2x;
  94121. ty = sd * dir1y + ed * dir2y;
  94122. tz = sd * dir1z + ed * dir2z;
  94123. px = cbx + tx;
  94124. py = cby + ty;
  94125. pz = cbz + tz;
  94126. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  94127. px = dx * r00 + dy * r01 + dz * r02;
  94128. py = dx * r10 + dy * r11 + dz * r12;
  94129. pz = dx * r20 + dy * r21 + dz * r22;
  94130. px = (dx = px) + ccx;
  94131. py = (dy = py) + ccy;
  94132. pz = (dz = pz) + ccz;
  94133. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  94134. if (pd <= 0) {
  94135. tx = px - pd * nx - cbx;
  94136. ty = py - pd * ny - cby;
  94137. tz = pz - pd * nz - cbz;
  94138. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  94139. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  94140. if (sd < -dir1l) sd = -dir1l;
  94141. else if (sd > dir1l) sd = dir1l;
  94142. if (ed < -dir2l) ed = -dir2l;
  94143. else if (ed > dir2l) ed = dir2l;
  94144. tx = sd * dir1x + ed * dir2x;
  94145. ty = sd * dir1y + ed * dir2y;
  94146. tz = sd * dir1z + ed * dir2z;
  94147. px = cbx + tx;
  94148. py = cby + ty;
  94149. pz = cbz + tz;
  94150. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,2,0,false);
  94151. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  94152. }
  94153. px = dx * r00 + dy * r01 + dz * r02;
  94154. py = dx * r10 + dy * r11 + dz * r12;
  94155. pz = dx * r20 + dy * r21 + dz * r22;
  94156. px = (dx = px) + ccx;
  94157. py = (dy = py) + ccy;
  94158. pz = (dz = pz) + ccz;
  94159. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  94160. if (pd <= 0) {
  94161. tx = px - pd * nx - cbx;
  94162. ty = py - pd * ny - cby;
  94163. tz = pz - pd * nz - cbz;
  94164. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  94165. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  94166. if (sd < -dir1l) sd = -dir1l;
  94167. else if (sd > dir1l) sd = dir1l;
  94168. if (ed < -dir2l) ed = -dir2l;
  94169. else if (ed > dir2l) ed = dir2l;
  94170. tx = sd * dir1x + ed * dir2x;
  94171. ty = sd * dir1y + ed * dir2y;
  94172. tz = sd * dir1z + ed * dir2z;
  94173. px = cbx + tx;
  94174. py = cby + ty;
  94175. pz = cbz + tz;
  94176. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,3,0,false);
  94177. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  94178. }
  94179. } else {
  94180. sx = tx;
  94181. sy = ty;
  94182. sz = tz;
  94183. sd = nx * (sx - cbx) + ny * (sy - cby) + nz * (sz - cbz);
  94184. sx -= sd * nx;
  94185. sy -= sd * ny;
  94186. sz -= sd * nz;
  94187. if (dot > 0) {
  94188. ex = tx + dcx * 2;
  94189. ey = ty + dcy * 2;
  94190. ez = tz + dcz * 2;
  94191. } else {
  94192. ex = tx - dcx * 2;
  94193. ey = ty - dcy * 2;
  94194. ez = tz - dcz * 2;
  94195. }
  94196. ed = nx * (ex - cbx) + ny * (ey - cby) + nz * (ez - cbz);
  94197. ex -= ed * nx;
  94198. ey -= ed * ny;
  94199. ez -= ed * nz;
  94200. d1x = sx - cbx;
  94201. d1y = sy - cby;
  94202. d1z = sz - cbz;
  94203. d2x = ex - cbx;
  94204. d2y = ey - cby;
  94205. d2z = ez - cbz;
  94206. tx = ex - sx;
  94207. ty = ey - sy;
  94208. tz = ez - sz;
  94209. td = ed - sd;
  94210. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  94211. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  94212. dot1 = dotw - dir1l;
  94213. dot2 = doth - dir1l;
  94214. if (dot1 > 0) {
  94215. if (dot2 > 0) return;
  94216. t1 = dot1 / (dot1 - dot2);
  94217. sx = sx + tx * t1;
  94218. sy = sy + ty * t1;
  94219. sz = sz + tz * t1;
  94220. sd = sd + td * t1;
  94221. d1x = sx - cbx;
  94222. d1y = sy - cby;
  94223. d1z = sz - cbz;
  94224. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  94225. tx = ex - sx;
  94226. ty = ey - sy;
  94227. tz = ez - sz;
  94228. td = ed - sd;
  94229. } else if (dot2 > 0) {
  94230. t1 = dot1 / (dot1 - dot2);
  94231. ex = sx + tx * t1;
  94232. ey = sy + ty * t1;
  94233. ez = sz + tz * t1;
  94234. ed = sd + td * t1;
  94235. d2x = ex - cbx;
  94236. d2y = ey - cby;
  94237. d2z = ez - cbz;
  94238. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  94239. tx = ex - sx;
  94240. ty = ey - sy;
  94241. tz = ez - sz;
  94242. td = ed - sd;
  94243. }
  94244. dot1 = dotw + dir1l;
  94245. dot2 = doth + dir1l;
  94246. if (dot1 < 0) {
  94247. if (dot2 < 0) return;
  94248. t1 = dot1 / (dot1 - dot2);
  94249. sx = sx + tx * t1;
  94250. sy = sy + ty * t1;
  94251. sz = sz + tz * t1;
  94252. sd = sd + td * t1;
  94253. d1x = sx - cbx;
  94254. d1y = sy - cby;
  94255. d1z = sz - cbz;
  94256. tx = ex - sx;
  94257. ty = ey - sy;
  94258. tz = ez - sz;
  94259. td = ed - sd;
  94260. } else if (dot2 < 0) {
  94261. t1 = dot1 / (dot1 - dot2);
  94262. ex = sx + tx * t1;
  94263. ey = sy + ty * t1;
  94264. ez = sz + tz * t1;
  94265. ed = sd + td * t1;
  94266. d2x = ex - cbx;
  94267. d2y = ey - cby;
  94268. d2z = ez - cbz;
  94269. tx = ex - sx;
  94270. ty = ey - sy;
  94271. tz = ez - sz;
  94272. td = ed - sd;
  94273. }
  94274. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  94275. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  94276. dot1 = dotw - dir2l;
  94277. dot2 = doth - dir2l;
  94278. if (dot1 > 0) {
  94279. if (dot2 > 0) return;
  94280. t1 = dot1 / (dot1 - dot2);
  94281. sx = sx + tx * t1;
  94282. sy = sy + ty * t1;
  94283. sz = sz + tz * t1;
  94284. sd = sd + td * t1;
  94285. d1x = sx - cbx;
  94286. d1y = sy - cby;
  94287. d1z = sz - cbz;
  94288. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  94289. tx = ex - sx;
  94290. ty = ey - sy;
  94291. tz = ez - sz;
  94292. td = ed - sd;
  94293. } else if (dot2 > 0) {
  94294. t1 = dot1 / (dot1 - dot2);
  94295. ex = sx + tx * t1;
  94296. ey = sy + ty * t1;
  94297. ez = sz + tz * t1;
  94298. ed = sd + td * t1;
  94299. d2x = ex - cbx;
  94300. d2y = ey - cby;
  94301. d2z = ez - cbz;
  94302. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  94303. tx = ex - sx;
  94304. ty = ey - sy;
  94305. tz = ez - sz;
  94306. td = ed - sd;
  94307. }
  94308. dot1 = dotw + dir2l;
  94309. dot2 = doth + dir2l;
  94310. if (dot1 < 0) {
  94311. if (dot2 < 0) return;
  94312. t1 = dot1 / (dot1 - dot2);
  94313. sx = sx + tx * t1;
  94314. sy = sy + ty * t1;
  94315. sz = sz + tz * t1;
  94316. sd = sd + td * t1;
  94317. } else if (dot2 < 0) {
  94318. t1 = dot1 / (dot1 - dot2);
  94319. ex = sx + tx * t1;
  94320. ey = sy + ty * t1;
  94321. ez = sz + tz * t1;
  94322. ed = sd + td * t1;
  94323. }
  94324. if (sd < 0) {
  94325. //manifold.addPoint(sx,sy,sz,nx,ny,nz,sd,b,c,1,0,false);
  94326. manifold.addPoint(sx, sy, sz, nx, ny, nz, sd, this.flip);
  94327. }
  94328. if (ed < 0) {
  94329. //manifold.addPoint(ex,ey,ez,nx,ny,nz,ed,b,c,4,0,false);
  94330. manifold.addPoint(ex, ey, ez, nx, ny, nz, ed, this.flip);
  94331. }
  94332. }
  94333. }
  94334. };
  94335. OIMO.CylinderCylinderCollisionDetector = function () {
  94336. OIMO.CollisionDetector.call(this);
  94337. };
  94338. OIMO.CylinderCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  94339. OIMO.CylinderCylinderCollisionDetector.prototype.constructor = OIMO.CylinderCylinderCollisionDetector;
  94340. OIMO.CylinderCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  94341. var t1x;
  94342. var t1y;
  94343. var t1z;
  94344. var t2x;
  94345. var t2y;
  94346. var t2z;
  94347. var sup = new OIMO.Vec3();
  94348. var len;
  94349. var p1x;
  94350. var p1y;
  94351. var p1z;
  94352. var p2x;
  94353. var p2y;
  94354. var p2z;
  94355. var v01x = c1.position.x;
  94356. var v01y = c1.position.y;
  94357. var v01z = c1.position.z;
  94358. var v02x = c2.position.x;
  94359. var v02y = c2.position.y;
  94360. var v02z = c2.position.z;
  94361. var v0x = v02x - v01x;
  94362. var v0y = v02y - v01y;
  94363. var v0z = v02z - v01z;
  94364. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  94365. var nx = -v0x;
  94366. var ny = -v0y;
  94367. var nz = -v0z;
  94368. this.supportPoint(c1, -nx, -ny, -nz, sup);
  94369. var v11x = sup.x;
  94370. var v11y = sup.y;
  94371. var v11z = sup.z;
  94372. this.supportPoint(c2, nx, ny, nz, sup);
  94373. var v12x = sup.x;
  94374. var v12y = sup.y;
  94375. var v12z = sup.z;
  94376. var v1x = v12x - v11x;
  94377. var v1y = v12y - v11y;
  94378. var v1z = v12z - v11z;
  94379. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  94380. return false;
  94381. }
  94382. nx = v1y * v0z - v1z * v0y;
  94383. ny = v1z * v0x - v1x * v0z;
  94384. nz = v1x * v0y - v1y * v0x;
  94385. if (nx * nx + ny * ny + nz * nz == 0) {
  94386. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  94387. sep.normalize(sep);
  94388. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  94389. return true;
  94390. }
  94391. this.supportPoint(c1, -nx, -ny, -nz, sup);
  94392. var v21x = sup.x;
  94393. var v21y = sup.y;
  94394. var v21z = sup.z;
  94395. this.supportPoint(c2, nx, ny, nz, sup);
  94396. var v22x = sup.x;
  94397. var v22y = sup.y;
  94398. var v22z = sup.z;
  94399. var v2x = v22x - v21x;
  94400. var v2y = v22y - v21y;
  94401. var v2z = v22z - v21z;
  94402. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  94403. return false;
  94404. }
  94405. t1x = v1x - v0x;
  94406. t1y = v1y - v0y;
  94407. t1z = v1z - v0z;
  94408. t2x = v2x - v0x;
  94409. t2y = v2y - v0y;
  94410. t2z = v2z - v0z;
  94411. nx = t1y * t2z - t1z * t2y;
  94412. ny = t1z * t2x - t1x * t2z;
  94413. nz = t1x * t2y - t1y * t2x;
  94414. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  94415. t1x = v1x;
  94416. t1y = v1y;
  94417. t1z = v1z;
  94418. v1x = v2x;
  94419. v1y = v2y;
  94420. v1z = v2z;
  94421. v2x = t1x;
  94422. v2y = t1y;
  94423. v2z = t1z;
  94424. t1x = v11x;
  94425. t1y = v11y;
  94426. t1z = v11z;
  94427. v11x = v21x;
  94428. v11y = v21y;
  94429. v11z = v21z;
  94430. v21x = t1x;
  94431. v21y = t1y;
  94432. v21z = t1z;
  94433. t1x = v12x;
  94434. t1y = v12y;
  94435. t1z = v12z;
  94436. v12x = v22x;
  94437. v12y = v22y;
  94438. v12z = v22z;
  94439. v22x = t1x;
  94440. v22y = t1y;
  94441. v22z = t1z;
  94442. nx = -nx;
  94443. ny = -ny;
  94444. nz = -nz;
  94445. }
  94446. var iterations = 0;
  94447. while (true) {
  94448. if (++iterations > 100) {
  94449. return false;
  94450. }
  94451. this.supportPoint(c1, -nx, -ny, -nz, sup);
  94452. var v31x = sup.x;
  94453. var v31y = sup.y;
  94454. var v31z = sup.z;
  94455. this.supportPoint(c2, nx, ny, nz, sup);
  94456. var v32x = sup.x;
  94457. var v32y = sup.y;
  94458. var v32z = sup.z;
  94459. var v3x = v32x - v31x;
  94460. var v3y = v32y - v31y;
  94461. var v3z = v32z - v31z;
  94462. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  94463. return false;
  94464. }
  94465. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  94466. v2x = v3x;
  94467. v2y = v3y;
  94468. v2z = v3z;
  94469. v21x = v31x;
  94470. v21y = v31y;
  94471. v21z = v31z;
  94472. v22x = v32x;
  94473. v22y = v32y;
  94474. v22z = v32z;
  94475. t1x = v1x - v0x;
  94476. t1y = v1y - v0y;
  94477. t1z = v1z - v0z;
  94478. t2x = v3x - v0x;
  94479. t2y = v3y - v0y;
  94480. t2z = v3z - v0z;
  94481. nx = t1y * t2z - t1z * t2y;
  94482. ny = t1z * t2x - t1x * t2z;
  94483. nz = t1x * t2y - t1y * t2x;
  94484. continue;
  94485. }
  94486. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  94487. v1x = v3x;
  94488. v1y = v3y;
  94489. v1z = v3z;
  94490. v11x = v31x;
  94491. v11y = v31y;
  94492. v11z = v31z;
  94493. v12x = v32x;
  94494. v12y = v32y;
  94495. v12z = v32z;
  94496. t1x = v3x - v0x;
  94497. t1y = v3y - v0y;
  94498. t1z = v3z - v0z;
  94499. t2x = v2x - v0x;
  94500. t2y = v2y - v0y;
  94501. t2z = v2z - v0z;
  94502. nx = t1y * t2z - t1z * t2y;
  94503. ny = t1z * t2x - t1x * t2z;
  94504. nz = t1x * t2y - t1y * t2x;
  94505. continue;
  94506. }
  94507. var hit = false;
  94508. while (true) {
  94509. t1x = v2x - v1x;
  94510. t1y = v2y - v1y;
  94511. t1z = v2z - v1z;
  94512. t2x = v3x - v1x;
  94513. t2y = v3y - v1y;
  94514. t2z = v3z - v1z;
  94515. nx = t1y * t2z - t1z * t2y;
  94516. ny = t1z * t2x - t1x * t2z;
  94517. nz = t1x * t2y - t1y * t2x;
  94518. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  94519. nx *= len;
  94520. ny *= len;
  94521. nz *= len;
  94522. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  94523. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  94524. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  94525. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  94526. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  94527. var sum = b0 + b1 + b2 + b3;
  94528. if (sum <= 0) {
  94529. b0 = 0;
  94530. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  94531. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  94532. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  94533. sum = b1 + b2 + b3;
  94534. }
  94535. var inv = 1 / sum;
  94536. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  94537. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  94538. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  94539. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  94540. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  94541. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  94542. hit = true;
  94543. }
  94544. this.supportPoint(c1, -nx, -ny, -nz, sup);
  94545. var v41x = sup.x;
  94546. var v41y = sup.y;
  94547. var v41z = sup.z;
  94548. this.supportPoint(c2, nx, ny, nz, sup);
  94549. var v42x = sup.x;
  94550. var v42y = sup.y;
  94551. var v42z = sup.z;
  94552. var v4x = v42x - v41x;
  94553. var v4y = v42y - v41y;
  94554. var v4z = v42z - v41z;
  94555. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  94556. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  94557. if (hit) {
  94558. sep.init(-nx, -ny, -nz);
  94559. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  94560. dep.x = separation;
  94561. return true;
  94562. }
  94563. return false;
  94564. }
  94565. if (
  94566. (v4y * v1z - v4z * v1y) * v0x +
  94567. (v4z * v1x - v4x * v1z) * v0y +
  94568. (v4x * v1y - v4y * v1x) * v0z < 0
  94569. ) {
  94570. if (
  94571. (v4y * v2z - v4z * v2y) * v0x +
  94572. (v4z * v2x - v4x * v2z) * v0y +
  94573. (v4x * v2y - v4y * v2x) * v0z < 0
  94574. ) {
  94575. v1x = v4x;
  94576. v1y = v4y;
  94577. v1z = v4z;
  94578. v11x = v41x;
  94579. v11y = v41y;
  94580. v11z = v41z;
  94581. v12x = v42x;
  94582. v12y = v42y;
  94583. v12z = v42z;
  94584. } else {
  94585. v3x = v4x;
  94586. v3y = v4y;
  94587. v3z = v4z;
  94588. v31x = v41x;
  94589. v31y = v41y;
  94590. v31z = v41z;
  94591. v32x = v42x;
  94592. v32y = v42y;
  94593. v32z = v42z;
  94594. }
  94595. } else {
  94596. if (
  94597. (v4y * v3z - v4z * v3y) * v0x +
  94598. (v4z * v3x - v4x * v3z) * v0y +
  94599. (v4x * v3y - v4y * v3x) * v0z < 0
  94600. ) {
  94601. v2x = v4x;
  94602. v2y = v4y;
  94603. v2z = v4z;
  94604. v21x = v41x;
  94605. v21y = v41y;
  94606. v21z = v41z;
  94607. v22x = v42x;
  94608. v22y = v42y;
  94609. v22z = v42z;
  94610. } else {
  94611. v1x = v4x;
  94612. v1y = v4y;
  94613. v1z = v4z;
  94614. v11x = v41x;
  94615. v11y = v41y;
  94616. v11z = v41z;
  94617. v12x = v42x;
  94618. v12y = v42y;
  94619. v12z = v42z;
  94620. }
  94621. }
  94622. }
  94623. }
  94624. //return false;
  94625. };
  94626. OIMO.CylinderCylinderCollisionDetector.prototype.supportPoint = function (c, dx, dy, dz, out) {
  94627. var rot = c.rotation.elements;
  94628. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  94629. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  94630. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  94631. var radx = ldx;
  94632. var radz = ldz;
  94633. var len = radx * radx + radz * radz;
  94634. var rad = c.radius;
  94635. var hh = c.halfHeight;
  94636. var ox;
  94637. var oy;
  94638. var oz;
  94639. if (len == 0) {
  94640. if (ldy < 0) {
  94641. ox = rad;
  94642. oy = -hh;
  94643. oz = 0;
  94644. } else {
  94645. ox = rad;
  94646. oy = hh;
  94647. oz = 0;
  94648. }
  94649. } else {
  94650. len = c.radius / OIMO.sqrt(len);
  94651. if (ldy < 0) {
  94652. ox = radx * len;
  94653. oy = -hh;
  94654. oz = radz * len;
  94655. } else {
  94656. ox = radx * len;
  94657. oy = hh;
  94658. oz = radz * len;
  94659. }
  94660. }
  94661. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  94662. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  94663. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  94664. out.init(ldx, ldy, ldz);
  94665. };
  94666. OIMO.CylinderCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  94667. var c1;
  94668. var c2;
  94669. if (shape1.id < shape2.id) {
  94670. c1 = shape1;
  94671. c2 = shape2;
  94672. } else {
  94673. c1 = shape2;
  94674. c2 = shape1;
  94675. }
  94676. var p1 = c1.position;
  94677. var p2 = c2.position;
  94678. var p1x = p1.x;
  94679. var p1y = p1.y;
  94680. var p1z = p1.z;
  94681. var p2x = p2.x;
  94682. var p2y = p2.y;
  94683. var p2z = p2.z;
  94684. var h1 = c1.halfHeight;
  94685. var h2 = c2.halfHeight;
  94686. var n1 = c1.normalDirection;
  94687. var n2 = c2.normalDirection;
  94688. var d1 = c1.halfDirection;
  94689. var d2 = c2.halfDirection;
  94690. var r1 = c1.radius;
  94691. var r2 = c2.radius;
  94692. var n1x = n1.x;
  94693. var n1y = n1.y;
  94694. var n1z = n1.z;
  94695. var n2x = n2.x;
  94696. var n2y = n2.y;
  94697. var n2z = n2.z;
  94698. var d1x = d1.x;
  94699. var d1y = d1.y;
  94700. var d1z = d1.z;
  94701. var d2x = d2.x;
  94702. var d2y = d2.y;
  94703. var d2z = d2.z;
  94704. var dx = p1x - p2x;
  94705. var dy = p1y - p2y;
  94706. var dz = p1z - p2z;
  94707. var len;
  94708. var len1;
  94709. var len2;
  94710. var c;
  94711. var c1x;
  94712. var c1y;
  94713. var c1z;
  94714. var c2x;
  94715. var c2y;
  94716. var c2z;
  94717. var tx;
  94718. var ty;
  94719. var tz;
  94720. var sx;
  94721. var sy;
  94722. var sz;
  94723. var ex;
  94724. var ey;
  94725. var ez;
  94726. var depth1;
  94727. var depth2;
  94728. var dot;
  94729. var t1;
  94730. var t2;
  94731. var sep = new OIMO.Vec3();
  94732. var pos = new OIMO.Vec3();
  94733. var dep = new OIMO.Vec3();
  94734. if (!this.getSep(c1, c2, sep, pos, dep)) return;
  94735. var dot1 = sep.x * n1x + sep.y * n1y + sep.z * n1z;
  94736. var dot2 = sep.x * n2x + sep.y * n2y + sep.z * n2z;
  94737. var right1 = dot1 > 0;
  94738. var right2 = dot2 > 0;
  94739. if (!right1) dot1 = -dot1;
  94740. if (!right2) dot2 = -dot2;
  94741. var state = 0;
  94742. if (dot1 > 0.999 || dot2 > 0.999) {
  94743. if (dot1 > dot2) state = 1;
  94744. else state = 2;
  94745. }
  94746. var nx;
  94747. var ny;
  94748. var nz;
  94749. var depth = dep.x;
  94750. var r00;
  94751. var r01;
  94752. var r02;
  94753. var r10;
  94754. var r11;
  94755. var r12;
  94756. var r20;
  94757. var r21;
  94758. var r22;
  94759. var px;
  94760. var py;
  94761. var pz;
  94762. var pd;
  94763. var a;
  94764. var b;
  94765. var e;
  94766. var f;
  94767. nx = sep.x;
  94768. ny = sep.y;
  94769. nz = sep.z;
  94770. switch (state) {
  94771. case 0:
  94772. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, depth, false);
  94773. break;
  94774. case 1:
  94775. if (right1) {
  94776. c1x = p1x + d1x;
  94777. c1y = p1y + d1y;
  94778. c1z = p1z + d1z;
  94779. nx = n1x;
  94780. ny = n1y;
  94781. nz = n1z;
  94782. } else {
  94783. c1x = p1x - d1x;
  94784. c1y = p1y - d1y;
  94785. c1z = p1z - d1z;
  94786. nx = -n1x;
  94787. ny = -n1y;
  94788. nz = -n1z;
  94789. }
  94790. dot = nx * n2x + ny * n2y + nz * n2z;
  94791. if (dot < 0) len = h2;
  94792. else len = -h2;
  94793. c2x = p2x + len * n2x;
  94794. c2y = p2y + len * n2y;
  94795. c2z = p2z + len * n2z;
  94796. if (dot2 >= 0.999999) {
  94797. tx = -ny;
  94798. ty = nz;
  94799. tz = nx;
  94800. } else {
  94801. tx = nx;
  94802. ty = ny;
  94803. tz = nz;
  94804. }
  94805. len = tx * n2x + ty * n2y + tz * n2z;
  94806. dx = len * n2x - tx;
  94807. dy = len * n2y - ty;
  94808. dz = len * n2z - tz;
  94809. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  94810. if (len == 0) break;
  94811. len = r2 / len;
  94812. dx *= len;
  94813. dy *= len;
  94814. dz *= len;
  94815. tx = c2x + dx;
  94816. ty = c2y + dy;
  94817. tz = c2z + dz;
  94818. if (dot < -0.96 || dot > 0.96) {
  94819. r00 = n2x * n2x * 1.5 - 0.5;
  94820. r01 = n2x * n2y * 1.5 - n2z * 0.866025403;
  94821. r02 = n2x * n2z * 1.5 + n2y * 0.866025403;
  94822. r10 = n2y * n2x * 1.5 + n2z * 0.866025403;
  94823. r11 = n2y * n2y * 1.5 - 0.5;
  94824. r12 = n2y * n2z * 1.5 - n2x * 0.866025403;
  94825. r20 = n2z * n2x * 1.5 - n2y * 0.866025403;
  94826. r21 = n2z * n2y * 1.5 + n2x * 0.866025403;
  94827. r22 = n2z * n2z * 1.5 - 0.5;
  94828. px = tx;
  94829. py = ty;
  94830. pz = tz;
  94831. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  94832. tx = px - pd * nx - c1x;
  94833. ty = py - pd * ny - c1y;
  94834. tz = pz - pd * nz - c1z;
  94835. len = tx * tx + ty * ty + tz * tz;
  94836. if (len > r1 * r1) {
  94837. len = r1 / OIMO.sqrt(len);
  94838. tx *= len;
  94839. ty *= len;
  94840. tz *= len;
  94841. }
  94842. px = c1x + tx;
  94843. py = c1y + ty;
  94844. pz = c1z + tz;
  94845. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  94846. px = dx * r00 + dy * r01 + dz * r02;
  94847. py = dx * r10 + dy * r11 + dz * r12;
  94848. pz = dx * r20 + dy * r21 + dz * r22;
  94849. px = (dx = px) + c2x;
  94850. py = (dy = py) + c2y;
  94851. pz = (dz = pz) + c2z;
  94852. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  94853. if (pd <= 0) {
  94854. tx = px - pd * nx - c1x;
  94855. ty = py - pd * ny - c1y;
  94856. tz = pz - pd * nz - c1z;
  94857. len = tx * tx + ty * ty + tz * tz;
  94858. if (len > r1 * r1) {
  94859. len = r1 / OIMO.sqrt(len);
  94860. tx *= len;
  94861. ty *= len;
  94862. tz *= len;
  94863. }
  94864. px = c1x + tx;
  94865. py = c1y + ty;
  94866. pz = c1z + tz;
  94867. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  94868. }
  94869. px = dx * r00 + dy * r01 + dz * r02;
  94870. py = dx * r10 + dy * r11 + dz * r12;
  94871. pz = dx * r20 + dy * r21 + dz * r22;
  94872. px = (dx = px) + c2x;
  94873. py = (dy = py) + c2y;
  94874. pz = (dz = pz) + c2z;
  94875. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  94876. if (pd <= 0) {
  94877. tx = px - pd * nx - c1x;
  94878. ty = py - pd * ny - c1y;
  94879. tz = pz - pd * nz - c1z;
  94880. len = tx * tx + ty * ty + tz * tz;
  94881. if (len > r1 * r1) {
  94882. len = r1 / OIMO.sqrt(len);
  94883. tx *= len;
  94884. ty *= len;
  94885. tz *= len;
  94886. }
  94887. px = c1x + tx;
  94888. py = c1y + ty;
  94889. pz = c1z + tz;
  94890. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  94891. }
  94892. } else {
  94893. sx = tx;
  94894. sy = ty;
  94895. sz = tz;
  94896. depth1 = nx * (sx - c1x) + ny * (sy - c1y) + nz * (sz - c1z);
  94897. sx -= depth1 * nx;
  94898. sy -= depth1 * ny;
  94899. sz -= depth1 * nz;
  94900. if (dot > 0) {
  94901. ex = tx + n2x * h2 * 2;
  94902. ey = ty + n2y * h2 * 2;
  94903. ez = tz + n2z * h2 * 2;
  94904. } else {
  94905. ex = tx - n2x * h2 * 2;
  94906. ey = ty - n2y * h2 * 2;
  94907. ez = tz - n2z * h2 * 2;
  94908. }
  94909. depth2 = nx * (ex - c1x) + ny * (ey - c1y) + nz * (ez - c1z);
  94910. ex -= depth2 * nx;
  94911. ey -= depth2 * ny;
  94912. ez -= depth2 * nz;
  94913. dx = c1x - sx;
  94914. dy = c1y - sy;
  94915. dz = c1z - sz;
  94916. tx = ex - sx;
  94917. ty = ey - sy;
  94918. tz = ez - sz;
  94919. a = dx * dx + dy * dy + dz * dz;
  94920. b = dx * tx + dy * ty + dz * tz;
  94921. e = tx * tx + ty * ty + tz * tz;
  94922. f = b * b - e * (a - r1 * r1);
  94923. if (f < 0) break;
  94924. f = OIMO.sqrt(f);
  94925. t1 = (b + f) / e;
  94926. t2 = (b - f) / e;
  94927. if (t2 < t1) {
  94928. len = t1;
  94929. t1 = t2;
  94930. t2 = len;
  94931. }
  94932. if (t2 > 1) t2 = 1;
  94933. if (t1 < 0) t1 = 0;
  94934. tx = sx + (ex - sx) * t1;
  94935. ty = sy + (ey - sy) * t1;
  94936. tz = sz + (ez - sz) * t1;
  94937. ex = sx + (ex - sx) * t2;
  94938. ey = sy + (ey - sy) * t2;
  94939. ez = sz + (ez - sz) * t2;
  94940. sx = tx;
  94941. sy = ty;
  94942. sz = tz;
  94943. len = depth1 + (depth2 - depth1) * t1;
  94944. depth2 = depth1 + (depth2 - depth1) * t2;
  94945. depth1 = len;
  94946. if (depth1 < 0) manifold.addPoint(sx, sy, sz, nx, ny, nz, pd, false);
  94947. if (depth2 < 0) manifold.addPoint(ex, ey, ez, nx, ny, nz, pd, false);
  94948. }
  94949. break;
  94950. case 2:
  94951. if (right2) {
  94952. c2x = p2x - d2x;
  94953. c2y = p2y - d2y;
  94954. c2z = p2z - d2z;
  94955. nx = -n2x;
  94956. ny = -n2y;
  94957. nz = -n2z;
  94958. } else {
  94959. c2x = p2x + d2x;
  94960. c2y = p2y + d2y;
  94961. c2z = p2z + d2z;
  94962. nx = n2x;
  94963. ny = n2y;
  94964. nz = n2z;
  94965. }
  94966. dot = nx * n1x + ny * n1y + nz * n1z;
  94967. if (dot < 0) len = h1;
  94968. else len = -h1;
  94969. c1x = p1x + len * n1x;
  94970. c1y = p1y + len * n1y;
  94971. c1z = p1z + len * n1z;
  94972. if (dot1 >= 0.999999) {
  94973. tx = -ny;
  94974. ty = nz;
  94975. tz = nx;
  94976. } else {
  94977. tx = nx;
  94978. ty = ny;
  94979. tz = nz;
  94980. }
  94981. len = tx * n1x + ty * n1y + tz * n1z;
  94982. dx = len * n1x - tx;
  94983. dy = len * n1y - ty;
  94984. dz = len * n1z - tz;
  94985. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  94986. if (len == 0) break;
  94987. len = r1 / len;
  94988. dx *= len;
  94989. dy *= len;
  94990. dz *= len;
  94991. tx = c1x + dx;
  94992. ty = c1y + dy;
  94993. tz = c1z + dz;
  94994. if (dot < -0.96 || dot > 0.96) {
  94995. r00 = n1x * n1x * 1.5 - 0.5;
  94996. r01 = n1x * n1y * 1.5 - n1z * 0.866025403;
  94997. r02 = n1x * n1z * 1.5 + n1y * 0.866025403;
  94998. r10 = n1y * n1x * 1.5 + n1z * 0.866025403;
  94999. r11 = n1y * n1y * 1.5 - 0.5;
  95000. r12 = n1y * n1z * 1.5 - n1x * 0.866025403;
  95001. r20 = n1z * n1x * 1.5 - n1y * 0.866025403;
  95002. r21 = n1z * n1y * 1.5 + n1x * 0.866025403;
  95003. r22 = n1z * n1z * 1.5 - 0.5;
  95004. px = tx;
  95005. py = ty;
  95006. pz = tz;
  95007. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  95008. tx = px - pd * nx - c2x;
  95009. ty = py - pd * ny - c2y;
  95010. tz = pz - pd * nz - c2z;
  95011. len = tx * tx + ty * ty + tz * tz;
  95012. if (len > r2 * r2) {
  95013. len = r2 / OIMO.sqrt(len);
  95014. tx *= len;
  95015. ty *= len;
  95016. tz *= len;
  95017. }
  95018. px = c2x + tx;
  95019. py = c2y + ty;
  95020. pz = c2z + tz;
  95021. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  95022. px = dx * r00 + dy * r01 + dz * r02;
  95023. py = dx * r10 + dy * r11 + dz * r12;
  95024. pz = dx * r20 + dy * r21 + dz * r22;
  95025. px = (dx = px) + c1x;
  95026. py = (dy = py) + c1y;
  95027. pz = (dz = pz) + c1z;
  95028. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  95029. if (pd <= 0) {
  95030. tx = px - pd * nx - c2x;
  95031. ty = py - pd * ny - c2y;
  95032. tz = pz - pd * nz - c2z;
  95033. len = tx * tx + ty * ty + tz * tz;
  95034. if (len > r2 * r2) {
  95035. len = r2 / OIMO.sqrt(len);
  95036. tx *= len;
  95037. ty *= len;
  95038. tz *= len;
  95039. }
  95040. px = c2x + tx;
  95041. py = c2y + ty;
  95042. pz = c2z + tz;
  95043. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  95044. }
  95045. px = dx * r00 + dy * r01 + dz * r02;
  95046. py = dx * r10 + dy * r11 + dz * r12;
  95047. pz = dx * r20 + dy * r21 + dz * r22;
  95048. px = (dx = px) + c1x;
  95049. py = (dy = py) + c1y;
  95050. pz = (dz = pz) + c1z;
  95051. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  95052. if (pd <= 0) {
  95053. tx = px - pd * nx - c2x;
  95054. ty = py - pd * ny - c2y;
  95055. tz = pz - pd * nz - c2z;
  95056. len = tx * tx + ty * ty + tz * tz;
  95057. if (len > r2 * r2) {
  95058. len = r2 / OIMO.sqrt(len);
  95059. tx *= len;
  95060. ty *= len;
  95061. tz *= len;
  95062. }
  95063. px = c2x + tx;
  95064. py = c2y + ty;
  95065. pz = c2z + tz;
  95066. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  95067. }
  95068. } else {
  95069. sx = tx;
  95070. sy = ty;
  95071. sz = tz;
  95072. depth1 = nx * (sx - c2x) + ny * (sy - c2y) + nz * (sz - c2z);
  95073. sx -= depth1 * nx;
  95074. sy -= depth1 * ny;
  95075. sz -= depth1 * nz;
  95076. if (dot > 0) {
  95077. ex = tx + n1x * h1 * 2;
  95078. ey = ty + n1y * h1 * 2;
  95079. ez = tz + n1z * h1 * 2;
  95080. } else {
  95081. ex = tx - n1x * h1 * 2;
  95082. ey = ty - n1y * h1 * 2;
  95083. ez = tz - n1z * h1 * 2;
  95084. }
  95085. depth2 = nx * (ex - c2x) + ny * (ey - c2y) + nz * (ez - c2z);
  95086. ex -= depth2 * nx;
  95087. ey -= depth2 * ny;
  95088. ez -= depth2 * nz;
  95089. dx = c2x - sx;
  95090. dy = c2y - sy;
  95091. dz = c2z - sz;
  95092. tx = ex - sx;
  95093. ty = ey - sy;
  95094. tz = ez - sz;
  95095. a = dx * dx + dy * dy + dz * dz;
  95096. b = dx * tx + dy * ty + dz * tz;
  95097. e = tx * tx + ty * ty + tz * tz;
  95098. f = b * b - e * (a - r2 * r2);
  95099. if (f < 0) break;
  95100. f = OIMO.sqrt(f);
  95101. t1 = (b + f) / e;
  95102. t2 = (b - f) / e;
  95103. if (t2 < t1) {
  95104. len = t1;
  95105. t1 = t2;
  95106. t2 = len;
  95107. }
  95108. if (t2 > 1) t2 = 1;
  95109. if (t1 < 0) t1 = 0;
  95110. tx = sx + (ex - sx) * t1;
  95111. ty = sy + (ey - sy) * t1;
  95112. tz = sz + (ez - sz) * t1;
  95113. ex = sx + (ex - sx) * t2;
  95114. ey = sy + (ey - sy) * t2;
  95115. ez = sz + (ez - sz) * t2;
  95116. sx = tx;
  95117. sy = ty;
  95118. sz = tz;
  95119. len = depth1 + (depth2 - depth1) * t1;
  95120. depth2 = depth1 + (depth2 - depth1) * t2;
  95121. depth1 = len;
  95122. if (depth1 < 0) {
  95123. manifold.addPoint(sx, sy, sz, -nx, -ny, -nz, depth1, false);
  95124. }
  95125. if (depth2 < 0) {
  95126. manifold.addPoint(ex, ey, ez, -nx, -ny, -nz, depth2, false);
  95127. }
  95128. }
  95129. break;
  95130. }
  95131. };
  95132. OIMO.SphereCylinderCollisionDetector = function (flip) {
  95133. OIMO.CollisionDetector.call(this);
  95134. this.flip = flip;
  95135. };
  95136. OIMO.SphereCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  95137. OIMO.SphereCylinderCollisionDetector.prototype.constructor = OIMO.SphereCylinderCollisionDetector;
  95138. OIMO.SphereCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  95139. var s;
  95140. var c;
  95141. if (this.flip) {
  95142. s = shape2;
  95143. c = shape1;
  95144. } else {
  95145. s = shape1;
  95146. c = shape2;
  95147. }
  95148. var ps = s.position;
  95149. var psx = ps.x;
  95150. var psy = ps.y;
  95151. var psz = ps.z;
  95152. var pc = c.position;
  95153. var pcx = pc.x;
  95154. var pcy = pc.y;
  95155. var pcz = pc.z;
  95156. var dirx = c.normalDirection.x;
  95157. var diry = c.normalDirection.y;
  95158. var dirz = c.normalDirection.z;
  95159. var rads = s.radius;
  95160. var radc = c.radius;
  95161. var rad2 = rads + radc;
  95162. var halfh = c.halfHeight;
  95163. var dx = psx - pcx;
  95164. var dy = psy - pcy;
  95165. var dz = psz - pcz;
  95166. var dot = dx * dirx + dy * diry + dz * dirz;
  95167. if (dot < -halfh - rads || dot > halfh + rads) return;
  95168. var cx = pcx + dot * dirx;
  95169. var cy = pcy + dot * diry;
  95170. var cz = pcz + dot * dirz;
  95171. var d2x = psx - cx;
  95172. var d2y = psy - cy;
  95173. var d2z = psz - cz;
  95174. var len = d2x * d2x + d2y * d2y + d2z * d2z;
  95175. if (len > rad2 * rad2) return;
  95176. if (len > radc * radc) {
  95177. len = radc / OIMO.sqrt(len);
  95178. d2x *= len;
  95179. d2y *= len;
  95180. d2z *= len;
  95181. }
  95182. if (dot < -halfh) dot = -halfh;
  95183. else if (dot > halfh) dot = halfh;
  95184. cx = pcx + dot * dirx + d2x;
  95185. cy = pcy + dot * diry + d2y;
  95186. cz = pcz + dot * dirz + d2z;
  95187. dx = cx - psx;
  95188. dy = cy - psy;
  95189. dz = cz - psz;
  95190. len = dx * dx + dy * dy + dz * dz;
  95191. var invLen;
  95192. if (len > 0 && len < rads * rads) {
  95193. len = OIMO.sqrt(len);
  95194. invLen = 1 / len;
  95195. dx *= invLen;
  95196. dy *= invLen;
  95197. dz *= invLen;
  95198. ///result.addContactInfo(psx+dx*rads,psy+dy*rads,psz+dz*rads,dx,dy,dz,len-rads,s,c,0,0,false);
  95199. manifold.addPoint(psx + dx * rads, psy + dy * rads, psz + dz * rads, dx, dy, dz, len - rads, this.flip);
  95200. }
  95201. };
  95202. /**
  95203. * Class for checking collisions between 2 tetras,
  95204. * a shape that is made with 4 vertices and 4 faces
  95205. * arranged in triangles. With this algorigthm, soft
  95206. * body physics are possible and easier to implement.
  95207. * @author xprogram
  95208. */
  95209. OIMO.TetraTetraCollisionDetector = function () {
  95210. OIMO.CollisionDetector.call(this);
  95211. };
  95212. OIMO.TetraTetraCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  95213. OIMO.TetraTetraCollisionDetector.prototype.constructor = OIMO.TetraTetraCollisionDetector;
  95214. OIMO.TetraTetraCollisionDetector.prototype.detectCollision = function (tet1, tet2, manifold) {
  95215. /*
  95216. * What we are doing:
  95217. * Each tetra is represented by four 3D triangles. The only
  95218. * quick way of finding if another tetra is within the other
  95219. * tetra is to see if a single vertex is within the triangles
  95220. * of the other tetra. So, for example, a tetra is represented
  95221. * by points B, C, D and E with triangles BCD, BCE, DCE and BDE.
  95222. * There is another tetra with a vertex A which was detected for
  95223. * collision by the broadphase. Now, if the point A is between ALL
  95224. * triangles of the other tetra (BCD, BCE, etc.) then the collision
  95225. * is valid and we can pass point A to the manifold. Since the only
  95226. * points on the tetra are the 4 vertices, collision detection is
  95227. * not so complex. However, it can be time-consuming because we
  95228. * need to split the 3D triangles into three 2D triangles each for
  95229. * collision detection.
  95230. */
  95231. var i, j, vec, fs1 = tet1.faces, vs1 = tet1.verts, fs2 = tet2.faces, vs2 = tet2.verts;
  95232. var j1, j2, j3, ts = 0; // Triangle vertices `j1`, `j2` and `j3`
  95233. // fs is undeclared
  95234. var fs = fs1;
  95235. for (i = 0; i < 4; i++) {
  95236. vec = vs1[i];
  95237. for (j = 0; j < 4; j++) {
  95238. j1 = vs2[fs[i].a];
  95239. j2 = vs2[fs[i].b];
  95240. j3 = vs2[fs[i].c];
  95241. if (
  95242. tricheck(pt(vec.x, vec.y), pt(j1.x, j1.y), pt(j2.x, j2.y), pt(j3.x, j3.y)) &&
  95243. tricheck(pt(vec.x, vec.z), pt(j1.x, j1.z), pt(j2.x, j2.z), pt(j3.x, j3.z)) &&
  95244. tricheck(pt(vec.z, vec.y), pt(j1.z, j1.y), pt(j2.z, j2.y), pt(j3.z, j3.y))
  95245. )
  95246. ts++;
  95247. if (ts === 4) // Only add point if it is inside all 4 triangles
  95248. manifold.addPoint(vec);
  95249. }
  95250. }
  95251. };
  95252. // Taken from: http://jsfiddle.net/PerroAZUL/zdaY8/1/
  95253. function tricheck(p, p0, p1, p2) {
  95254. var A = 0.5 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  95255. var sg = A < 0 ? -1 : 1;
  95256. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sg;
  95257. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sg;
  95258. return s > 0 && t > 0 && (s + t) < 2 * A * sg;
  95259. }
  95260. function pt(x, y) { return { x: x, y: y }; }
  95261. /**
  95262. * An axis-aligned bounding box.
  95263. * @author saharan
  95264. * @author lo-th
  95265. */
  95266. OIMO.AABB = function (minX, maxX, minY, maxY, minZ, maxZ) {
  95267. this.elements = new OIMO_ARRAY_TYPE(6);
  95268. var te = this.elements;
  95269. te[0] = minX || 0; te[1] = minY || 0; te[2] = minZ || 0;
  95270. te[3] = maxX || 0; te[4] = maxY || 0; te[5] = maxZ || 0;
  95271. };
  95272. OIMO.AABB.prototype = {
  95273. constructor: OIMO.AABB,
  95274. set: function (minX, maxX, minY, maxY, minZ, maxZ) {
  95275. var te = this.elements;
  95276. te[0] = minX; te[3] = maxX;
  95277. te[1] = minY; te[4] = maxY;
  95278. te[2] = minZ; te[5] = maxZ;
  95279. return this;
  95280. },
  95281. intersectTest: function (aabb) {
  95282. var te = this.elements;
  95283. var ue = aabb.elements;
  95284. 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];
  95285. },
  95286. intersectTestTwo: function (aabb) {
  95287. var te = this.elements;
  95288. var ue = aabb.elements;
  95289. 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];
  95290. },
  95291. clone: function () {
  95292. return new this.constructor().fromArray(this.elements);
  95293. },
  95294. copy: function (aabb, margin) {
  95295. var m = margin || 0;
  95296. var me = aabb.elements;
  95297. this.set(me[0] - m, me[3] + m, me[1] - m, me[4] + m, me[2] - m, me[5] + m);
  95298. return this;
  95299. },
  95300. fromArray: function (array) {
  95301. this.elements.set(array);
  95302. return this;
  95303. },
  95304. // Set this AABB to the combined AABB of aabb1 and aabb2.
  95305. combine: function (aabb1, aabb2) {
  95306. var a = aabb1.elements;
  95307. var b = aabb2.elements;
  95308. var te = this.elements;
  95309. te[0] = a[0] < b[0] ? a[0] : b[0];
  95310. te[1] = a[1] < b[1] ? a[1] : b[1];
  95311. te[2] = a[2] < b[2] ? a[2] : b[2];
  95312. te[3] = a[3] > b[3] ? a[3] : b[3];
  95313. te[4] = a[4] > b[4] ? a[4] : b[4];
  95314. te[5] = a[5] > b[5] ? a[5] : b[5];
  95315. return this;
  95316. },
  95317. // Get the surface area.
  95318. surfaceArea: function () {
  95319. var te = this.elements;
  95320. var a = te[3] - te[0];
  95321. var h = te[4] - te[1];
  95322. var d = te[5] - te[2];
  95323. return 2 * (a * (h + d) + h * d);
  95324. },
  95325. // Get whether the AABB intersects with the point or not.
  95326. intersectsWithPoint: function (x, y, z) {
  95327. var te = this.elements;
  95328. return x >= te[0] && x <= te[3] && y >= te[1] && y <= te[4] && z >= te[2] && z <= te[5];
  95329. },
  95330. /**
  95331. * Set the AABB from an array
  95332. * of vertices. From THREE.
  95333. * @author mrdoob
  95334. * @author xprogram
  95335. */
  95336. setFromPoints: function (arr) {
  95337. this.makeEmpty();
  95338. for (var i = 0; i < arr.length; i++) {
  95339. this.expandByPoint(arr[i]);
  95340. }
  95341. },
  95342. makeEmpty: function () {
  95343. this.set(-Infinity, -Infinity, -Infinity, Infinity, Infinity, Infinity);
  95344. },
  95345. expandByPoint: function (pt) {
  95346. var te = this.elements;
  95347. this.set(
  95348. OIMO.min(te[0], pt.x), OIMO.min(te[1], pt.y), OIMO.min(te[2], pt.z),
  95349. OIMO.max(te[3], pt.x), OIMO.max(te[4], pt.y), OIMO.max(te[5], pt.z)
  95350. );
  95351. }
  95352. };
  95353. /**
  95354. * A proxy is used for broad-phase collecting pairs that can be colliding.
  95355. */
  95356. OIMO.Proxy = function (shape) {
  95357. // The parent shape.
  95358. this.shape = shape;
  95359. // The axis-aligned bounding box.
  95360. this.aabb = shape.aabb;
  95361. };
  95362. OIMO.Proxy.prototype = {
  95363. constructor: OIMO.Proxy,
  95364. // Update the proxy.
  95365. update: function () {
  95366. OIMO.Error("Proxy", "Inheritance error.");
  95367. }
  95368. };
  95369. /**
  95370. * A basic implementation of proxies.
  95371. * @author saharan
  95372. */
  95373. OIMO.BasicProxy = function (shape) {
  95374. OIMO.Proxy.call(this, shape);
  95375. this.id = OIMO.proxyID++;
  95376. };
  95377. OIMO.BasicProxy.prototype = Object.create(OIMO.Proxy.prototype);
  95378. OIMO.BasicProxy.prototype.constructor = OIMO.BasicProxy;
  95379. OIMO.BasicProxy.prototype.update = function () {
  95380. };
  95381. /**
  95382. * The broad-phase is used for collecting all possible pairs for collision.
  95383. */
  95384. OIMO.BroadPhase = function () {
  95385. this.types = OIMO.BR_NULL;
  95386. this.numPairChecks = 0;
  95387. this.numPairs = 0;
  95388. this.pairs = [];
  95389. };
  95390. OIMO.BroadPhase.prototype = {
  95391. constructor: OIMO.BroadPhase,
  95392. /**
  95393. * Create a new proxy.
  95394. * @param shape
  95395. * @return
  95396. */
  95397. createProxy: function (shape) {
  95398. OIMO.Error("BroadPhase", "Inheritance error.");
  95399. },
  95400. /**
  95401. * Add the proxy into the broad-phase.
  95402. * @param proxy
  95403. */
  95404. addProxy: function (proxy) {
  95405. OIMO.Error("BroadPhase", "Inheritance error.");
  95406. },
  95407. /**
  95408. * Remove the proxy from the broad-phase.
  95409. * @param proxy
  95410. */
  95411. removeProxy: function (proxy) {
  95412. OIMO.Error("BroadPhase", "Inheritance error.");
  95413. },
  95414. /**
  95415. * Returns whether the pair is available or not.
  95416. * @param s1
  95417. * @param s2
  95418. * @return
  95419. */
  95420. isAvailablePair: function (s1, s2) {
  95421. var b1 = s1.parent;
  95422. var b2 = s2.parent;
  95423. if (b1 == b2 || // same parents
  95424. (!b1.isDynamic && !b2.isDynamic) || // static or kinematic object
  95425. (s1.belongsTo & s2.collidesWith) == 0 ||
  95426. (s2.belongsTo & s1.collidesWith) == 0 // collision filtering
  95427. ) { return false; }
  95428. var js;
  95429. if (b1.numJoints < b2.numJoints) js = b1.jointLink;
  95430. else js = b2.jointLink;
  95431. while (js !== null) {
  95432. var joint = js.joint;
  95433. if (!joint.allowCollision && ((joint.body1 == b1 && joint.body2 == b2) || (joint.body1 == b2 && joint.body2 == b1))) { return false; }
  95434. js = js.next;
  95435. }
  95436. return true;
  95437. },
  95438. // Detect overlapping pairs.
  95439. detectPairs: function () {
  95440. // clear old
  95441. this.pairs = [];
  95442. this.numPairs = 0;
  95443. this.numPairChecks = 0;
  95444. this.collectPairs();
  95445. },
  95446. collectPairs: function () {
  95447. OIMO.Error("BroadPhase", "Inheritance error.");
  95448. },
  95449. addPair: function (s1, s2) {
  95450. var pair = new OIMO.Pair(s1, s2);
  95451. this.pairs.push(pair);
  95452. this.numPairs++;
  95453. }
  95454. };
  95455. /**
  95456. * A broad-phase algorithm with brute-force search.
  95457. * This always checks for all possible pairs.
  95458. */
  95459. OIMO.BruteForceBroadPhase = function () {
  95460. OIMO.BroadPhase.call(this);
  95461. this.types = OIMO.BR_BRUTE_FORCE;;
  95462. //this.numProxies=0;
  95463. ///this.maxProxies = 256;
  95464. this.proxies = [];
  95465. //this.proxies.length = 256;
  95466. };
  95467. OIMO.BruteForceBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  95468. OIMO.BruteForceBroadPhase.prototype.constructor = OIMO.BruteForceBroadPhase;
  95469. OIMO.BruteForceBroadPhase.prototype.createProxy = function (shape) {
  95470. return new OIMO.BasicProxy(shape);
  95471. };
  95472. OIMO.BruteForceBroadPhase.prototype.addProxy = function (proxy) {
  95473. /*if(this.numProxies==this.maxProxies){
  95474. //this.maxProxies<<=1;
  95475. this.maxProxies*=2;
  95476. var newProxies=[];
  95477. newProxies.length = this.maxProxies;
  95478. var i = this.numProxies;
  95479. while(i--){
  95480. //for(var i=0, l=this.numProxies;i<l;i++){
  95481. newProxies[i]=this.proxies[i];
  95482. }
  95483. this.proxies=newProxies;
  95484. }*/
  95485. //this.proxies[this.numProxies++] = proxy;
  95486. this.proxies.push(proxy);
  95487. //this.numProxies++;
  95488. };
  95489. OIMO.BruteForceBroadPhase.prototype.removeProxy = function (proxy) {
  95490. var n = this.proxies.indexOf(proxy);
  95491. if (n > -1) {
  95492. this.proxies.splice(n, 1);
  95493. //this.numProxies--;
  95494. }
  95495. /*var i = this.numProxies;
  95496. while(i--){
  95497. //for(var i=0, l=this.numProxies;i<l;i++){
  95498. if(this.proxies[i] == proxy){
  95499. this.proxies[i] = this.proxies[--this.numProxies];
  95500. this.proxies[this.numProxies] = null;
  95501. return;
  95502. }
  95503. }*/
  95504. };
  95505. OIMO.BruteForceBroadPhase.prototype.collectPairs = function () {
  95506. var i = 0, j, p1, p2;
  95507. var px = this.proxies;
  95508. var l = px.length;//this.numProxies;
  95509. //var ar1 = [];
  95510. //var ar2 = [];
  95511. //for( i = px.length ; i-- ; ar1[ i ] = px[ i ] ){};
  95512. //for( i = px.length ; i-- ; ar2[ i ] = px[ i ] ){};
  95513. //var ar1 = JSON.parse(JSON.stringify(this.proxies))
  95514. //var ar2 = JSON.parse(JSON.stringify(this.proxies))
  95515. this.numPairChecks = l * (l - 1) >> 1;
  95516. //this.numPairChecks=this.numProxies*(this.numProxies-1)*0.5;
  95517. while (i < l) {
  95518. p1 = px[i++];
  95519. j = i + 1;
  95520. while (j < l) {
  95521. p2 = px[j++];
  95522. if (p1.aabb.intersectTest(p2.aabb) || !this.isAvailablePair(p1.shape, p2.shape)) continue;
  95523. this.addPair(p1.shape, p2.shape);
  95524. }
  95525. }
  95526. };
  95527. /**
  95528. * A pair of shapes that may collide.
  95529. * @author saharan
  95530. */
  95531. OIMO.Pair = function (s1, s2) {
  95532. // The first shape.
  95533. this.shape1 = s1 || null;
  95534. // The second shape.
  95535. this.shape2 = s2 || null;
  95536. };
  95537. /**
  95538. * A projection axis for sweep and prune broad-phase.
  95539. * @author saharan
  95540. */
  95541. OIMO.SAPAxis = function () {
  95542. this.numElements = 0;
  95543. this.bufferSize = 256;
  95544. this.elements = [];
  95545. this.elements.length = this.bufferSize;
  95546. this.stack = new OIMO_ARRAY_TYPE(64);
  95547. };
  95548. OIMO.SAPAxis.prototype = {
  95549. constructor: OIMO.SAPAxis,
  95550. addElements: function (min, max) {
  95551. if (this.numElements + 2 >= this.bufferSize) {
  95552. //this.bufferSize<<=1;
  95553. this.bufferSize *= 2;
  95554. var newElements = [];
  95555. var i = this.numElements;
  95556. while (i--) {
  95557. //for(var i=0, l=this.numElements; i<l; i++){
  95558. newElements[i] = this.elements[i];
  95559. }
  95560. }
  95561. this.elements[this.numElements++] = min;
  95562. this.elements[this.numElements++] = max;
  95563. },
  95564. removeElements: function (min, max) {
  95565. var minIndex = -1;
  95566. var maxIndex = -1;
  95567. for (var i = 0, l = this.numElements; i < l; i++) {
  95568. var e = this.elements[i];
  95569. if (e == min || e == max) {
  95570. if (minIndex == -1) {
  95571. minIndex = i;
  95572. } else {
  95573. maxIndex = i;
  95574. break;
  95575. }
  95576. }
  95577. }
  95578. for (i = minIndex + 1, l = maxIndex; i < l; i++) {
  95579. this.elements[i - 1] = this.elements[i];
  95580. }
  95581. for (i = maxIndex + 1, l = this.numElements; i < l; i++) {
  95582. this.elements[i - 2] = this.elements[i];
  95583. }
  95584. this.elements[--this.numElements] = null;
  95585. this.elements[--this.numElements] = null;
  95586. },
  95587. sort: function () {
  95588. var count = 0;
  95589. var threshold = 1;
  95590. while ((this.numElements >> threshold) != 0) threshold++;
  95591. threshold = threshold * this.numElements >> 2;
  95592. count = 0;
  95593. var giveup = false;
  95594. var elements = this.elements;
  95595. for (var i = 1, l = this.numElements; i < l; i++) { // try insertion sort
  95596. var tmp = elements[i];
  95597. var pivot = tmp.value;
  95598. var tmp2 = elements[i - 1];
  95599. if (tmp2.value > pivot) {
  95600. var j = i;
  95601. do {
  95602. elements[j] = tmp2;
  95603. if (--j == 0) break;
  95604. tmp2 = elements[j - 1];
  95605. } while (tmp2.value > pivot);
  95606. elements[j] = tmp;
  95607. count += i - j;
  95608. if (count > threshold) {
  95609. giveup = true; // stop and use quick sort
  95610. break;
  95611. }
  95612. }
  95613. }
  95614. if (!giveup) return;
  95615. count = 2; var stack = this.stack;
  95616. stack[0] = 0;
  95617. stack[1] = this.numElements - 1;
  95618. while (count > 0) {
  95619. var right = stack[--count];
  95620. var left = stack[--count];
  95621. var diff = right - left;
  95622. if (diff > 16) { // quick sort
  95623. //var mid=left+(diff>>1);
  95624. var mid = left + (OIMO.floor(diff * 0.5));
  95625. tmp = elements[mid];
  95626. elements[mid] = elements[right];
  95627. elements[right] = tmp;
  95628. pivot = tmp.value;
  95629. i = left - 1;
  95630. j = right;
  95631. while (true) {
  95632. var ei;
  95633. var ej;
  95634. do { ei = elements[++i]; } while (ei.value < pivot);
  95635. do { ej = elements[--j]; } while (pivot < ej.value && j != left);
  95636. if (i >= j) break;
  95637. elements[i] = ej;
  95638. elements[j] = ei;
  95639. }
  95640. elements[right] = elements[i];
  95641. elements[i] = tmp;
  95642. if (i - left > right - i) {
  95643. stack[count++] = left;
  95644. stack[count++] = i - 1;
  95645. stack[count++] = i + 1;
  95646. stack[count++] = right;
  95647. } else {
  95648. stack[count++] = i + 1;
  95649. stack[count++] = right;
  95650. stack[count++] = left;
  95651. stack[count++] = i - 1;
  95652. }
  95653. } else {
  95654. for (i = left + 1; i <= right; i++) {
  95655. tmp = elements[i];
  95656. pivot = tmp.value;
  95657. tmp2 = elements[i - 1];
  95658. if (tmp2.value > pivot) {
  95659. j = i;
  95660. do {
  95661. elements[j] = tmp2;
  95662. if (--j == 0) break;
  95663. tmp2 = elements[j - 1];
  95664. } while (tmp2.value > pivot);
  95665. elements[j] = tmp;
  95666. }
  95667. }
  95668. }
  95669. }
  95670. },
  95671. calculateTestCount: function () {
  95672. var num = 1;
  95673. var sum = 0;
  95674. for (var i = 1, l = this.numElements; i < l; i++) {
  95675. if (this.elements[i].max) {
  95676. num--;
  95677. } else {
  95678. sum += num;
  95679. num++;
  95680. }
  95681. }
  95682. return sum;
  95683. }
  95684. }
  95685. /**
  95686. * A broad-phase collision detection algorithm using sweep and prune.
  95687. * @author saharan
  95688. * @author lo-th
  95689. */
  95690. OIMO.SAPBroadPhase = function () {
  95691. OIMO.BroadPhase.call(this);
  95692. this.types = OIMO.BR_SWEEP_AND_PRUNE;
  95693. this.numElementsD = 0;
  95694. this.numElementsS = 0;
  95695. // dynamic proxies
  95696. this.axesD = [
  95697. new OIMO.SAPAxis(),
  95698. new OIMO.SAPAxis(),
  95699. new OIMO.SAPAxis()
  95700. ];
  95701. // static or sleeping proxies
  95702. this.axesS = [
  95703. new OIMO.SAPAxis(),
  95704. new OIMO.SAPAxis(),
  95705. new OIMO.SAPAxis()
  95706. ];
  95707. this.index1 = 0;
  95708. this.index2 = 1;
  95709. };
  95710. OIMO.SAPBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  95711. OIMO.SAPBroadPhase.prototype.constructor = OIMO.SAPBroadPhase;
  95712. OIMO.SAPBroadPhase.prototype.createProxy = function (shape) {
  95713. return new OIMO.SAPProxy(this, shape);
  95714. };
  95715. OIMO.SAPBroadPhase.prototype.addProxy = function (proxy) {
  95716. var p = proxy;
  95717. if (p.isDynamic()) {
  95718. this.axesD[0].addElements(p.min[0], p.max[0]);
  95719. this.axesD[1].addElements(p.min[1], p.max[1]);
  95720. this.axesD[2].addElements(p.min[2], p.max[2]);
  95721. p.belongsTo = 1;
  95722. this.numElementsD += 2;
  95723. } else {
  95724. this.axesS[0].addElements(p.min[0], p.max[0]);
  95725. this.axesS[1].addElements(p.min[1], p.max[1]);
  95726. this.axesS[2].addElements(p.min[2], p.max[2]);
  95727. p.belongsTo = 2;
  95728. this.numElementsS += 2;
  95729. }
  95730. };
  95731. OIMO.SAPBroadPhase.prototype.removeProxy = function (proxy) {
  95732. var p = proxy;
  95733. if (p.belongsTo == 0) return;
  95734. /*else if ( p.belongsTo == 1 ) {
  95735. this.axesD[0].removeElements( p.min[0], p.max[0] );
  95736. this.axesD[1].removeElements( p.min[1], p.max[1] );
  95737. this.axesD[2].removeElements( p.min[2], p.max[2] );
  95738. this.numElementsD -= 2;
  95739. } else if ( p.belongsTo == 2 ) {
  95740. this.axesS[0].removeElements( p.min[0], p.max[0] );
  95741. this.axesS[1].removeElements( p.min[1], p.max[1] );
  95742. this.axesS[2].removeElements( p.min[2], p.max[2] );
  95743. this.numElementsS -= 2;
  95744. }*/
  95745. switch (p.belongsTo) {
  95746. case 1:
  95747. this.axesD[0].removeElements(p.min[0], p.max[0]);
  95748. this.axesD[1].removeElements(p.min[1], p.max[1]);
  95749. this.axesD[2].removeElements(p.min[2], p.max[2]);
  95750. this.numElementsD -= 2;
  95751. break;
  95752. case 2:
  95753. this.axesS[0].removeElements(p.min[0], p.max[0]);
  95754. this.axesS[1].removeElements(p.min[1], p.max[1]);
  95755. this.axesS[2].removeElements(p.min[2], p.max[2]);
  95756. this.numElementsS -= 2;
  95757. break;
  95758. }
  95759. p.belongsTo = 0;
  95760. };
  95761. OIMO.SAPBroadPhase.prototype.collectPairs = function () {
  95762. if (this.numElementsD == 0) return;
  95763. var axis1 = this.axesD[this.index1];
  95764. var axis2 = this.axesD[this.index2];
  95765. axis1.sort();
  95766. axis2.sort();
  95767. var count1 = axis1.calculateTestCount();
  95768. var count2 = axis2.calculateTestCount();
  95769. var elementsD;
  95770. var elementsS;
  95771. if (count1 <= count2) {// select the best axis
  95772. axis2 = this.axesS[this.index1];
  95773. axis2.sort();
  95774. elementsD = axis1.elements;
  95775. elementsS = axis2.elements;
  95776. } else {
  95777. axis1 = this.axesS[this.index2];
  95778. axis1.sort();
  95779. elementsD = axis2.elements;
  95780. elementsS = axis1.elements;
  95781. this.index1 ^= this.index2;
  95782. this.index2 ^= this.index1;
  95783. this.index1 ^= this.index2;
  95784. }
  95785. var activeD;
  95786. var activeS;
  95787. var p = 0;
  95788. var q = 0;
  95789. while (p < this.numElementsD) {
  95790. var e1;
  95791. var dyn;
  95792. if (q == this.numElementsS) {
  95793. e1 = elementsD[p];
  95794. dyn = true;
  95795. p++;
  95796. } else {
  95797. var d = elementsD[p];
  95798. var s = elementsS[q];
  95799. if (d.value < s.value) {
  95800. e1 = d;
  95801. dyn = true;
  95802. p++;
  95803. } else {
  95804. e1 = s;
  95805. dyn = false;
  95806. q++;
  95807. }
  95808. }
  95809. if (!e1.max) {
  95810. var s1 = e1.proxy.shape;
  95811. var min1 = e1.min1.value;
  95812. var max1 = e1.max1.value;
  95813. var min2 = e1.min2.value;
  95814. var max2 = e1.max2.value;
  95815. for (var e2 = activeD; e2 != null; e2 = e2.pair) {// test for dynamic
  95816. var s2 = e2.proxy.shape;
  95817. this.numPairChecks++;
  95818. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  95819. this.addPair(s1, s2);
  95820. }
  95821. if (dyn) {
  95822. for (e2 = activeS; e2 != null; e2 = e2.pair) {// test for static
  95823. s2 = e2.proxy.shape;
  95824. this.numPairChecks++;
  95825. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  95826. this.addPair(s1, s2);
  95827. }
  95828. e1.pair = activeD;
  95829. activeD = e1;
  95830. } else {
  95831. e1.pair = activeS;
  95832. activeS = e1;
  95833. }
  95834. } else {
  95835. var min = e1.pair;
  95836. if (dyn) {
  95837. if (min == activeD) {
  95838. activeD = activeD.pair;
  95839. continue;
  95840. } else {
  95841. e1 = activeD;
  95842. }
  95843. } else {
  95844. if (min == activeS) {
  95845. activeS = activeS.pair;
  95846. continue;
  95847. } else {
  95848. e1 = activeS;
  95849. }
  95850. }
  95851. do {
  95852. e2 = e1.pair;
  95853. if (e2 == min) {
  95854. e1.pair = e2.pair;
  95855. break;
  95856. }
  95857. e1 = e2;
  95858. } while (e1 != null);
  95859. }
  95860. }
  95861. this.index2 = (this.index1 | this.index2) ^ 3;
  95862. };
  95863. /**
  95864. * An element of proxies.
  95865. * @author saharan
  95866. */
  95867. OIMO.SAPElement = function (proxy, max) {
  95868. // The parent proxy
  95869. this.proxy = proxy;
  95870. // The pair element.
  95871. this.pair = null;
  95872. // The minimum element on other axis.
  95873. this.min1 = null;
  95874. // The maximum element on other axis.
  95875. this.max1 = null;
  95876. // The minimum element on other axis.
  95877. this.min2 = null;
  95878. // The maximum element on other axis.
  95879. this.max2 = null;
  95880. // Whether the element has maximum value or not.
  95881. this.max = max;
  95882. // The value of the element.
  95883. this.value = 0;
  95884. };
  95885. /**
  95886. * A proxy for sweep and prune broad-phase.
  95887. * @author saharan
  95888. * @author lo-th
  95889. */
  95890. OIMO.SAPProxy = function (sap, shape) {
  95891. OIMO.Proxy.call(this, shape);
  95892. // Type of the axis to which the proxy belongs to. [0:none, 1:dynamic, 2:static]
  95893. this.belongsTo = 0;
  95894. // The maximum elements on each axis.
  95895. this.max = [];
  95896. // The minimum elements on each axis.
  95897. this.min = [];
  95898. this.sap = sap;
  95899. this.min[0] = new OIMO.SAPElement(this, false);
  95900. this.max[0] = new OIMO.SAPElement(this, true);
  95901. this.min[1] = new OIMO.SAPElement(this, false);
  95902. this.max[1] = new OIMO.SAPElement(this, true);
  95903. this.min[2] = new OIMO.SAPElement(this, false);
  95904. this.max[2] = new OIMO.SAPElement(this, true);
  95905. this.max[0].pair = this.min[0];
  95906. this.max[1].pair = this.min[1];
  95907. this.max[2].pair = this.min[2];
  95908. this.min[0].min1 = this.min[1];
  95909. this.min[0].max1 = this.max[1];
  95910. this.min[0].min2 = this.min[2];
  95911. this.min[0].max2 = this.max[2];
  95912. this.min[1].min1 = this.min[0];
  95913. this.min[1].max1 = this.max[0];
  95914. this.min[1].min2 = this.min[2];
  95915. this.min[1].max2 = this.max[2];
  95916. this.min[2].min1 = this.min[0];
  95917. this.min[2].max1 = this.max[0];
  95918. this.min[2].min2 = this.min[1];
  95919. this.min[2].max2 = this.max[1];
  95920. };
  95921. OIMO.SAPProxy.prototype = Object.create(OIMO.Proxy.prototype);
  95922. OIMO.SAPProxy.prototype.constructor = OIMO.SAPProxy;
  95923. // Returns whether the proxy is dynamic or not.
  95924. OIMO.SAPProxy.prototype.isDynamic = function () {
  95925. var body = this.shape.parent;
  95926. return body.isDynamic && !body.sleeping;
  95927. };
  95928. OIMO.SAPProxy.prototype.update = function () {
  95929. var te = this.aabb.elements;
  95930. this.min[0].value = te[0];
  95931. this.min[1].value = te[1];
  95932. this.min[2].value = te[2];
  95933. this.max[0].value = te[3];
  95934. this.max[1].value = te[4];
  95935. this.max[2].value = te[5];
  95936. if (this.belongsTo == 1 && !this.isDynamic() || this.belongsTo == 2 && this.isDynamic()) {
  95937. this.sap.removeProxy(this);
  95938. this.sap.addProxy(this);
  95939. }
  95940. };
  95941. /**
  95942. * A dynamic bounding volume tree for the broad-phase algorithm.
  95943. * @author saharan
  95944. * @author lo-th
  95945. */
  95946. OIMO.DBVT = function () {
  95947. // The root of the tree.
  95948. this.root = null;
  95949. this.freeNodes = [];
  95950. this.freeNodes.length = 16384;
  95951. this.numFreeNodes = 0;
  95952. this.aabb = new OIMO.AABB();
  95953. };
  95954. OIMO.DBVT.prototype = {
  95955. constructor: OIMO.DBVT,
  95956. /**
  95957. * Move a leaf.
  95958. * @param leaf
  95959. */
  95960. moveLeaf: function (leaf) {
  95961. this.deleteLeaf(leaf);
  95962. this.insertLeaf(leaf);
  95963. },
  95964. /**
  95965. * Insert a leaf to the tree.
  95966. * @param node
  95967. */
  95968. insertLeaf: function (leaf) {
  95969. if (this.root == null) {
  95970. this.root = leaf;
  95971. return;
  95972. }
  95973. var lb = leaf.aabb;
  95974. var sibling = this.root;
  95975. var oldArea;
  95976. var newArea;
  95977. while (sibling.proxy == null) { // descend the node to search the best pair
  95978. var c1 = sibling.child1;
  95979. var c2 = sibling.child2;
  95980. var b = sibling.aabb;
  95981. var c1b = c1.aabb;
  95982. var c2b = c2.aabb;
  95983. oldArea = b.surfaceArea();
  95984. this.aabb.combine(lb, b);
  95985. newArea = this.aabb.surfaceArea();
  95986. var creatingCost = newArea * 2;
  95987. var incrementalCost = (newArea - oldArea) * 2; // cost of creating a new pair with the node
  95988. var discendingCost1 = incrementalCost;
  95989. this.aabb.combine(lb, c1b);
  95990. if (c1.proxy != null) {
  95991. // leaf cost = area(combined aabb)
  95992. discendingCost1 += this.aabb.surfaceArea();
  95993. } else {
  95994. // node cost = area(combined aabb) - area(old aabb)
  95995. discendingCost1 += this.aabb.surfaceArea() - c1b.surfaceArea();
  95996. }
  95997. var discendingCost2 = incrementalCost;
  95998. this.aabb.combine(lb, c2b);
  95999. if (c2.proxy != null) {
  96000. // leaf cost = area(combined aabb)
  96001. discendingCost2 += this.aabb.surfaceArea();
  96002. } else {
  96003. // node cost = area(combined aabb) - area(old aabb)
  96004. discendingCost2 += this.aabb.surfaceArea() - c2b.surfaceArea();
  96005. }
  96006. if (discendingCost1 < discendingCost2) {
  96007. if (creatingCost < discendingCost1) {
  96008. break;// stop descending
  96009. } else {
  96010. sibling = c1;// descend into first child
  96011. }
  96012. } else {
  96013. if (creatingCost < discendingCost2) {
  96014. break;// stop descending
  96015. } else {
  96016. sibling = c2;// descend into second child
  96017. }
  96018. }
  96019. }
  96020. var oldParent = sibling.parent;
  96021. var newParent;
  96022. if (this.numFreeNodes > 0) {
  96023. newParent = this.freeNodes[--this.numFreeNodes];
  96024. } else {
  96025. newParent = new OIMO.DBVTNode();
  96026. }
  96027. newParent.parent = oldParent;
  96028. newParent.child1 = leaf;
  96029. newParent.child2 = sibling;
  96030. newParent.aabb.combine(leaf.aabb, sibling.aabb);
  96031. newParent.height = sibling.height + 1;
  96032. sibling.parent = newParent;
  96033. leaf.parent = newParent;
  96034. if (sibling == this.root) {
  96035. // replace root
  96036. this.root = newParent;
  96037. } else {
  96038. // replace child
  96039. if (oldParent.child1 == sibling) {
  96040. oldParent.child1 = newParent;
  96041. } else {
  96042. oldParent.child2 = newParent;
  96043. }
  96044. }
  96045. // update whole tree
  96046. do {
  96047. newParent = this.balance(newParent);
  96048. this.fix(newParent);
  96049. newParent = newParent.parent;
  96050. } while (newParent != null);
  96051. },
  96052. getBalance: function (node) {
  96053. if (node.proxy != null) return 0;
  96054. return node.child1.height - node.child2.height;
  96055. },
  96056. /*print:function(node,indent,text){
  96057. var hasChild=node.proxy==null;
  96058. if(hasChild)text=this.print(node.child1,indent+1,text);
  96059. for(var i=indent*2;i>=0;i--){
  96060. text+=" ";
  96061. }
  96062. text+=(hasChild?this.getBalance(node):"["+node.proxy.aabb.minX+"]")+"\n";
  96063. if(hasChild)text=this.print(node.child2,indent+1,text);
  96064. return text;
  96065. },*/
  96066. /**
  96067. * Delete a leaf from the tree.
  96068. * @param node
  96069. */
  96070. deleteLeaf: function (leaf) {
  96071. if (leaf == this.root) {
  96072. this.root = null;
  96073. return;
  96074. }
  96075. var parent = leaf.parent;
  96076. var sibling;
  96077. if (parent.child1 == leaf) {
  96078. sibling = parent.child2;
  96079. } else {
  96080. sibling = parent.child1;
  96081. }
  96082. if (parent == this.root) {
  96083. this.root = sibling;
  96084. sibling.parent = null;
  96085. return;
  96086. }
  96087. var grandParent = parent.parent;
  96088. sibling.parent = grandParent;
  96089. if (grandParent.child1 == parent) {
  96090. grandParent.child1 = sibling;
  96091. } else {
  96092. grandParent.child2 = sibling;
  96093. }
  96094. if (this.numFreeNodes < 16384) {
  96095. this.freeNodes[this.numFreeNodes++] = parent;
  96096. }
  96097. do {
  96098. grandParent = this.balance(grandParent);
  96099. this.fix(grandParent);
  96100. grandParent = grandParent.parent;
  96101. } while (grandParent != null);
  96102. },
  96103. balance: function (node) {
  96104. var nh = node.height;
  96105. if (nh < 2) {
  96106. return node;
  96107. }
  96108. var p = node.parent;
  96109. var l = node.child1;
  96110. var r = node.child2;
  96111. var lh = l.height;
  96112. var rh = r.height;
  96113. var balance = lh - rh;
  96114. var t;// for bit operation
  96115. // [ N ]
  96116. // / \
  96117. // [ L ] [ R ]
  96118. // / \ / \
  96119. // [L-L] [L-R] [R-L] [R-R]
  96120. // Is the tree balanced?
  96121. if (balance > 1) {
  96122. var ll = l.child1;
  96123. var lr = l.child2;
  96124. var llh = ll.height;
  96125. var lrh = lr.height;
  96126. // Is L-L higher than L-R?
  96127. if (llh > lrh) {
  96128. // set N to L-R
  96129. l.child2 = node;
  96130. node.parent = l;
  96131. // [ L ]
  96132. // / \
  96133. // [L-L] [ N ]
  96134. // / \ / \
  96135. // [...] [...] [ L ] [ R ]
  96136. // set L-R
  96137. node.child1 = lr;
  96138. lr.parent = node;
  96139. // [ L ]
  96140. // / \
  96141. // [L-L] [ N ]
  96142. // / \ / \
  96143. // [...] [...] [L-R] [ R ]
  96144. // fix bounds and heights
  96145. node.aabb.combine(lr.aabb, r.aabb);
  96146. t = lrh - rh;
  96147. node.height = lrh - (t & t >> 31) + 1;
  96148. l.aabb.combine(ll.aabb, node.aabb);
  96149. t = llh - nh;
  96150. l.height = llh - (t & t >> 31) + 1;
  96151. } else {
  96152. // set N to L-L
  96153. l.child1 = node;
  96154. node.parent = l;
  96155. // [ L ]
  96156. // / \
  96157. // [ N ] [L-R]
  96158. // / \ / \
  96159. // [ L ] [ R ] [...] [...]
  96160. // set L-L
  96161. node.child1 = ll;
  96162. ll.parent = node;
  96163. // [ L ]
  96164. // / \
  96165. // [ N ] [L-R]
  96166. // / \ / \
  96167. // [L-L] [ R ] [...] [...]
  96168. // fix bounds and heights
  96169. node.aabb.combine(ll.aabb, r.aabb);
  96170. t = llh - rh;
  96171. node.height = llh - (t & t >> 31) + 1;
  96172. l.aabb.combine(node.aabb, lr.aabb);
  96173. t = nh - lrh;
  96174. l.height = nh - (t & t >> 31) + 1;
  96175. }
  96176. // set new parent of L
  96177. if (p != null) {
  96178. if (p.child1 == node) {
  96179. p.child1 = l;
  96180. } else {
  96181. p.child2 = l;
  96182. }
  96183. } else {
  96184. this.root = l;
  96185. }
  96186. l.parent = p;
  96187. return l;
  96188. } else if (balance < -1) {
  96189. var rl = r.child1;
  96190. var rr = r.child2;
  96191. var rlh = rl.height;
  96192. var rrh = rr.height;
  96193. // Is R-L higher than R-R?
  96194. if (rlh > rrh) {
  96195. // set N to R-R
  96196. r.child2 = node;
  96197. node.parent = r;
  96198. // [ R ]
  96199. // / \
  96200. // [R-L] [ N ]
  96201. // / \ / \
  96202. // [...] [...] [ L ] [ R ]
  96203. // set R-R
  96204. node.child2 = rr;
  96205. rr.parent = node;
  96206. // [ R ]
  96207. // / \
  96208. // [R-L] [ N ]
  96209. // / \ / \
  96210. // [...] [...] [ L ] [R-R]
  96211. // fix bounds and heights
  96212. node.aabb.combine(l.aabb, rr.aabb);
  96213. t = lh - rrh;
  96214. node.height = lh - (t & t >> 31) + 1;
  96215. r.aabb.combine(rl.aabb, node.aabb);
  96216. t = rlh - nh;
  96217. r.height = rlh - (t & t >> 31) + 1;
  96218. } else {
  96219. // set N to R-L
  96220. r.child1 = node;
  96221. node.parent = r;
  96222. // [ R ]
  96223. // / \
  96224. // [ N ] [R-R]
  96225. // / \ / \
  96226. // [ L ] [ R ] [...] [...]
  96227. // set R-L
  96228. node.child2 = rl;
  96229. rl.parent = node;
  96230. // [ R ]
  96231. // / \
  96232. // [ N ] [R-R]
  96233. // / \ / \
  96234. // [ L ] [R-L] [...] [...]
  96235. // fix bounds and heights
  96236. node.aabb.combine(l.aabb, rl.aabb);
  96237. t = lh - rlh;
  96238. node.height = lh - (t & t >> 31) + 1;
  96239. r.aabb.combine(node.aabb, rr.aabb);
  96240. t = nh - rrh;
  96241. r.height = nh - (t & t >> 31) + 1;
  96242. }
  96243. // set new parent of R
  96244. if (p != null) {
  96245. if (p.child1 == node) {
  96246. p.child1 = r;
  96247. } else {
  96248. p.child2 = r;
  96249. }
  96250. } else {
  96251. this.root = r;
  96252. }
  96253. r.parent = p;
  96254. return r;
  96255. }
  96256. return node;
  96257. },
  96258. fix: function (node) {
  96259. var c1 = node.child1;
  96260. var c2 = node.child2;
  96261. node.aabb.combine(c1.aabb, c2.aabb);
  96262. //var h1 = c1.height;
  96263. //var h2 = c2.height;
  96264. node.height = c1.height < c2.height ? c2.height + 1 : c1.height + 1;
  96265. /*if( h1 < h2 ) {
  96266. node.height = h2+1;
  96267. }else{
  96268. node.height = h1+1;
  96269. }*/
  96270. }
  96271. }
  96272. /**
  96273. * A broad-phase algorithm using dynamic bounding volume tree.
  96274. * @author saharan
  96275. * @author lo-th
  96276. */
  96277. OIMO.DBVTBroadPhase = function () {
  96278. OIMO.BroadPhase.call(this);
  96279. this.types = OIMO.BR_BOUNDING_VOLUME_TREE;
  96280. this.tree = new OIMO.DBVT();
  96281. this.stack = [];
  96282. this.leaves = [];
  96283. this.numLeaves = 0;
  96284. };
  96285. OIMO.DBVTBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  96286. OIMO.DBVTBroadPhase.prototype.constructor = OIMO.DBVTBroadPhase;
  96287. OIMO.DBVTBroadPhase.prototype.createProxy = function (shape) {
  96288. return new OIMO.DBVTProxy(shape);
  96289. };
  96290. OIMO.DBVTBroadPhase.prototype.addProxy = function (proxy) {
  96291. this.tree.insertLeaf(proxy.leaf);
  96292. this.leaves.push(proxy.leaf);
  96293. this.numLeaves++;
  96294. };
  96295. OIMO.DBVTBroadPhase.prototype.removeProxy = function (proxy) {
  96296. this.tree.deleteLeaf(proxy.leaf);
  96297. var n = this.leaves.indexOf(proxy.leaf);
  96298. if (n > -1) {
  96299. this.leaves.splice(n, 1);
  96300. this.numLeaves--;
  96301. }
  96302. };
  96303. OIMO.DBVTBroadPhase.prototype.collectPairs = function () {
  96304. if (this.numLeaves < 2) return;
  96305. var leaf, margin = 0.1, i = this.numLeaves;
  96306. while (i--) {
  96307. leaf = this.leaves[i];
  96308. if (leaf.proxy.aabb.intersectTestTwo(leaf.aabb)) {
  96309. leaf.aabb.copy(leaf.proxy.aabb, margin);
  96310. this.tree.deleteLeaf(leaf);
  96311. this.tree.insertLeaf(leaf);
  96312. this.collide(leaf, this.tree.root);
  96313. }
  96314. }
  96315. };
  96316. OIMO.DBVTBroadPhase.prototype.collide = function (node1, node2) {
  96317. var stackCount = 2;
  96318. var s1, s2, n1, n2, l1, l2;
  96319. this.stack[0] = node1;
  96320. this.stack[1] = node2;
  96321. while (stackCount > 0) {
  96322. n1 = this.stack[--stackCount];
  96323. n2 = this.stack[--stackCount];
  96324. l1 = n1.proxy != null;
  96325. l2 = n2.proxy != null;
  96326. this.numPairChecks++;
  96327. if (l1 && l2) {
  96328. s1 = n1.proxy.shape;
  96329. s2 = n2.proxy.shape;
  96330. if (s1 == s2 || s1.aabb.intersectTest(s2.aabb) || !this.isAvailablePair(s1, s2)) continue;
  96331. this.addPair(s1, s2);
  96332. } else {
  96333. if (n1.aabb.intersectTest(n2.aabb)) continue;
  96334. /*if(stackCount+4>=this.maxStack){// expand the stack
  96335. //this.maxStack<<=1;
  96336. this.maxStack*=2;
  96337. var newStack = [];// vector
  96338. newStack.length = this.maxStack;
  96339. for(var i=0;i<stackCount;i++){
  96340. newStack[i] = this.stack[i];
  96341. }
  96342. this.stack = newStack;
  96343. }*/
  96344. if (l2 || !l1 && (n1.aabb.surfaceArea() > n2.aabb.surfaceArea())) {
  96345. this.stack[stackCount++] = n1.child1;
  96346. this.stack[stackCount++] = n2;
  96347. this.stack[stackCount++] = n1.child2;
  96348. this.stack[stackCount++] = n2;
  96349. } else {
  96350. this.stack[stackCount++] = n1;
  96351. this.stack[stackCount++] = n2.child1;
  96352. this.stack[stackCount++] = n1;
  96353. this.stack[stackCount++] = n2.child2;
  96354. }
  96355. }
  96356. }
  96357. };
  96358. /**
  96359. * A node of the dynamic bounding volume tree.
  96360. * @author saharan
  96361. */
  96362. OIMO.DBVTNode = function () {
  96363. // The first child node of this node.
  96364. this.child1 = null;
  96365. // The second child node of this node.
  96366. this.child2 = null;
  96367. // The parent node of this tree.
  96368. this.parent = null;
  96369. // The proxy of this node. This has no value if this node is not leaf.
  96370. this.proxy = null;
  96371. // The maximum distance from leaf nodes.
  96372. this.height = 0;
  96373. // The AABB of this node.
  96374. this.aabb = new OIMO.AABB();
  96375. };
  96376. /**
  96377. * A proxy for dynamic bounding volume tree broad-phase.
  96378. * @author saharan
  96379. */
  96380. OIMO.DBVTProxy = function (shape) {
  96381. OIMO.Proxy.call(this, shape);
  96382. // The leaf of the proxy.
  96383. this.leaf = new OIMO.DBVTNode();
  96384. this.leaf.proxy = this;
  96385. };
  96386. OIMO.DBVTProxy.prototype = Object.create(OIMO.Proxy.prototype);
  96387. OIMO.DBVTProxy.prototype.constructor = OIMO.DBVTProxy;
  96388. OIMO.DBVTProxy.prototype.update = function () {
  96389. };
  96390. OIMO.World.prototype.add = function (obj) {
  96391. obj = obj || {};
  96392. var type = obj.type || "box";
  96393. if (typeof type === 'string') type = [type];// single shape
  96394. if (type[0].substring(0, 5) == 'joint') { // is joint
  96395. if (type[0] === 'joint') type[0] = 'jointHinge';
  96396. var axe1 = obj.axe1 || [1, 0, 0];
  96397. var axe2 = obj.axe2 || [1, 0, 0];
  96398. var pos1 = obj.pos1 || [0, 0, 0];
  96399. var pos2 = obj.pos2 || [0, 0, 0];
  96400. pos1 = pos1.map(function (x) { return x * OIMO.INV_SCALE; });
  96401. pos2 = pos2.map(function (x) { return x * OIMO.INV_SCALE; });
  96402. var min, max;
  96403. if (type[0] === "jointDistance") {
  96404. min = obj.min || 0;
  96405. max = obj.max || 10;
  96406. min = min * OIMO.INV_SCALE;
  96407. max = max * OIMO.INV_SCALE;
  96408. } else {
  96409. min = obj.min || 57.29578;
  96410. max = obj.max || 0;
  96411. min = min * OIMO.degtorad;
  96412. max = max * OIMO.degtorad;
  96413. }
  96414. var limit = obj.limit || null;
  96415. var spring = obj.spring || null;
  96416. var motor = obj.motor || null;
  96417. // joint setting
  96418. var jc = new OIMO.JointConfig();
  96419. jc.allowCollision = obj.collision || false;;
  96420. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  96421. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  96422. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  96423. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  96424. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = this.getByName(obj.body1);
  96425. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = this.getByName(obj.body2);
  96426. jc.body1 = obj.body1;
  96427. jc.body2 = obj.body2;
  96428. var joint;
  96429. switch (type[0]) {
  96430. case "jointDistance": joint = new OIMO.DistanceJoint(jc, min, max);
  96431. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);
  96432. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  96433. break;
  96434. case "jointHinge": joint = new OIMO.HingeJoint(jc, min, max);
  96435. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  96436. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  96437. break;
  96438. case "jointPrisme": joint = new OIMO.PrismaticJoint(jc, min, max); break;
  96439. case "jointSlide": joint = new OIMO.SliderJoint(jc, min, max); break;
  96440. case "jointBall": joint = new OIMO.BallAndSocketJoint(jc); break;
  96441. case "jointWheel": joint = new OIMO.WheelJoint(jc);
  96442. if (limit !== null) joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  96443. if (spring !== null) joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  96444. if (motor !== null) joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  96445. break;
  96446. }
  96447. joint.name = obj.name || '';
  96448. // finaly add to physics world
  96449. this.addJoint(joint);
  96450. return joint;
  96451. } else { // is body
  96452. // I'm dynamique or not
  96453. var move = obj.move || false;
  96454. // I can sleep or not
  96455. var noSleep = obj.noSleep || false;
  96456. // My start position
  96457. var p = obj.pos || [0, 0, 0];
  96458. p = p.map(function (x) { return x * OIMO.INV_SCALE; });
  96459. // My size
  96460. var s = obj.size || [1, 1, 1];
  96461. s = s.map(function (x) { return x * OIMO.INV_SCALE; });
  96462. // My rotation in degre
  96463. var rot = obj.rot || [0, 0, 0];
  96464. rot = rot.map(function (x) { return x * OIMO.degtorad; });
  96465. var r = [];
  96466. for (var i = 0; i < rot.length / 3; i++) {
  96467. var tmp = OIMO.EulerToAxis(rot[i + 0], rot[i + 1], rot[i + 2]);
  96468. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  96469. }
  96470. // My physics setting
  96471. var sc = new OIMO.ShapeConfig();
  96472. if (obj.sc !== undefined) sc = obj.sc;
  96473. if (obj.config) {
  96474. // The density of the shape.
  96475. sc.density = obj.config[0] === undefined ? 1 : obj.config[0];
  96476. // The coefficient of friction of the shape.
  96477. sc.friction = obj.config[1] === undefined ? 0.4 : obj.config[1];
  96478. // The coefficient of restitution of the shape.
  96479. sc.restitution = obj.config[2] === undefined ? 0.2 : obj.config[2];
  96480. // The bits of the collision groups to which the shape belongs.
  96481. sc.belongsTo = obj.config[3] || 1;
  96482. //sc.belongsTo = obj.config[3] === undefined ? 1 : obj.config[3];
  96483. // The bits of the collision groups with which the shape collides.
  96484. sc.collidesWith = obj.config[4] || 0xffffffff;
  96485. //sc.collidesWith = obj.config[4] === undefined ? 0xffffffff : obj.config[4];
  96486. }
  96487. // direct physics setting
  96488. if (obj.density !== undefined) sc.density = obj.density;
  96489. if (obj.friction !== undefined) sc.friction = obj.friction;
  96490. if (obj.restitution !== undefined) sc.restitution = obj.restitution;
  96491. if (obj.belongsTo !== undefined) sc.belongsTo = obj.belongsTo;
  96492. if (obj.collidesWith !== undefined) sc.collidesWith = obj.collidesWith;
  96493. if (obj.massPos) {
  96494. obj.massPos = obj.massPos.map(function (x) { return x * OIMO.INV_SCALE; });
  96495. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  96496. }
  96497. if (obj.massRot) {
  96498. obj.massRot = obj.massRot.map(function (x) { return x * OIMO.degtorad; });
  96499. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  96500. }
  96501. // My rigidbody
  96502. var body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  96503. // My shapes
  96504. var shapes = [];
  96505. //if( typeof type === 'string' ) type = [type];// single shape
  96506. var n, n2;
  96507. for (var i = 0; i < type.length; i++) {
  96508. n = i * 3;
  96509. n2 = i * 4;
  96510. switch (type[i]) {
  96511. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n]); break;
  96512. case "cylinder": shapes[i] = new OIMO.CylinderShape(sc, s[n], s[n + 1]); break;
  96513. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n], s[n + 1], s[n + 2]); break;
  96514. }
  96515. body.addShape(shapes[i]);
  96516. if (i > 0) {
  96517. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  96518. shapes[i].relativePosition = new OIMO.Vec3(p[n], p[n + 1], p[n + 2]);
  96519. if (r[n2 + 0]) shapes[i].relativeRotation = [r[n2], r[n2 + 1], r[n2 + 2], r[n2 + 3]];
  96520. }
  96521. }
  96522. // I'm static or i move
  96523. if (move) {
  96524. if (obj.massPos || obj.massRot) body.setupMass(0x1, false);
  96525. else body.setupMass(0x1, true);
  96526. if (noSleep) body.allowSleep = false;
  96527. else body.allowSleep = true;
  96528. } else {
  96529. body.setupMass(0x2);
  96530. }
  96531. body.name = obj.name || ' ';
  96532. // finaly add to physics world
  96533. this.addRigidBody(body);
  96534. return body;
  96535. }
  96536. }
  96537. //UMD simplified
  96538. var root = this;
  96539. if (!root['OIMO']) {
  96540. if (true)
  96541. module.exports = OIMO;
  96542. else if (typeof define === 'function' && define.amd)
  96543. define([], function () {
  96544. return OIMO;
  96545. });
  96546. else if (typeof exports === 'object')
  96547. exports["OIMO"] = OIMO;
  96548. else {
  96549. root["OIMO"] = OIMO;
  96550. }
  96551. }
  96552. /***/ }),
  96553. /* 9 */
  96554. /***/ (function(module, exports, __webpack_require__) {
  96555. /**!
  96556. @license
  96557. handlebars v4.0.11
  96558. Copyright (C) 2011-2017 by Yehuda Katz
  96559. Permission is hereby granted, free of charge, to any person obtaining a copy
  96560. of this software and associated documentation files (the "Software"), to deal
  96561. in the Software without restriction, including without limitation the rights
  96562. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  96563. copies of the Software, and to permit persons to whom the Software is
  96564. furnished to do so, subject to the following conditions:
  96565. The above copyright notice and this permission notice shall be included in
  96566. all copies or substantial portions of the Software.
  96567. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  96568. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  96569. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  96570. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  96571. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  96572. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  96573. THE SOFTWARE.
  96574. */
  96575. !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],
  96576. 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){
  96577. 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"]}])});
  96578. /***/ }),
  96579. /* 10 */
  96580. /***/ (function(module, exports, __webpack_require__) {
  96581. "use strict";
  96582. Object.defineProperty(exports, "__esModule", { value: true });
  96583. var mappers_1 = __webpack_require__(4);
  96584. var configuration_1 = __webpack_require__(11);
  96585. var merge = __webpack_require__(18);
  96586. var ConfigurationLoader = (function () {
  96587. function ConfigurationLoader() {
  96588. }
  96589. ConfigurationLoader.prototype.loadConfiguration = function (initConfig) {
  96590. if (initConfig === void 0) { initConfig = {}; }
  96591. var loadedConfig = merge({}, initConfig);
  96592. if (loadedConfig.defaultViewer) {
  96593. loadedConfig = merge(loadedConfig, configuration_1.defaultConfiguration);
  96594. }
  96595. else {
  96596. loadedConfig = merge(configuration_1.defaultConfiguration, loadedConfig);
  96597. }
  96598. if (loadedConfig.configuration) {
  96599. var mapperType = "json";
  96600. var url = loadedConfig.configuration;
  96601. if (loadedConfig.configuration.url) {
  96602. url = loadedConfig.configuration.url;
  96603. mapperType = loadedConfig.configuration.mapper;
  96604. if (!mapperType) {
  96605. mapperType = loadedConfig.configuration.url.split('.').pop();
  96606. }
  96607. }
  96608. var mapper_1 = mappers_1.mapperManager.getMapper(mapperType);
  96609. return this.loadFile(url).then(function (data) {
  96610. var parsed = mapper_1.map(data);
  96611. return merge(loadedConfig, parsed);
  96612. });
  96613. }
  96614. else {
  96615. return Promise.resolve(loadedConfig);
  96616. }
  96617. };
  96618. ConfigurationLoader.prototype.loadFile = function (url) {
  96619. var cacheReference = this.configurationCache;
  96620. if (cacheReference[url]) {
  96621. return Promise.resolve(cacheReference[url]);
  96622. }
  96623. return new Promise(function (resolve, reject) {
  96624. var xhr = new XMLHttpRequest();
  96625. xhr.open('GET', url);
  96626. xhr.send();
  96627. xhr.onreadystatechange = function () {
  96628. var DONE = 4;
  96629. var OK = 200;
  96630. if (xhr.readyState === DONE) {
  96631. if (xhr.status === OK) {
  96632. cacheReference[url] = xhr.responseText;
  96633. resolve(xhr.responseText);
  96634. }
  96635. }
  96636. else {
  96637. console.log('Error: ' + xhr.status, url);
  96638. reject('Error: ' + xhr.status);
  96639. }
  96640. };
  96641. });
  96642. };
  96643. return ConfigurationLoader;
  96644. }());
  96645. exports.ConfigurationLoader = ConfigurationLoader;
  96646. exports.configurationLoader = new ConfigurationLoader();
  96647. exports.default = exports.configurationLoader;
  96648. /***/ }),
  96649. /* 11 */
  96650. /***/ (function(module, exports, __webpack_require__) {
  96651. "use strict";
  96652. Object.defineProperty(exports, "__esModule", { value: true });
  96653. exports.defaultConfiguration = {
  96654. version: "0.1",
  96655. eventPrefix: 'babylonviewer-',
  96656. events: true,
  96657. defaultViewer: true,
  96658. template: {
  96659. html: __webpack_require__(12),
  96660. children: {
  96661. loadingScreen: {
  96662. html: __webpack_require__(13),
  96663. config: {
  96664. backgroundColor: "#000000",
  96665. loadingImage: __webpack_require__(14)
  96666. }
  96667. },
  96668. viewer: {
  96669. html: __webpack_require__(15),
  96670. children: {
  96671. navBar: {
  96672. html: __webpack_require__(16),
  96673. config: {
  96674. buttons: [
  96675. {
  96676. id: 'fullscreen-button',
  96677. altText: "Fullscreen",
  96678. image: __webpack_require__(17)
  96679. }
  96680. ]
  96681. },
  96682. events: {
  96683. pointerdown: ['#fullscreen-button']
  96684. }
  96685. }
  96686. }
  96687. }
  96688. }
  96689. },
  96690. camera: {
  96691. behaviors: [
  96692. 0,
  96693. {
  96694. type: 2,
  96695. zoomOnBoundingInfo: true,
  96696. zoomStopsAnimation: false
  96697. }
  96698. ]
  96699. },
  96700. skybox: {
  96701. cubeTexture: {
  96702. url: 'https://playground.babylonjs.com/textures/environment.dds',
  96703. gammaSpace: false
  96704. },
  96705. pbr: true,
  96706. blur: 0.7,
  96707. infiniteDIstance: false,
  96708. material: {
  96709. imageProcessingConfiguration: {
  96710. colorCurves: {
  96711. globalDensity: 89,
  96712. globalHue: 58.88,
  96713. globalSaturation: 94
  96714. },
  96715. colorCurvesEnabled: true,
  96716. exposure: 1.5,
  96717. contrast: 1.66,
  96718. toneMappingEnabled: true,
  96719. vignetteEnabled: true,
  96720. vignetteWeight: 5,
  96721. vignetteColor: { r: 0.8, g: 0.6, b: 0.4 },
  96722. vignetteM: true
  96723. }
  96724. }
  96725. },
  96726. ground: true,
  96727. engine: {
  96728. antialiasing: true
  96729. },
  96730. scene: {
  96731. imageProcessingConfiguration: {
  96732. exposure: 1.4,
  96733. contrast: 1.66,
  96734. toneMappingEnabled: true
  96735. }
  96736. }
  96737. };
  96738. /***/ }),
  96739. /* 12 */
  96740. /***/ (function(module, exports) {
  96741. module.exports = "<style>\r\n loading-screen {\r\n position: absolute;\r\n z-index: 100;\r\n opacity: 1;\r\n pointer-events: none;\r\n display: flex;\r\n justify-content: center;\r\n align-items: center;\r\n -webkit-transition: opacity 1.5s ease;\r\n -moz-transition: opacity 1.5s ease;\r\n transition: opacity 1.5s ease;\r\n }\r\n\r\n viewer {\r\n position: relative;\r\n overflow: hidden;\r\n /* Start stage */\r\n flex: 1;\r\n z-index: 1;\r\n justify-content: center;\r\n align-items: center;\r\n\r\n width: 100%;\r\n height: 100%;\r\n }\r\n</style>\r\n\r\n<viewer></viewer>\r\n<loading-screen></loading-screen>";
  96742. /***/ }),
  96743. /* 13 */
  96744. /***/ (function(module, exports) {
  96745. module.exports = "<style>\r\n img.loading-image {\r\n -webkit-animation: spin 2s linear infinite;\r\n animation: spin 2s linear infinite;\r\n }\r\n\r\n @-webkit-keyframes spin {\r\n 0% {\r\n -webkit-transform: rotate(0deg);\r\n }\r\n 100% {\r\n -webkit-transform: rotate(360deg);\r\n }\r\n }\r\n\r\n @keyframes spin {\r\n 0% {\r\n transform: rotate(0deg);\r\n }\r\n 100% {\r\n transform: rotate(360deg);\r\n }\r\n }\r\n</style>\r\n\r\n<img class=\"loading-image\" src=\"{{loadingImage}}\">";
  96746. /***/ }),
  96747. /* 14 */
  96748. /***/ (function(module, exports) {
  96749. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZQHvphnV65cjTMzxaQY3eA5V9OO/hmnm1lSjE7woFsQbiXki4++foHnXkW4mLC1JUl947333tsMY3emqfB9jtPJlXN5U0+bOXPmWCPxgOccSy4+AfqPio+9/oFnbyatbqVE28GSZfjQ1NT0KQzaHMcdyPfyaNoE12HcvdxT29K3Fkv8A2vWrPmcifAFZNtD91yRY+SBZ+9UsMtEgD+jTpeenp6JXI6xpKkuUDqRcA6Kr0Wpens+InQTnIpV6Fdi+BQT64ulS5eOIzefD62na7CeoGcnLCM8ykt5OWlzcPv772/BS/w3nP+K+xU11+DvQe5dcrQlTfWAwbNMb8XA8AyGX80xtLlA6TAJuteMbVhhia1v5VMcr+LWMeoZ4xiYw7q6urbhHbgG+paCkIRQehHu4pO3O5fVydEomF5Ulx548JfVD2wqfKE2I3R3ob/f2GoC1DWhdz7HG3i5j2pvb9+Z24m6HvVZQtYsZFWcowlzePEP4jJdR/OQhxTVpAs9NMXxmZxuZKo8IG4s+v8R2tUFphSBTBWzH+OAFwn/gS3TuN55xYoVqfc6dXd3fwHZ1xFaTX0iyGbwjJqXXAammxP00EXx6UMGEx7ram7+vKnzBZ/87Xiwp40tEdDTgYwlHG/CmadSjO7L+XiialOZAej7POFG2VK0Khngl6Pn8/LL0YEtlFh4n8oDAqvaAYH8tzH2iNDm1IIFn8Ax50G7xtgCAU07CfAG4RHOz+vLZL7e0dGxlYlKHaj8BHo25xgrsfV5wrYH4KmouxV+ZZDnCUdwmXxMGgFvFUVWD+jQuOot6rI0tb4gcfaG9v+MrcAn+wj38gL8C7cObmlp2ZRjOkWYD6ypuAf6zjFHLSJ0c/6YQ813DM/yZXgehreiVgP8cvSfsOeExYsXuzs6n8v9j8mqBRZQmdjXVPuira1NHSpn8UDf4Xu0vd2uCtDzacJOlDDf5ng94X8JTWarB8R1EK7ju7udiYgEz/v3pLFKm4oHUHhh3iZdfshpaEYpA4pvKLLXBujLYKRq71XLhUHg27z12rW9B6L/QhLrWWxRH7nzeDK8awi/5HRTEx0K6MZQ694LHk0DqrgfADkreIYz1q5c+UlTEQzesIuMryrggYQWjNL3RGO7p2tuFMeqjaOidgzyCz1yJMTJ6L6d66WEVCcHIO/dQkI75Chs2g97Hoc3jRz9Lge1ED5l4r0gckqRPB0gTw34t1B+h3IqxZkmrn2SULUa7ezZszdE5xfR9130Xsm5ilrnHrmkQOcKvrkncxqrIiY6wlewbw7BOUfDo/b84zzvj9C7J7eCS0NrUiRKCPjUE7ScMBdlF/B2HqBi0ERXBcuXL99YnQz9fX2ah3Up4UnsWGEmDRuUhoTn+Z5PfvbZZ2N/fuCZRJgnfhNVBu73EZoIKt7l0L2UBsYeDZg016nb5EUCWuXQewinUtTuyq2aTStF14a8SD+VDQVj6hDYxjuXf4Hjl83sSMCmTp8j4FtoMuRQ5dAZcii3kk/0s2bBhxIcBxjxUlib1hWInEDO/6qKV+y4geO5HAMntEE/pq+nZyo0ywsG1SmwL4Orf+0yqGCfmvR73LAn9lAeBjQTEhkA+1h49a08iRflcq4H5iuXFU9cz4lqihC/LXS/NZa6Bc+pz5gql5ub6VXD2tZWTSPeyS7XgeLhXrMnEhj6MSHSwaIhFGZH8oA/JzzFeexvJbRN2HW03moT6cEChx6w4QY2rurn85JWrxsiCy0FwjcIqos8w7GZNPulkawDEbFHlaBtjzODEDrVztuKXMmADPWA3RaljyJeNdKq98ilAez8iJdyGqfO31V4NoV/EvyaCqR54V2EshE5Lqcb+TrkstkTLD4WKB4PNNZQ8P05HAelMXNSPWChC8JsYvwthJo0jSoF6fIqjjqe08Aat+LIkd+AVjn09zxbZFqK3tjXAUbXUaWDjTUSyN4J45YZX2Igo4cEOVfFson2ALIxSjR0jog5YNgpfNHM90BxIjDyWIB8Z2NfB01HISJ20wPaw4w1FlavXq1v8aPGXhFw9JNRFTDItifU/RwwpfmKxYsDK180kU4x0lhAXvOSJUs+bezlIDL2N4xi4GpjK4MGCuzUA+SPxzn3m4iKgKyV2DCV08DeMWg0B+zHHOt2DpjS3Mz1BfFOM25C5ZH4LxldJBB0g7GVARkaXgv8VsKqZtIMPpN9RUnJgRzU5Wfp22vifcG3+2vQvmdsdQXsX2pm+oKX+GYjjQXkPWqsXshpRhcJ0RpbGShSHiSuheP37ZYHsGusVHOrU1lMxkO9od4eE+8LlSzQqfetpnPAooBN/2Um+gISp89MkF8K4G3RrMJYoOhbYGxlQEGhSOGogfoLwipExGtUZVVBYIVAluaAaUpuWA+YujlPF22Ra/iBLYEOsV6tV4w0FiitfmLsXiBMU0NiAVrfsp77Zd8MHPgbDoHtva6uLs1jiv1piAKy5tCG+4KJ9wVO/p6RDzvy+b5rzSwP9Okh/WKPERiCWzfk4K8bUSTiOljAyCdx5DZG4gE8W5Dov+NYUfsV/j50fUC4dmXIQDh0qQ6PVgJsOcLM8oA410Ggvo6Ojr81di+g2TKuQOiyJOKWxlpCJpM5zUjKAL3awTsamQfEbYhjtDGKa5tPsyn/wAuiURftlBO56h6aunEwCMxxvV1d+2Fr7Jce2vAu5LUtLeoGi/19gtbToCaR97BoD6BvUs+WkXqgbw6OuhC6wH5l4rRGaCFOvYnjYbyxnpcsCvDVhYOxo6+zszNwSNHVTtJEmSiwzlMAQmNPwIPW42Dds2hfEK/5WJo0Fth+5VNxFHSlkoTzFRh/N3wnq0OGWxXtdoO8enFwaI4jsyidYgNZTxhrMEjEJ4w+En65ESWRXZ7Q4K/COqDAPlhka87WedB8KawmngTIHREOJs5pMiRp+p/GGgxL1FiA9hxjK6G1tVVdhJGAV15+cPXq1f7dahVC20Wg4miCp0uTe3Xh4Hwu93rY1B7SR/t7xQbP5R1FGgpy8IlKe+MJhZ9Aa7u5jPm+pGLX2BMDOZ+hDXgQiXIJ5xoXHZg96anEEFcvOTi0SMUXS4w0FijSTzTWYEA3hkTSEtDI2qw6RoytDLA6jctCvzKqJ8oPFOO7kAhnYe9cZGiWiZ/N9ezguWaSL4h3TUfvKJIfoN0I4sjigYSdZyxlcDVMgEczEY41ER6oZFBOh2Yqegf2zYoziFC3DuZZrjSTPLDtMlxaNPmPP/54W2OPxksrVozP5fLPGr8vEOpbxJCr3jQSJyDvGRNRhv7iHh8vE5LMpKznHBz4zSTOaXwe+mXGGh9tbWvVQf+iyfCAON/ZlTj4v43ECfB94Le4CuMrWVpTtw7O9fZOM5M8oD7xVSOLBdLuNWN1g7bgJUF8+4qpBjf7Te9M6hD4tBDc0289Wh2MHbuaSR7gsHOMLBaQ9W/G6o5MJrNDPu9dcYdQ33Yc95I6OFV5hnp2cGCliDingX5KU+9MShd0dmqta/k8J4zwnV2JsuuNxAnI83VwNpO52kiSoC4djA255cuXBzYPycGzjTQWkPdNY00OfRcQVLafRnd39ySLLsG1i20AyPZ3cDb7AyNJgnp1cOhUHUhcFiL045v9jTUa8Gjlm29fsQQhb3DzJLUEhC+oiK7EISPOwapoEh+7JQJti5YfGXs0YNC62ouC1h9lsrlToClsjc/RM7uSe0kd3EmlzTO/Kqk8Q106mM/Yw2aOB9jnOg6sWTHxJ9FraSJMy6nGz7RbZUDYmN7e3BnQ5Gisez7u3J9c0JwA6Pb0aCFvNObgwKk6NoU59uJwaJ8y1viAT4vCtEFXYO8SFQGtCZpllyXQtNqL+4lmZ/BN/5qJKQFZozEHe9JtAGSaw4wsFnie4JmUQcjleh8yZq0Fnmq3y0D02IzPMgnonYqYIfA4pC+TcXrgIahLB+PEb5s5HrjaR0b7kbHGB0pK7TDO1/T39x1lUZGAPlUH0xTbz+KSoC4dDDx2DQCHzTCaWOB5zjbW+KCSpW0IS0BIJmy6zWCk7WDuxZ4r5oO6dHB7e/sBZo4H2OfUsYOv9jHW+ECJdkAtA/c6MpmMd+XaEKj7km9M4F5TEfBzSKovDLKG1cHobw+b6EDa3WOksYBPAhevBUJMxl8GJTRhFyMLBKSJFn5ls9nvmogS0DfaHOzb3h8AcUuNNBLQNiWa0gRv4MwMMyBwCqxAfCIH82JdYSJKQN+ocjA5NHD2I/e1aj/23iPyhbG6A+bAgXsZoUEII/UAkkQORu71JqIE7o22HBw4VaelpWU74mPPDc/39d1trO5Qb4vJ8QXxbwat06WofcTInMCzeToAtN4VXUn/l1AXDkan9tDSfmL6C81BZooHxDkN9CMveLFZFFAWWZtDwVta3G0sJcAbe3bmYEiniShBXabcL+wflQDD5mD0yKlvk0b/Tk33AG5F7idG+/ibRe54oEl1nLG6A+ZYe1jyAIuG/u2LB3MazxwAfL5vJFGJinxQUwcju6c/n3+FNPm5JhJyy2k/sQTp5nm+2HBJCGi1X1WpwzuBoQXAN+IcjDz8mdePKi/WhH1uxd7GcCjIVBcWpUYDfZ0VbclEJSr2akMBhVrdX6j+Jx3DpSh7vKB8CIiqKwcrcXGqdr05k3RKbU9ryTQVkUB3aHMrEshw7kGCXiv8xxG0h6Uzent6Fpn6MhA17A6GT/3yTxNO1coJbgWur3JFf1fXNuTes5AZe18xXobFHJKv04JZc3O7CtIcgGL9KW03u3QCfL4D4b292dhrpoYgsYOhEz4kaOuHqXKqiagYiN9QnUlyKgX84JUYsQFP9GKzMFRSe8XJb9upE9Dn62CK/KQT75wdTLz+NXgPNdrDuYzeUd0ByN4Wp07n+EdCRZuTY1/ymZQDwIjQye9pA32xdw6IiUgHc639mN8kzCLRjkxzQRzitUpkZ8LZBP1CILUd55EVvdgsCrzJl5i8mgCja+Zgjst4Pq3DUnMmtSWqyNIuQruRU3+CbO08n+pvBAZAjf1IU5kcGJc0YRMBfVV3MPd2RN4+YbvYukI/3sSpe+LUmbw0ryG/6ts1oSLeYrMw6C0xeaFAGc+Wq3hbfeRk582b55lrzf3UHJwWkD0Wp+6BQ3+BfXEXw6UCdHX4TVB0BoJi9Y1Cp59XbUWN8HW7lRjLli3zbINE+1hNiCRI1cGakIhT99ani/A6z1z1nDoUqNQfbO40kyqDfrCBwMg3E5rsCy+8sFlHR8dEnFzRTq/I8hQ9NFFOtGhXVOxgFeUqfknUK7Ctpjl1ANKJ/vmUkvrdwRZmWjpA4J9MTyja2toKY8TQa/ufxP/Whdd5c5cQJHIwfBsTvkKiaqd6/fRyOHKqavdL0H+V2sxmWvrQCAeKItfmQlNyDG/8SVwnetMHyxmA7lm0K2I7GFrlVBW/V6FPP9GqeU4V0Kt2+O2yhctUN6AJBEWD9ngMnessJxh5AfCoQe+8q+xQOYLuWbQrQh2MXP1XYh8S9DKC2sI1z6kCatW3/RCZ6Vj9fNPMqx2wQVNJQlcNEl/mGG5pv48bi7HxMVSOoHsW7QqPg5GlvnJtk6/B9+HMqYUfaXE6rampqWy4dVhgi8FfLprnBXEex+i/wCSkNiSNDSpUxxt7Ccj2nQQYAwUHc9yE3HEotuifDklnfFYMdGNC/lWCxotDf4PvB/jHZTs71c+f2n+ryqCPPcb5/pKdGrTvbH2MUjH4ByOLBDpON9YSFi5cuI1FOwFbbyTox5T6y+iwFL8CqvWvwVtolWgSv/N4sXbl5ZP3r8hRLT50d56KgYJDCYXVhYOhtqqReKDdZuGJtSQSOk8f67x581SspvH3lpoBe9Vefbg/lzveaXmnAf6tEDMNGRp3LnV3ch29o10lQIf+bOKZc+XnmMGARF2EK4vUwQiSw33n7ZlqDWwcaK9Ob29vd26vwj+OT8m3kKFxdd9tlILSJ1Wo8Y8RZT/YiKOY4le5P3SGZJAc7telg7FroL16Jc/n/a1cBBCxsSblwT8LOfofcCh4AQ4x1uoCXZtgVKnYDXLMUECnPSQD29VBcrhfVw7GHrVXb6WylGg0SvUZcrr+YPYuwWVfaE9ltmpA2Q6EQq2UY+yigzf2oqCH4v4MIysD94fdwdig9uqDnB4T5/d+gwHPGNVFcOopyJiPLOfmGTwa0Ek8qS8RKDKORLFWH95utwbDd94SRqqN/Cv4PDXbTFfXfUZWBvRUPJCRBJiIqfnnccy0Dz74wHkWoypY2D4ZGU8gK+kKjQKQ8RcTW1uQI2fmc7nH7LIMFEW+sw6xdyN4CgvNByNIDjp+ZyRVhzlV7dVLaZc7t1cRoW0w9of/No6ptbuRdZupqC3QPZY33HchMkbJiRPssgyaHkN82XaJXPtOJuN+JRuixQI6Cu1VXiZtJehcFGpeNPyXI6cqPWTIvsxU1R7o912akevre4OHfTHot3fEfRbD3y8+Qu0djO5Ce5UXNGl7dTt4z0RGqnOuhgLZgmcPk2FHrrd3jgwkAVQ58e1ioxjcHeMLPWQcq+5gZKm9+hJHjXo5z4xQBQsxxyDjEfir+nNq5GfQo/nYh6f9e4NUgGEFx3DEzvw1nPrOhSJ+kh6GUBUHw6//Kmls96dJ2qv6FxNF9z8g405kVLVXDfkaiFAd4JIkttYUGFpyDOf91Ch/YVEe8DA/gORpuywDfLNMjBOQt4qEupbTPTX4YeJig+/qrnoxkfMeIdH2UHGBfP0H6kFepElc1rY5lBQYXZbzuO7BWYH7b3V3d/+TX1FEG/JSExEJdOi7qsnrx3DuNM8Zdg2NqnN/BjK0EXlVhxORr56wP6Lv/DT+X1FzYLynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC"
  96750. /***/ }),
  96751. /* 15 */
  96752. /***/ (function(module, exports) {
  96753. module.exports = "<style>\r\n .babylonjs-canvas {\r\n flex: 1;\r\n width: 100%;\r\n height: 100%;\r\n touch-action: none;\r\n }\r\n\r\n nav-bar {\r\n position: absolute;\r\n height: 160px;\r\n width: 100%;\r\n bottom: 0;\r\n background-color: rgba(0, 0, 0, 0.3);\r\n color: white;\r\n transition: 1s;\r\n\r\n align-items: center;\r\n justify-content: center;\r\n display: flex;\r\n\r\n flex-direction: column;\r\n }\r\n\r\n /* Big screens have room for the entire navbar */\r\n\r\n @media screen and (min-width: 768px) {\r\n nav-bar {\r\n flex-direction: row;\r\n justify-content: space-between;\r\n height: 80px;\r\n }\r\n }\r\n</style>\r\n\r\n<canvas class=\"babylonjs-canvas\" id=\"{{canvasId}}\">\r\n</canvas>\r\n\r\n<nav-bar></nav-bar>";
  96754. /***/ }),
  96755. /* 16 */
  96756. /***/ (function(module, exports) {
  96757. module.exports = "<style>\r\n div.flex-container {\r\n display: flex;\r\n }\r\n\r\n div.thumbnail {\r\n position: relative;\r\n overflow: hidden;\r\n display: block;\r\n width: 40px;\r\n height: 40px;\r\n background-size: cover;\r\n background-position: center;\r\n border-radius: 20px;\r\n margin: 0 10px;\r\n }\r\n\r\n div.title-container {\r\n flex-direction: column;\r\n display: flex;\r\n justify-content: space-between;\r\n }\r\n\r\n span.model-title {\r\n font-size: 125%;\r\n }\r\n\r\n span.model-subtitle {\r\n font-size: 90%;\r\n }\r\n\r\n div.button-container {\r\n align-items: center;\r\n display: flex;\r\n }\r\n\r\n div.button {\r\n cursor: pointer;\r\n height: 30px;\r\n margin: 0 10px;\r\n }\r\n\r\n div.button img {\r\n height: 100%;\r\n }\r\n</style>\r\n\r\n<div class=\"flex-container\" id=\"model-metadata\">\r\n <!-- holding the description -->\r\n <div class=\"thumbnail\">\r\n <!-- holding the thumbnail \r\n <img src=\"{{thumbnail}}\" alt=\"{{title}}\">-->\r\n </div>\r\n <div class=\"title-container\">\r\n\r\n <span class=\"model-title\">{{#if title}}{{title}}{{/if}}</span>\r\n <span class=\"model-subtitle\"> {{#if subtitle}}{{subtitle}} {{/if}}</span>\r\n </div>\r\n</div>\r\n<div class=\"button-container\">\r\n <!-- holding the buttons -->\r\n {{#each buttons}}\r\n <div id=\"{{id}}\" class=\"button\">\r\n {{#if text}}\r\n <span>{{text}}</span>> {{/if}} {{#if image}}\r\n <img src=\"{{image}}\" alt=\"{{altText}}\"> {{/if}}\r\n </div>\r\n {{/each}}\r\n</div>";
  96758. /***/ }),
  96759. /* 17 */
  96760. /***/ (function(module, exports) {
  96761. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAAZiS0dEAAAAAAAA+UO7fwAAAAlwSFlzAAAASAAAAEgARslrPgAAAG5JREFUaN7t2NEKgCAMBVAX/f8v21MvQTDEHNI5z21wU7HVGgBQJ7IP9t57qmFErOhzO758OysIUO0cLczu0Wxd9mw8bb8CAlQTAAAqDU9ko1+js/tvfxMLUE2AasMz8dsMO+u/UNb2KyAAAPBnFyAoHCsn18AtAAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDE3LTEwLTI0VDA5OjI5OjA3KzAwOjAwnIEg5AAAACV0RVh0ZGF0ZTptb2RpZnkAMjAxNy0xMC0yNFQwOToyOTowNyswMDowMO3cmFgAAAAodEVYdHN2ZzpiYXNlLXVyaQBmaWxlOi8vL3RtcC9tYWdpY2stYU9TenZXZUYevZw/AAAAAElFTkSuQmCC"
  96762. /***/ }),
  96763. /* 18 */
  96764. /***/ (function(module, exports, __webpack_require__) {
  96765. /* WEBPACK VAR INJECTION */(function(global, module) {/**
  96766. * lodash (Custom Build) <https://lodash.com/>
  96767. * Build: `lodash modularize exports="npm" -o ./`
  96768. * Copyright jQuery Foundation and other contributors <https://jquery.org/>
  96769. * Released under MIT license <https://lodash.com/license>
  96770. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  96771. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  96772. */
  96773. /** Used as the size to enable large array optimizations. */
  96774. var LARGE_ARRAY_SIZE = 200;
  96775. /** Used to stand-in for `undefined` hash values. */
  96776. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  96777. /** Used as references for various `Number` constants. */
  96778. var MAX_SAFE_INTEGER = 9007199254740991;
  96779. /** `Object#toString` result references. */
  96780. var argsTag = '[object Arguments]',
  96781. arrayTag = '[object Array]',
  96782. boolTag = '[object Boolean]',
  96783. dateTag = '[object Date]',
  96784. errorTag = '[object Error]',
  96785. funcTag = '[object Function]',
  96786. genTag = '[object GeneratorFunction]',
  96787. mapTag = '[object Map]',
  96788. numberTag = '[object Number]',
  96789. objectTag = '[object Object]',
  96790. promiseTag = '[object Promise]',
  96791. regexpTag = '[object RegExp]',
  96792. setTag = '[object Set]',
  96793. stringTag = '[object String]',
  96794. symbolTag = '[object Symbol]',
  96795. weakMapTag = '[object WeakMap]';
  96796. var arrayBufferTag = '[object ArrayBuffer]',
  96797. dataViewTag = '[object DataView]',
  96798. float32Tag = '[object Float32Array]',
  96799. float64Tag = '[object Float64Array]',
  96800. int8Tag = '[object Int8Array]',
  96801. int16Tag = '[object Int16Array]',
  96802. int32Tag = '[object Int32Array]',
  96803. uint8Tag = '[object Uint8Array]',
  96804. uint8ClampedTag = '[object Uint8ClampedArray]',
  96805. uint16Tag = '[object Uint16Array]',
  96806. uint32Tag = '[object Uint32Array]';
  96807. /**
  96808. * Used to match `RegExp`
  96809. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  96810. */
  96811. var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  96812. /** Used to match `RegExp` flags from their coerced string values. */
  96813. var reFlags = /\w*$/;
  96814. /** Used to detect host constructors (Safari). */
  96815. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  96816. /** Used to detect unsigned integer values. */
  96817. var reIsUint = /^(?:0|[1-9]\d*)$/;
  96818. /** Used to identify `toStringTag` values of typed arrays. */
  96819. var typedArrayTags = {};
  96820. typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
  96821. typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
  96822. typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
  96823. typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
  96824. typedArrayTags[uint32Tag] = true;
  96825. typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
  96826. typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
  96827. typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
  96828. typedArrayTags[errorTag] = typedArrayTags[funcTag] =
  96829. typedArrayTags[mapTag] = typedArrayTags[numberTag] =
  96830. typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
  96831. typedArrayTags[setTag] = typedArrayTags[stringTag] =
  96832. typedArrayTags[weakMapTag] = false;
  96833. /** Used to identify `toStringTag` values supported by `_.clone`. */
  96834. var cloneableTags = {};
  96835. cloneableTags[argsTag] = cloneableTags[arrayTag] =
  96836. cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
  96837. cloneableTags[boolTag] = cloneableTags[dateTag] =
  96838. cloneableTags[float32Tag] = cloneableTags[float64Tag] =
  96839. cloneableTags[int8Tag] = cloneableTags[int16Tag] =
  96840. cloneableTags[int32Tag] = cloneableTags[mapTag] =
  96841. cloneableTags[numberTag] = cloneableTags[objectTag] =
  96842. cloneableTags[regexpTag] = cloneableTags[setTag] =
  96843. cloneableTags[stringTag] = cloneableTags[symbolTag] =
  96844. cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
  96845. cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
  96846. cloneableTags[errorTag] = cloneableTags[funcTag] =
  96847. cloneableTags[weakMapTag] = false;
  96848. /** Detect free variable `global` from Node.js. */
  96849. var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
  96850. /** Detect free variable `self`. */
  96851. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  96852. /** Used as a reference to the global object. */
  96853. var root = freeGlobal || freeSelf || Function('return this')();
  96854. /** Detect free variable `exports`. */
  96855. var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
  96856. /** Detect free variable `module`. */
  96857. var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
  96858. /** Detect the popular CommonJS extension `module.exports`. */
  96859. var moduleExports = freeModule && freeModule.exports === freeExports;
  96860. /** Detect free variable `process` from Node.js. */
  96861. var freeProcess = moduleExports && freeGlobal.process;
  96862. /** Used to access faster Node.js helpers. */
  96863. var nodeUtil = (function() {
  96864. try {
  96865. return freeProcess && freeProcess.binding('util');
  96866. } catch (e) {}
  96867. }());
  96868. /* Node.js helper references. */
  96869. var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
  96870. /**
  96871. * Adds the key-value `pair` to `map`.
  96872. *
  96873. * @private
  96874. * @param {Object} map The map to modify.
  96875. * @param {Array} pair The key-value pair to add.
  96876. * @returns {Object} Returns `map`.
  96877. */
  96878. function addMapEntry(map, pair) {
  96879. // Don't return `map.set` because it's not chainable in IE 11.
  96880. map.set(pair[0], pair[1]);
  96881. return map;
  96882. }
  96883. /**
  96884. * Adds `value` to `set`.
  96885. *
  96886. * @private
  96887. * @param {Object} set The set to modify.
  96888. * @param {*} value The value to add.
  96889. * @returns {Object} Returns `set`.
  96890. */
  96891. function addSetEntry(set, value) {
  96892. // Don't return `set.add` because it's not chainable in IE 11.
  96893. set.add(value);
  96894. return set;
  96895. }
  96896. /**
  96897. * A faster alternative to `Function#apply`, this function invokes `func`
  96898. * with the `this` binding of `thisArg` and the arguments of `args`.
  96899. *
  96900. * @private
  96901. * @param {Function} func The function to invoke.
  96902. * @param {*} thisArg The `this` binding of `func`.
  96903. * @param {Array} args The arguments to invoke `func` with.
  96904. * @returns {*} Returns the result of `func`.
  96905. */
  96906. function apply(func, thisArg, args) {
  96907. switch (args.length) {
  96908. case 0: return func.call(thisArg);
  96909. case 1: return func.call(thisArg, args[0]);
  96910. case 2: return func.call(thisArg, args[0], args[1]);
  96911. case 3: return func.call(thisArg, args[0], args[1], args[2]);
  96912. }
  96913. return func.apply(thisArg, args);
  96914. }
  96915. /**
  96916. * A specialized version of `_.forEach` for arrays without support for
  96917. * iteratee shorthands.
  96918. *
  96919. * @private
  96920. * @param {Array} [array] The array to iterate over.
  96921. * @param {Function} iteratee The function invoked per iteration.
  96922. * @returns {Array} Returns `array`.
  96923. */
  96924. function arrayEach(array, iteratee) {
  96925. var index = -1,
  96926. length = array ? array.length : 0;
  96927. while (++index < length) {
  96928. if (iteratee(array[index], index, array) === false) {
  96929. break;
  96930. }
  96931. }
  96932. return array;
  96933. }
  96934. /**
  96935. * Appends the elements of `values` to `array`.
  96936. *
  96937. * @private
  96938. * @param {Array} array The array to modify.
  96939. * @param {Array} values The values to append.
  96940. * @returns {Array} Returns `array`.
  96941. */
  96942. function arrayPush(array, values) {
  96943. var index = -1,
  96944. length = values.length,
  96945. offset = array.length;
  96946. while (++index < length) {
  96947. array[offset + index] = values[index];
  96948. }
  96949. return array;
  96950. }
  96951. /**
  96952. * A specialized version of `_.reduce` for arrays without support for
  96953. * iteratee shorthands.
  96954. *
  96955. * @private
  96956. * @param {Array} [array] The array to iterate over.
  96957. * @param {Function} iteratee The function invoked per iteration.
  96958. * @param {*} [accumulator] The initial value.
  96959. * @param {boolean} [initAccum] Specify using the first element of `array` as
  96960. * the initial value.
  96961. * @returns {*} Returns the accumulated value.
  96962. */
  96963. function arrayReduce(array, iteratee, accumulator, initAccum) {
  96964. var index = -1,
  96965. length = array ? array.length : 0;
  96966. if (initAccum && length) {
  96967. accumulator = array[++index];
  96968. }
  96969. while (++index < length) {
  96970. accumulator = iteratee(accumulator, array[index], index, array);
  96971. }
  96972. return accumulator;
  96973. }
  96974. /**
  96975. * The base implementation of `_.times` without support for iteratee shorthands
  96976. * or max array length checks.
  96977. *
  96978. * @private
  96979. * @param {number} n The number of times to invoke `iteratee`.
  96980. * @param {Function} iteratee The function invoked per iteration.
  96981. * @returns {Array} Returns the array of results.
  96982. */
  96983. function baseTimes(n, iteratee) {
  96984. var index = -1,
  96985. result = Array(n);
  96986. while (++index < n) {
  96987. result[index] = iteratee(index);
  96988. }
  96989. return result;
  96990. }
  96991. /**
  96992. * The base implementation of `_.unary` without support for storing metadata.
  96993. *
  96994. * @private
  96995. * @param {Function} func The function to cap arguments for.
  96996. * @returns {Function} Returns the new capped function.
  96997. */
  96998. function baseUnary(func) {
  96999. return function(value) {
  97000. return func(value);
  97001. };
  97002. }
  97003. /**
  97004. * Gets the value at `key` of `object`.
  97005. *
  97006. * @private
  97007. * @param {Object} [object] The object to query.
  97008. * @param {string} key The key of the property to get.
  97009. * @returns {*} Returns the property value.
  97010. */
  97011. function getValue(object, key) {
  97012. return object == null ? undefined : object[key];
  97013. }
  97014. /**
  97015. * Checks if `value` is a host object in IE < 9.
  97016. *
  97017. * @private
  97018. * @param {*} value The value to check.
  97019. * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
  97020. */
  97021. function isHostObject(value) {
  97022. // Many host objects are `Object` objects that can coerce to strings
  97023. // despite having improperly defined `toString` methods.
  97024. var result = false;
  97025. if (value != null && typeof value.toString != 'function') {
  97026. try {
  97027. result = !!(value + '');
  97028. } catch (e) {}
  97029. }
  97030. return result;
  97031. }
  97032. /**
  97033. * Converts `map` to its key-value pairs.
  97034. *
  97035. * @private
  97036. * @param {Object} map The map to convert.
  97037. * @returns {Array} Returns the key-value pairs.
  97038. */
  97039. function mapToArray(map) {
  97040. var index = -1,
  97041. result = Array(map.size);
  97042. map.forEach(function(value, key) {
  97043. result[++index] = [key, value];
  97044. });
  97045. return result;
  97046. }
  97047. /**
  97048. * Creates a unary function that invokes `func` with its argument transformed.
  97049. *
  97050. * @private
  97051. * @param {Function} func The function to wrap.
  97052. * @param {Function} transform The argument transform.
  97053. * @returns {Function} Returns the new function.
  97054. */
  97055. function overArg(func, transform) {
  97056. return function(arg) {
  97057. return func(transform(arg));
  97058. };
  97059. }
  97060. /**
  97061. * Converts `set` to an array of its values.
  97062. *
  97063. * @private
  97064. * @param {Object} set The set to convert.
  97065. * @returns {Array} Returns the values.
  97066. */
  97067. function setToArray(set) {
  97068. var index = -1,
  97069. result = Array(set.size);
  97070. set.forEach(function(value) {
  97071. result[++index] = value;
  97072. });
  97073. return result;
  97074. }
  97075. /** Used for built-in method references. */
  97076. var arrayProto = Array.prototype,
  97077. funcProto = Function.prototype,
  97078. objectProto = Object.prototype;
  97079. /** Used to detect overreaching core-js shims. */
  97080. var coreJsData = root['__core-js_shared__'];
  97081. /** Used to detect methods masquerading as native. */
  97082. var maskSrcKey = (function() {
  97083. var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
  97084. return uid ? ('Symbol(src)_1.' + uid) : '';
  97085. }());
  97086. /** Used to resolve the decompiled source of functions. */
  97087. var funcToString = funcProto.toString;
  97088. /** Used to check objects for own properties. */
  97089. var hasOwnProperty = objectProto.hasOwnProperty;
  97090. /** Used to infer the `Object` constructor. */
  97091. var objectCtorString = funcToString.call(Object);
  97092. /**
  97093. * Used to resolve the
  97094. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  97095. * of values.
  97096. */
  97097. var objectToString = objectProto.toString;
  97098. /** Used to detect if a method is native. */
  97099. var reIsNative = RegExp('^' +
  97100. funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
  97101. .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
  97102. );
  97103. /** Built-in value references. */
  97104. var Buffer = moduleExports ? root.Buffer : undefined,
  97105. Symbol = root.Symbol,
  97106. Uint8Array = root.Uint8Array,
  97107. getPrototype = overArg(Object.getPrototypeOf, Object),
  97108. objectCreate = Object.create,
  97109. propertyIsEnumerable = objectProto.propertyIsEnumerable,
  97110. splice = arrayProto.splice;
  97111. /* Built-in method references for those with the same name as other `lodash` methods. */
  97112. var nativeGetSymbols = Object.getOwnPropertySymbols,
  97113. nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
  97114. nativeKeys = overArg(Object.keys, Object),
  97115. nativeMax = Math.max;
  97116. /* Built-in method references that are verified to be native. */
  97117. var DataView = getNative(root, 'DataView'),
  97118. Map = getNative(root, 'Map'),
  97119. Promise = getNative(root, 'Promise'),
  97120. Set = getNative(root, 'Set'),
  97121. WeakMap = getNative(root, 'WeakMap'),
  97122. nativeCreate = getNative(Object, 'create');
  97123. /** Used to detect maps, sets, and weakmaps. */
  97124. var dataViewCtorString = toSource(DataView),
  97125. mapCtorString = toSource(Map),
  97126. promiseCtorString = toSource(Promise),
  97127. setCtorString = toSource(Set),
  97128. weakMapCtorString = toSource(WeakMap);
  97129. /** Used to convert symbols to primitives and strings. */
  97130. var symbolProto = Symbol ? Symbol.prototype : undefined,
  97131. symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
  97132. /**
  97133. * Creates a hash object.
  97134. *
  97135. * @private
  97136. * @constructor
  97137. * @param {Array} [entries] The key-value pairs to cache.
  97138. */
  97139. function Hash(entries) {
  97140. var index = -1,
  97141. length = entries ? entries.length : 0;
  97142. this.clear();
  97143. while (++index < length) {
  97144. var entry = entries[index];
  97145. this.set(entry[0], entry[1]);
  97146. }
  97147. }
  97148. /**
  97149. * Removes all key-value entries from the hash.
  97150. *
  97151. * @private
  97152. * @name clear
  97153. * @memberOf Hash
  97154. */
  97155. function hashClear() {
  97156. this.__data__ = nativeCreate ? nativeCreate(null) : {};
  97157. }
  97158. /**
  97159. * Removes `key` and its value from the hash.
  97160. *
  97161. * @private
  97162. * @name delete
  97163. * @memberOf Hash
  97164. * @param {Object} hash The hash to modify.
  97165. * @param {string} key The key of the value to remove.
  97166. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  97167. */
  97168. function hashDelete(key) {
  97169. return this.has(key) && delete this.__data__[key];
  97170. }
  97171. /**
  97172. * Gets the hash value for `key`.
  97173. *
  97174. * @private
  97175. * @name get
  97176. * @memberOf Hash
  97177. * @param {string} key The key of the value to get.
  97178. * @returns {*} Returns the entry value.
  97179. */
  97180. function hashGet(key) {
  97181. var data = this.__data__;
  97182. if (nativeCreate) {
  97183. var result = data[key];
  97184. return result === HASH_UNDEFINED ? undefined : result;
  97185. }
  97186. return hasOwnProperty.call(data, key) ? data[key] : undefined;
  97187. }
  97188. /**
  97189. * Checks if a hash value for `key` exists.
  97190. *
  97191. * @private
  97192. * @name has
  97193. * @memberOf Hash
  97194. * @param {string} key The key of the entry to check.
  97195. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  97196. */
  97197. function hashHas(key) {
  97198. var data = this.__data__;
  97199. return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
  97200. }
  97201. /**
  97202. * Sets the hash `key` to `value`.
  97203. *
  97204. * @private
  97205. * @name set
  97206. * @memberOf Hash
  97207. * @param {string} key The key of the value to set.
  97208. * @param {*} value The value to set.
  97209. * @returns {Object} Returns the hash instance.
  97210. */
  97211. function hashSet(key, value) {
  97212. var data = this.__data__;
  97213. data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
  97214. return this;
  97215. }
  97216. // Add methods to `Hash`.
  97217. Hash.prototype.clear = hashClear;
  97218. Hash.prototype['delete'] = hashDelete;
  97219. Hash.prototype.get = hashGet;
  97220. Hash.prototype.has = hashHas;
  97221. Hash.prototype.set = hashSet;
  97222. /**
  97223. * Creates an list cache object.
  97224. *
  97225. * @private
  97226. * @constructor
  97227. * @param {Array} [entries] The key-value pairs to cache.
  97228. */
  97229. function ListCache(entries) {
  97230. var index = -1,
  97231. length = entries ? entries.length : 0;
  97232. this.clear();
  97233. while (++index < length) {
  97234. var entry = entries[index];
  97235. this.set(entry[0], entry[1]);
  97236. }
  97237. }
  97238. /**
  97239. * Removes all key-value entries from the list cache.
  97240. *
  97241. * @private
  97242. * @name clear
  97243. * @memberOf ListCache
  97244. */
  97245. function listCacheClear() {
  97246. this.__data__ = [];
  97247. }
  97248. /**
  97249. * Removes `key` and its value from the list cache.
  97250. *
  97251. * @private
  97252. * @name delete
  97253. * @memberOf ListCache
  97254. * @param {string} key The key of the value to remove.
  97255. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  97256. */
  97257. function listCacheDelete(key) {
  97258. var data = this.__data__,
  97259. index = assocIndexOf(data, key);
  97260. if (index < 0) {
  97261. return false;
  97262. }
  97263. var lastIndex = data.length - 1;
  97264. if (index == lastIndex) {
  97265. data.pop();
  97266. } else {
  97267. splice.call(data, index, 1);
  97268. }
  97269. return true;
  97270. }
  97271. /**
  97272. * Gets the list cache value for `key`.
  97273. *
  97274. * @private
  97275. * @name get
  97276. * @memberOf ListCache
  97277. * @param {string} key The key of the value to get.
  97278. * @returns {*} Returns the entry value.
  97279. */
  97280. function listCacheGet(key) {
  97281. var data = this.__data__,
  97282. index = assocIndexOf(data, key);
  97283. return index < 0 ? undefined : data[index][1];
  97284. }
  97285. /**
  97286. * Checks if a list cache value for `key` exists.
  97287. *
  97288. * @private
  97289. * @name has
  97290. * @memberOf ListCache
  97291. * @param {string} key The key of the entry to check.
  97292. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  97293. */
  97294. function listCacheHas(key) {
  97295. return assocIndexOf(this.__data__, key) > -1;
  97296. }
  97297. /**
  97298. * Sets the list cache `key` to `value`.
  97299. *
  97300. * @private
  97301. * @name set
  97302. * @memberOf ListCache
  97303. * @param {string} key The key of the value to set.
  97304. * @param {*} value The value to set.
  97305. * @returns {Object} Returns the list cache instance.
  97306. */
  97307. function listCacheSet(key, value) {
  97308. var data = this.__data__,
  97309. index = assocIndexOf(data, key);
  97310. if (index < 0) {
  97311. data.push([key, value]);
  97312. } else {
  97313. data[index][1] = value;
  97314. }
  97315. return this;
  97316. }
  97317. // Add methods to `ListCache`.
  97318. ListCache.prototype.clear = listCacheClear;
  97319. ListCache.prototype['delete'] = listCacheDelete;
  97320. ListCache.prototype.get = listCacheGet;
  97321. ListCache.prototype.has = listCacheHas;
  97322. ListCache.prototype.set = listCacheSet;
  97323. /**
  97324. * Creates a map cache object to store key-value pairs.
  97325. *
  97326. * @private
  97327. * @constructor
  97328. * @param {Array} [entries] The key-value pairs to cache.
  97329. */
  97330. function MapCache(entries) {
  97331. var index = -1,
  97332. length = entries ? entries.length : 0;
  97333. this.clear();
  97334. while (++index < length) {
  97335. var entry = entries[index];
  97336. this.set(entry[0], entry[1]);
  97337. }
  97338. }
  97339. /**
  97340. * Removes all key-value entries from the map.
  97341. *
  97342. * @private
  97343. * @name clear
  97344. * @memberOf MapCache
  97345. */
  97346. function mapCacheClear() {
  97347. this.__data__ = {
  97348. 'hash': new Hash,
  97349. 'map': new (Map || ListCache),
  97350. 'string': new Hash
  97351. };
  97352. }
  97353. /**
  97354. * Removes `key` and its value from the map.
  97355. *
  97356. * @private
  97357. * @name delete
  97358. * @memberOf MapCache
  97359. * @param {string} key The key of the value to remove.
  97360. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  97361. */
  97362. function mapCacheDelete(key) {
  97363. return getMapData(this, key)['delete'](key);
  97364. }
  97365. /**
  97366. * Gets the map value for `key`.
  97367. *
  97368. * @private
  97369. * @name get
  97370. * @memberOf MapCache
  97371. * @param {string} key The key of the value to get.
  97372. * @returns {*} Returns the entry value.
  97373. */
  97374. function mapCacheGet(key) {
  97375. return getMapData(this, key).get(key);
  97376. }
  97377. /**
  97378. * Checks if a map value for `key` exists.
  97379. *
  97380. * @private
  97381. * @name has
  97382. * @memberOf MapCache
  97383. * @param {string} key The key of the entry to check.
  97384. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  97385. */
  97386. function mapCacheHas(key) {
  97387. return getMapData(this, key).has(key);
  97388. }
  97389. /**
  97390. * Sets the map `key` to `value`.
  97391. *
  97392. * @private
  97393. * @name set
  97394. * @memberOf MapCache
  97395. * @param {string} key The key of the value to set.
  97396. * @param {*} value The value to set.
  97397. * @returns {Object} Returns the map cache instance.
  97398. */
  97399. function mapCacheSet(key, value) {
  97400. getMapData(this, key).set(key, value);
  97401. return this;
  97402. }
  97403. // Add methods to `MapCache`.
  97404. MapCache.prototype.clear = mapCacheClear;
  97405. MapCache.prototype['delete'] = mapCacheDelete;
  97406. MapCache.prototype.get = mapCacheGet;
  97407. MapCache.prototype.has = mapCacheHas;
  97408. MapCache.prototype.set = mapCacheSet;
  97409. /**
  97410. * Creates a stack cache object to store key-value pairs.
  97411. *
  97412. * @private
  97413. * @constructor
  97414. * @param {Array} [entries] The key-value pairs to cache.
  97415. */
  97416. function Stack(entries) {
  97417. this.__data__ = new ListCache(entries);
  97418. }
  97419. /**
  97420. * Removes all key-value entries from the stack.
  97421. *
  97422. * @private
  97423. * @name clear
  97424. * @memberOf Stack
  97425. */
  97426. function stackClear() {
  97427. this.__data__ = new ListCache;
  97428. }
  97429. /**
  97430. * Removes `key` and its value from the stack.
  97431. *
  97432. * @private
  97433. * @name delete
  97434. * @memberOf Stack
  97435. * @param {string} key The key of the value to remove.
  97436. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  97437. */
  97438. function stackDelete(key) {
  97439. return this.__data__['delete'](key);
  97440. }
  97441. /**
  97442. * Gets the stack value for `key`.
  97443. *
  97444. * @private
  97445. * @name get
  97446. * @memberOf Stack
  97447. * @param {string} key The key of the value to get.
  97448. * @returns {*} Returns the entry value.
  97449. */
  97450. function stackGet(key) {
  97451. return this.__data__.get(key);
  97452. }
  97453. /**
  97454. * Checks if a stack value for `key` exists.
  97455. *
  97456. * @private
  97457. * @name has
  97458. * @memberOf Stack
  97459. * @param {string} key The key of the entry to check.
  97460. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  97461. */
  97462. function stackHas(key) {
  97463. return this.__data__.has(key);
  97464. }
  97465. /**
  97466. * Sets the stack `key` to `value`.
  97467. *
  97468. * @private
  97469. * @name set
  97470. * @memberOf Stack
  97471. * @param {string} key The key of the value to set.
  97472. * @param {*} value The value to set.
  97473. * @returns {Object} Returns the stack cache instance.
  97474. */
  97475. function stackSet(key, value) {
  97476. var cache = this.__data__;
  97477. if (cache instanceof ListCache) {
  97478. var pairs = cache.__data__;
  97479. if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
  97480. pairs.push([key, value]);
  97481. return this;
  97482. }
  97483. cache = this.__data__ = new MapCache(pairs);
  97484. }
  97485. cache.set(key, value);
  97486. return this;
  97487. }
  97488. // Add methods to `Stack`.
  97489. Stack.prototype.clear = stackClear;
  97490. Stack.prototype['delete'] = stackDelete;
  97491. Stack.prototype.get = stackGet;
  97492. Stack.prototype.has = stackHas;
  97493. Stack.prototype.set = stackSet;
  97494. /**
  97495. * Creates an array of the enumerable property names of the array-like `value`.
  97496. *
  97497. * @private
  97498. * @param {*} value The value to query.
  97499. * @param {boolean} inherited Specify returning inherited property names.
  97500. * @returns {Array} Returns the array of property names.
  97501. */
  97502. function arrayLikeKeys(value, inherited) {
  97503. // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
  97504. // Safari 9 makes `arguments.length` enumerable in strict mode.
  97505. var result = (isArray(value) || isArguments(value))
  97506. ? baseTimes(value.length, String)
  97507. : [];
  97508. var length = result.length,
  97509. skipIndexes = !!length;
  97510. for (var key in value) {
  97511. if ((inherited || hasOwnProperty.call(value, key)) &&
  97512. !(skipIndexes && (key == 'length' || isIndex(key, length)))) {
  97513. result.push(key);
  97514. }
  97515. }
  97516. return result;
  97517. }
  97518. /**
  97519. * This function is like `assignValue` except that it doesn't assign
  97520. * `undefined` values.
  97521. *
  97522. * @private
  97523. * @param {Object} object The object to modify.
  97524. * @param {string} key The key of the property to assign.
  97525. * @param {*} value The value to assign.
  97526. */
  97527. function assignMergeValue(object, key, value) {
  97528. if ((value !== undefined && !eq(object[key], value)) ||
  97529. (typeof key == 'number' && value === undefined && !(key in object))) {
  97530. object[key] = value;
  97531. }
  97532. }
  97533. /**
  97534. * Assigns `value` to `key` of `object` if the existing value is not equivalent
  97535. * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  97536. * for equality comparisons.
  97537. *
  97538. * @private
  97539. * @param {Object} object The object to modify.
  97540. * @param {string} key The key of the property to assign.
  97541. * @param {*} value The value to assign.
  97542. */
  97543. function assignValue(object, key, value) {
  97544. var objValue = object[key];
  97545. if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
  97546. (value === undefined && !(key in object))) {
  97547. object[key] = value;
  97548. }
  97549. }
  97550. /**
  97551. * Gets the index at which the `key` is found in `array` of key-value pairs.
  97552. *
  97553. * @private
  97554. * @param {Array} array The array to inspect.
  97555. * @param {*} key The key to search for.
  97556. * @returns {number} Returns the index of the matched value, else `-1`.
  97557. */
  97558. function assocIndexOf(array, key) {
  97559. var length = array.length;
  97560. while (length--) {
  97561. if (eq(array[length][0], key)) {
  97562. return length;
  97563. }
  97564. }
  97565. return -1;
  97566. }
  97567. /**
  97568. * The base implementation of `_.assign` without support for multiple sources
  97569. * or `customizer` functions.
  97570. *
  97571. * @private
  97572. * @param {Object} object The destination object.
  97573. * @param {Object} source The source object.
  97574. * @returns {Object} Returns `object`.
  97575. */
  97576. function baseAssign(object, source) {
  97577. return object && copyObject(source, keys(source), object);
  97578. }
  97579. /**
  97580. * The base implementation of `_.clone` and `_.cloneDeep` which tracks
  97581. * traversed objects.
  97582. *
  97583. * @private
  97584. * @param {*} value The value to clone.
  97585. * @param {boolean} [isDeep] Specify a deep clone.
  97586. * @param {boolean} [isFull] Specify a clone including symbols.
  97587. * @param {Function} [customizer] The function to customize cloning.
  97588. * @param {string} [key] The key of `value`.
  97589. * @param {Object} [object] The parent object of `value`.
  97590. * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
  97591. * @returns {*} Returns the cloned value.
  97592. */
  97593. function baseClone(value, isDeep, isFull, customizer, key, object, stack) {
  97594. var result;
  97595. if (customizer) {
  97596. result = object ? customizer(value, key, object, stack) : customizer(value);
  97597. }
  97598. if (result !== undefined) {
  97599. return result;
  97600. }
  97601. if (!isObject(value)) {
  97602. return value;
  97603. }
  97604. var isArr = isArray(value);
  97605. if (isArr) {
  97606. result = initCloneArray(value);
  97607. if (!isDeep) {
  97608. return copyArray(value, result);
  97609. }
  97610. } else {
  97611. var tag = getTag(value),
  97612. isFunc = tag == funcTag || tag == genTag;
  97613. if (isBuffer(value)) {
  97614. return cloneBuffer(value, isDeep);
  97615. }
  97616. if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
  97617. if (isHostObject(value)) {
  97618. return object ? value : {};
  97619. }
  97620. result = initCloneObject(isFunc ? {} : value);
  97621. if (!isDeep) {
  97622. return copySymbols(value, baseAssign(result, value));
  97623. }
  97624. } else {
  97625. if (!cloneableTags[tag]) {
  97626. return object ? value : {};
  97627. }
  97628. result = initCloneByTag(value, tag, baseClone, isDeep);
  97629. }
  97630. }
  97631. // Check for circular references and return its corresponding clone.
  97632. stack || (stack = new Stack);
  97633. var stacked = stack.get(value);
  97634. if (stacked) {
  97635. return stacked;
  97636. }
  97637. stack.set(value, result);
  97638. if (!isArr) {
  97639. var props = isFull ? getAllKeys(value) : keys(value);
  97640. }
  97641. arrayEach(props || value, function(subValue, key) {
  97642. if (props) {
  97643. key = subValue;
  97644. subValue = value[key];
  97645. }
  97646. // Recursively populate clone (susceptible to call stack limits).
  97647. assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack));
  97648. });
  97649. return result;
  97650. }
  97651. /**
  97652. * The base implementation of `_.create` without support for assigning
  97653. * properties to the created object.
  97654. *
  97655. * @private
  97656. * @param {Object} prototype The object to inherit from.
  97657. * @returns {Object} Returns the new object.
  97658. */
  97659. function baseCreate(proto) {
  97660. return isObject(proto) ? objectCreate(proto) : {};
  97661. }
  97662. /**
  97663. * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
  97664. * `keysFunc` and `symbolsFunc` to get the enumerable property names and
  97665. * symbols of `object`.
  97666. *
  97667. * @private
  97668. * @param {Object} object The object to query.
  97669. * @param {Function} keysFunc The function to get the keys of `object`.
  97670. * @param {Function} symbolsFunc The function to get the symbols of `object`.
  97671. * @returns {Array} Returns the array of property names and symbols.
  97672. */
  97673. function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  97674. var result = keysFunc(object);
  97675. return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
  97676. }
  97677. /**
  97678. * The base implementation of `getTag`.
  97679. *
  97680. * @private
  97681. * @param {*} value The value to query.
  97682. * @returns {string} Returns the `toStringTag`.
  97683. */
  97684. function baseGetTag(value) {
  97685. return objectToString.call(value);
  97686. }
  97687. /**
  97688. * The base implementation of `_.isNative` without bad shim checks.
  97689. *
  97690. * @private
  97691. * @param {*} value The value to check.
  97692. * @returns {boolean} Returns `true` if `value` is a native function,
  97693. * else `false`.
  97694. */
  97695. function baseIsNative(value) {
  97696. if (!isObject(value) || isMasked(value)) {
  97697. return false;
  97698. }
  97699. var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;
  97700. return pattern.test(toSource(value));
  97701. }
  97702. /**
  97703. * The base implementation of `_.isTypedArray` without Node.js optimizations.
  97704. *
  97705. * @private
  97706. * @param {*} value The value to check.
  97707. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  97708. */
  97709. function baseIsTypedArray(value) {
  97710. return isObjectLike(value) &&
  97711. isLength(value.length) && !!typedArrayTags[objectToString.call(value)];
  97712. }
  97713. /**
  97714. * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
  97715. *
  97716. * @private
  97717. * @param {Object} object The object to query.
  97718. * @returns {Array} Returns the array of property names.
  97719. */
  97720. function baseKeys(object) {
  97721. if (!isPrototype(object)) {
  97722. return nativeKeys(object);
  97723. }
  97724. var result = [];
  97725. for (var key in Object(object)) {
  97726. if (hasOwnProperty.call(object, key) && key != 'constructor') {
  97727. result.push(key);
  97728. }
  97729. }
  97730. return result;
  97731. }
  97732. /**
  97733. * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
  97734. *
  97735. * @private
  97736. * @param {Object} object The object to query.
  97737. * @returns {Array} Returns the array of property names.
  97738. */
  97739. function baseKeysIn(object) {
  97740. if (!isObject(object)) {
  97741. return nativeKeysIn(object);
  97742. }
  97743. var isProto = isPrototype(object),
  97744. result = [];
  97745. for (var key in object) {
  97746. if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
  97747. result.push(key);
  97748. }
  97749. }
  97750. return result;
  97751. }
  97752. /**
  97753. * The base implementation of `_.merge` without support for multiple sources.
  97754. *
  97755. * @private
  97756. * @param {Object} object The destination object.
  97757. * @param {Object} source The source object.
  97758. * @param {number} srcIndex The index of `source`.
  97759. * @param {Function} [customizer] The function to customize merged values.
  97760. * @param {Object} [stack] Tracks traversed source values and their merged
  97761. * counterparts.
  97762. */
  97763. function baseMerge(object, source, srcIndex, customizer, stack) {
  97764. if (object === source) {
  97765. return;
  97766. }
  97767. if (!(isArray(source) || isTypedArray(source))) {
  97768. var props = baseKeysIn(source);
  97769. }
  97770. arrayEach(props || source, function(srcValue, key) {
  97771. if (props) {
  97772. key = srcValue;
  97773. srcValue = source[key];
  97774. }
  97775. if (isObject(srcValue)) {
  97776. stack || (stack = new Stack);
  97777. baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
  97778. }
  97779. else {
  97780. var newValue = customizer
  97781. ? customizer(object[key], srcValue, (key + ''), object, source, stack)
  97782. : undefined;
  97783. if (newValue === undefined) {
  97784. newValue = srcValue;
  97785. }
  97786. assignMergeValue(object, key, newValue);
  97787. }
  97788. });
  97789. }
  97790. /**
  97791. * A specialized version of `baseMerge` for arrays and objects which performs
  97792. * deep merges and tracks traversed objects enabling objects with circular
  97793. * references to be merged.
  97794. *
  97795. * @private
  97796. * @param {Object} object The destination object.
  97797. * @param {Object} source The source object.
  97798. * @param {string} key The key of the value to merge.
  97799. * @param {number} srcIndex The index of `source`.
  97800. * @param {Function} mergeFunc The function to merge values.
  97801. * @param {Function} [customizer] The function to customize assigned values.
  97802. * @param {Object} [stack] Tracks traversed source values and their merged
  97803. * counterparts.
  97804. */
  97805. function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
  97806. var objValue = object[key],
  97807. srcValue = source[key],
  97808. stacked = stack.get(srcValue);
  97809. if (stacked) {
  97810. assignMergeValue(object, key, stacked);
  97811. return;
  97812. }
  97813. var newValue = customizer
  97814. ? customizer(objValue, srcValue, (key + ''), object, source, stack)
  97815. : undefined;
  97816. var isCommon = newValue === undefined;
  97817. if (isCommon) {
  97818. newValue = srcValue;
  97819. if (isArray(srcValue) || isTypedArray(srcValue)) {
  97820. if (isArray(objValue)) {
  97821. newValue = objValue;
  97822. }
  97823. else if (isArrayLikeObject(objValue)) {
  97824. newValue = copyArray(objValue);
  97825. }
  97826. else {
  97827. isCommon = false;
  97828. newValue = baseClone(srcValue, true);
  97829. }
  97830. }
  97831. else if (isPlainObject(srcValue) || isArguments(srcValue)) {
  97832. if (isArguments(objValue)) {
  97833. newValue = toPlainObject(objValue);
  97834. }
  97835. else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) {
  97836. isCommon = false;
  97837. newValue = baseClone(srcValue, true);
  97838. }
  97839. else {
  97840. newValue = objValue;
  97841. }
  97842. }
  97843. else {
  97844. isCommon = false;
  97845. }
  97846. }
  97847. if (isCommon) {
  97848. // Recursively merge objects and arrays (susceptible to call stack limits).
  97849. stack.set(srcValue, newValue);
  97850. mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
  97851. stack['delete'](srcValue);
  97852. }
  97853. assignMergeValue(object, key, newValue);
  97854. }
  97855. /**
  97856. * The base implementation of `_.rest` which doesn't validate or coerce arguments.
  97857. *
  97858. * @private
  97859. * @param {Function} func The function to apply a rest parameter to.
  97860. * @param {number} [start=func.length-1] The start position of the rest parameter.
  97861. * @returns {Function} Returns the new function.
  97862. */
  97863. function baseRest(func, start) {
  97864. start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
  97865. return function() {
  97866. var args = arguments,
  97867. index = -1,
  97868. length = nativeMax(args.length - start, 0),
  97869. array = Array(length);
  97870. while (++index < length) {
  97871. array[index] = args[start + index];
  97872. }
  97873. index = -1;
  97874. var otherArgs = Array(start + 1);
  97875. while (++index < start) {
  97876. otherArgs[index] = args[index];
  97877. }
  97878. otherArgs[start] = array;
  97879. return apply(func, this, otherArgs);
  97880. };
  97881. }
  97882. /**
  97883. * Creates a clone of `buffer`.
  97884. *
  97885. * @private
  97886. * @param {Buffer} buffer The buffer to clone.
  97887. * @param {boolean} [isDeep] Specify a deep clone.
  97888. * @returns {Buffer} Returns the cloned buffer.
  97889. */
  97890. function cloneBuffer(buffer, isDeep) {
  97891. if (isDeep) {
  97892. return buffer.slice();
  97893. }
  97894. var result = new buffer.constructor(buffer.length);
  97895. buffer.copy(result);
  97896. return result;
  97897. }
  97898. /**
  97899. * Creates a clone of `arrayBuffer`.
  97900. *
  97901. * @private
  97902. * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
  97903. * @returns {ArrayBuffer} Returns the cloned array buffer.
  97904. */
  97905. function cloneArrayBuffer(arrayBuffer) {
  97906. var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
  97907. new Uint8Array(result).set(new Uint8Array(arrayBuffer));
  97908. return result;
  97909. }
  97910. /**
  97911. * Creates a clone of `dataView`.
  97912. *
  97913. * @private
  97914. * @param {Object} dataView The data view to clone.
  97915. * @param {boolean} [isDeep] Specify a deep clone.
  97916. * @returns {Object} Returns the cloned data view.
  97917. */
  97918. function cloneDataView(dataView, isDeep) {
  97919. var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
  97920. return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
  97921. }
  97922. /**
  97923. * Creates a clone of `map`.
  97924. *
  97925. * @private
  97926. * @param {Object} map The map to clone.
  97927. * @param {Function} cloneFunc The function to clone values.
  97928. * @param {boolean} [isDeep] Specify a deep clone.
  97929. * @returns {Object} Returns the cloned map.
  97930. */
  97931. function cloneMap(map, isDeep, cloneFunc) {
  97932. var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map);
  97933. return arrayReduce(array, addMapEntry, new map.constructor);
  97934. }
  97935. /**
  97936. * Creates a clone of `regexp`.
  97937. *
  97938. * @private
  97939. * @param {Object} regexp The regexp to clone.
  97940. * @returns {Object} Returns the cloned regexp.
  97941. */
  97942. function cloneRegExp(regexp) {
  97943. var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
  97944. result.lastIndex = regexp.lastIndex;
  97945. return result;
  97946. }
  97947. /**
  97948. * Creates a clone of `set`.
  97949. *
  97950. * @private
  97951. * @param {Object} set The set to clone.
  97952. * @param {Function} cloneFunc The function to clone values.
  97953. * @param {boolean} [isDeep] Specify a deep clone.
  97954. * @returns {Object} Returns the cloned set.
  97955. */
  97956. function cloneSet(set, isDeep, cloneFunc) {
  97957. var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set);
  97958. return arrayReduce(array, addSetEntry, new set.constructor);
  97959. }
  97960. /**
  97961. * Creates a clone of the `symbol` object.
  97962. *
  97963. * @private
  97964. * @param {Object} symbol The symbol object to clone.
  97965. * @returns {Object} Returns the cloned symbol object.
  97966. */
  97967. function cloneSymbol(symbol) {
  97968. return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
  97969. }
  97970. /**
  97971. * Creates a clone of `typedArray`.
  97972. *
  97973. * @private
  97974. * @param {Object} typedArray The typed array to clone.
  97975. * @param {boolean} [isDeep] Specify a deep clone.
  97976. * @returns {Object} Returns the cloned typed array.
  97977. */
  97978. function cloneTypedArray(typedArray, isDeep) {
  97979. var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
  97980. return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
  97981. }
  97982. /**
  97983. * Copies the values of `source` to `array`.
  97984. *
  97985. * @private
  97986. * @param {Array} source The array to copy values from.
  97987. * @param {Array} [array=[]] The array to copy values to.
  97988. * @returns {Array} Returns `array`.
  97989. */
  97990. function copyArray(source, array) {
  97991. var index = -1,
  97992. length = source.length;
  97993. array || (array = Array(length));
  97994. while (++index < length) {
  97995. array[index] = source[index];
  97996. }
  97997. return array;
  97998. }
  97999. /**
  98000. * Copies properties of `source` to `object`.
  98001. *
  98002. * @private
  98003. * @param {Object} source The object to copy properties from.
  98004. * @param {Array} props The property identifiers to copy.
  98005. * @param {Object} [object={}] The object to copy properties to.
  98006. * @param {Function} [customizer] The function to customize copied values.
  98007. * @returns {Object} Returns `object`.
  98008. */
  98009. function copyObject(source, props, object, customizer) {
  98010. object || (object = {});
  98011. var index = -1,
  98012. length = props.length;
  98013. while (++index < length) {
  98014. var key = props[index];
  98015. var newValue = customizer
  98016. ? customizer(object[key], source[key], key, object, source)
  98017. : undefined;
  98018. assignValue(object, key, newValue === undefined ? source[key] : newValue);
  98019. }
  98020. return object;
  98021. }
  98022. /**
  98023. * Copies own symbol properties of `source` to `object`.
  98024. *
  98025. * @private
  98026. * @param {Object} source The object to copy symbols from.
  98027. * @param {Object} [object={}] The object to copy symbols to.
  98028. * @returns {Object} Returns `object`.
  98029. */
  98030. function copySymbols(source, object) {
  98031. return copyObject(source, getSymbols(source), object);
  98032. }
  98033. /**
  98034. * Creates a function like `_.assign`.
  98035. *
  98036. * @private
  98037. * @param {Function} assigner The function to assign values.
  98038. * @returns {Function} Returns the new assigner function.
  98039. */
  98040. function createAssigner(assigner) {
  98041. return baseRest(function(object, sources) {
  98042. var index = -1,
  98043. length = sources.length,
  98044. customizer = length > 1 ? sources[length - 1] : undefined,
  98045. guard = length > 2 ? sources[2] : undefined;
  98046. customizer = (assigner.length > 3 && typeof customizer == 'function')
  98047. ? (length--, customizer)
  98048. : undefined;
  98049. if (guard && isIterateeCall(sources[0], sources[1], guard)) {
  98050. customizer = length < 3 ? undefined : customizer;
  98051. length = 1;
  98052. }
  98053. object = Object(object);
  98054. while (++index < length) {
  98055. var source = sources[index];
  98056. if (source) {
  98057. assigner(object, source, index, customizer);
  98058. }
  98059. }
  98060. return object;
  98061. });
  98062. }
  98063. /**
  98064. * Creates an array of own enumerable property names and symbols of `object`.
  98065. *
  98066. * @private
  98067. * @param {Object} object The object to query.
  98068. * @returns {Array} Returns the array of property names and symbols.
  98069. */
  98070. function getAllKeys(object) {
  98071. return baseGetAllKeys(object, keys, getSymbols);
  98072. }
  98073. /**
  98074. * Gets the data for `map`.
  98075. *
  98076. * @private
  98077. * @param {Object} map The map to query.
  98078. * @param {string} key The reference key.
  98079. * @returns {*} Returns the map data.
  98080. */
  98081. function getMapData(map, key) {
  98082. var data = map.__data__;
  98083. return isKeyable(key)
  98084. ? data[typeof key == 'string' ? 'string' : 'hash']
  98085. : data.map;
  98086. }
  98087. /**
  98088. * Gets the native function at `key` of `object`.
  98089. *
  98090. * @private
  98091. * @param {Object} object The object to query.
  98092. * @param {string} key The key of the method to get.
  98093. * @returns {*} Returns the function if it's native, else `undefined`.
  98094. */
  98095. function getNative(object, key) {
  98096. var value = getValue(object, key);
  98097. return baseIsNative(value) ? value : undefined;
  98098. }
  98099. /**
  98100. * Creates an array of the own enumerable symbol properties of `object`.
  98101. *
  98102. * @private
  98103. * @param {Object} object The object to query.
  98104. * @returns {Array} Returns the array of symbols.
  98105. */
  98106. var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray;
  98107. /**
  98108. * Gets the `toStringTag` of `value`.
  98109. *
  98110. * @private
  98111. * @param {*} value The value to query.
  98112. * @returns {string} Returns the `toStringTag`.
  98113. */
  98114. var getTag = baseGetTag;
  98115. // Fallback for data views, maps, sets, and weak maps in IE 11,
  98116. // for data views in Edge < 14, and promises in Node.js.
  98117. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
  98118. (Map && getTag(new Map) != mapTag) ||
  98119. (Promise && getTag(Promise.resolve()) != promiseTag) ||
  98120. (Set && getTag(new Set) != setTag) ||
  98121. (WeakMap && getTag(new WeakMap) != weakMapTag)) {
  98122. getTag = function(value) {
  98123. var result = objectToString.call(value),
  98124. Ctor = result == objectTag ? value.constructor : undefined,
  98125. ctorString = Ctor ? toSource(Ctor) : undefined;
  98126. if (ctorString) {
  98127. switch (ctorString) {
  98128. case dataViewCtorString: return dataViewTag;
  98129. case mapCtorString: return mapTag;
  98130. case promiseCtorString: return promiseTag;
  98131. case setCtorString: return setTag;
  98132. case weakMapCtorString: return weakMapTag;
  98133. }
  98134. }
  98135. return result;
  98136. };
  98137. }
  98138. /**
  98139. * Initializes an array clone.
  98140. *
  98141. * @private
  98142. * @param {Array} array The array to clone.
  98143. * @returns {Array} Returns the initialized clone.
  98144. */
  98145. function initCloneArray(array) {
  98146. var length = array.length,
  98147. result = array.constructor(length);
  98148. // Add properties assigned by `RegExp#exec`.
  98149. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
  98150. result.index = array.index;
  98151. result.input = array.input;
  98152. }
  98153. return result;
  98154. }
  98155. /**
  98156. * Initializes an object clone.
  98157. *
  98158. * @private
  98159. * @param {Object} object The object to clone.
  98160. * @returns {Object} Returns the initialized clone.
  98161. */
  98162. function initCloneObject(object) {
  98163. return (typeof object.constructor == 'function' && !isPrototype(object))
  98164. ? baseCreate(getPrototype(object))
  98165. : {};
  98166. }
  98167. /**
  98168. * Initializes an object clone based on its `toStringTag`.
  98169. *
  98170. * **Note:** This function only supports cloning values with tags of
  98171. * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
  98172. *
  98173. * @private
  98174. * @param {Object} object The object to clone.
  98175. * @param {string} tag The `toStringTag` of the object to clone.
  98176. * @param {Function} cloneFunc The function to clone values.
  98177. * @param {boolean} [isDeep] Specify a deep clone.
  98178. * @returns {Object} Returns the initialized clone.
  98179. */
  98180. function initCloneByTag(object, tag, cloneFunc, isDeep) {
  98181. var Ctor = object.constructor;
  98182. switch (tag) {
  98183. case arrayBufferTag:
  98184. return cloneArrayBuffer(object);
  98185. case boolTag:
  98186. case dateTag:
  98187. return new Ctor(+object);
  98188. case dataViewTag:
  98189. return cloneDataView(object, isDeep);
  98190. case float32Tag: case float64Tag:
  98191. case int8Tag: case int16Tag: case int32Tag:
  98192. case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
  98193. return cloneTypedArray(object, isDeep);
  98194. case mapTag:
  98195. return cloneMap(object, isDeep, cloneFunc);
  98196. case numberTag:
  98197. case stringTag:
  98198. return new Ctor(object);
  98199. case regexpTag:
  98200. return cloneRegExp(object);
  98201. case setTag:
  98202. return cloneSet(object, isDeep, cloneFunc);
  98203. case symbolTag:
  98204. return cloneSymbol(object);
  98205. }
  98206. }
  98207. /**
  98208. * Checks if `value` is a valid array-like index.
  98209. *
  98210. * @private
  98211. * @param {*} value The value to check.
  98212. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  98213. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  98214. */
  98215. function isIndex(value, length) {
  98216. length = length == null ? MAX_SAFE_INTEGER : length;
  98217. return !!length &&
  98218. (typeof value == 'number' || reIsUint.test(value)) &&
  98219. (value > -1 && value % 1 == 0 && value < length);
  98220. }
  98221. /**
  98222. * Checks if the given arguments are from an iteratee call.
  98223. *
  98224. * @private
  98225. * @param {*} value The potential iteratee value argument.
  98226. * @param {*} index The potential iteratee index or key argument.
  98227. * @param {*} object The potential iteratee object argument.
  98228. * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
  98229. * else `false`.
  98230. */
  98231. function isIterateeCall(value, index, object) {
  98232. if (!isObject(object)) {
  98233. return false;
  98234. }
  98235. var type = typeof index;
  98236. if (type == 'number'
  98237. ? (isArrayLike(object) && isIndex(index, object.length))
  98238. : (type == 'string' && index in object)
  98239. ) {
  98240. return eq(object[index], value);
  98241. }
  98242. return false;
  98243. }
  98244. /**
  98245. * Checks if `value` is suitable for use as unique object key.
  98246. *
  98247. * @private
  98248. * @param {*} value The value to check.
  98249. * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
  98250. */
  98251. function isKeyable(value) {
  98252. var type = typeof value;
  98253. return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
  98254. ? (value !== '__proto__')
  98255. : (value === null);
  98256. }
  98257. /**
  98258. * Checks if `func` has its source masked.
  98259. *
  98260. * @private
  98261. * @param {Function} func The function to check.
  98262. * @returns {boolean} Returns `true` if `func` is masked, else `false`.
  98263. */
  98264. function isMasked(func) {
  98265. return !!maskSrcKey && (maskSrcKey in func);
  98266. }
  98267. /**
  98268. * Checks if `value` is likely a prototype object.
  98269. *
  98270. * @private
  98271. * @param {*} value The value to check.
  98272. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
  98273. */
  98274. function isPrototype(value) {
  98275. var Ctor = value && value.constructor,
  98276. proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
  98277. return value === proto;
  98278. }
  98279. /**
  98280. * This function is like
  98281. * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  98282. * except that it includes inherited enumerable properties.
  98283. *
  98284. * @private
  98285. * @param {Object} object The object to query.
  98286. * @returns {Array} Returns the array of property names.
  98287. */
  98288. function nativeKeysIn(object) {
  98289. var result = [];
  98290. if (object != null) {
  98291. for (var key in Object(object)) {
  98292. result.push(key);
  98293. }
  98294. }
  98295. return result;
  98296. }
  98297. /**
  98298. * Converts `func` to its source code.
  98299. *
  98300. * @private
  98301. * @param {Function} func The function to process.
  98302. * @returns {string} Returns the source code.
  98303. */
  98304. function toSource(func) {
  98305. if (func != null) {
  98306. try {
  98307. return funcToString.call(func);
  98308. } catch (e) {}
  98309. try {
  98310. return (func + '');
  98311. } catch (e) {}
  98312. }
  98313. return '';
  98314. }
  98315. /**
  98316. * Performs a
  98317. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  98318. * comparison between two values to determine if they are equivalent.
  98319. *
  98320. * @static
  98321. * @memberOf _
  98322. * @since 4.0.0
  98323. * @category Lang
  98324. * @param {*} value The value to compare.
  98325. * @param {*} other The other value to compare.
  98326. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  98327. * @example
  98328. *
  98329. * var object = { 'a': 1 };
  98330. * var other = { 'a': 1 };
  98331. *
  98332. * _.eq(object, object);
  98333. * // => true
  98334. *
  98335. * _.eq(object, other);
  98336. * // => false
  98337. *
  98338. * _.eq('a', 'a');
  98339. * // => true
  98340. *
  98341. * _.eq('a', Object('a'));
  98342. * // => false
  98343. *
  98344. * _.eq(NaN, NaN);
  98345. * // => true
  98346. */
  98347. function eq(value, other) {
  98348. return value === other || (value !== value && other !== other);
  98349. }
  98350. /**
  98351. * Checks if `value` is likely an `arguments` object.
  98352. *
  98353. * @static
  98354. * @memberOf _
  98355. * @since 0.1.0
  98356. * @category Lang
  98357. * @param {*} value The value to check.
  98358. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  98359. * else `false`.
  98360. * @example
  98361. *
  98362. * _.isArguments(function() { return arguments; }());
  98363. * // => true
  98364. *
  98365. * _.isArguments([1, 2, 3]);
  98366. * // => false
  98367. */
  98368. function isArguments(value) {
  98369. // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
  98370. return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
  98371. (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
  98372. }
  98373. /**
  98374. * Checks if `value` is classified as an `Array` object.
  98375. *
  98376. * @static
  98377. * @memberOf _
  98378. * @since 0.1.0
  98379. * @category Lang
  98380. * @param {*} value The value to check.
  98381. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  98382. * @example
  98383. *
  98384. * _.isArray([1, 2, 3]);
  98385. * // => true
  98386. *
  98387. * _.isArray(document.body.children);
  98388. * // => false
  98389. *
  98390. * _.isArray('abc');
  98391. * // => false
  98392. *
  98393. * _.isArray(_.noop);
  98394. * // => false
  98395. */
  98396. var isArray = Array.isArray;
  98397. /**
  98398. * Checks if `value` is array-like. A value is considered array-like if it's
  98399. * not a function and has a `value.length` that's an integer greater than or
  98400. * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
  98401. *
  98402. * @static
  98403. * @memberOf _
  98404. * @since 4.0.0
  98405. * @category Lang
  98406. * @param {*} value The value to check.
  98407. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  98408. * @example
  98409. *
  98410. * _.isArrayLike([1, 2, 3]);
  98411. * // => true
  98412. *
  98413. * _.isArrayLike(document.body.children);
  98414. * // => true
  98415. *
  98416. * _.isArrayLike('abc');
  98417. * // => true
  98418. *
  98419. * _.isArrayLike(_.noop);
  98420. * // => false
  98421. */
  98422. function isArrayLike(value) {
  98423. return value != null && isLength(value.length) && !isFunction(value);
  98424. }
  98425. /**
  98426. * This method is like `_.isArrayLike` except that it also checks if `value`
  98427. * is an object.
  98428. *
  98429. * @static
  98430. * @memberOf _
  98431. * @since 4.0.0
  98432. * @category Lang
  98433. * @param {*} value The value to check.
  98434. * @returns {boolean} Returns `true` if `value` is an array-like object,
  98435. * else `false`.
  98436. * @example
  98437. *
  98438. * _.isArrayLikeObject([1, 2, 3]);
  98439. * // => true
  98440. *
  98441. * _.isArrayLikeObject(document.body.children);
  98442. * // => true
  98443. *
  98444. * _.isArrayLikeObject('abc');
  98445. * // => false
  98446. *
  98447. * _.isArrayLikeObject(_.noop);
  98448. * // => false
  98449. */
  98450. function isArrayLikeObject(value) {
  98451. return isObjectLike(value) && isArrayLike(value);
  98452. }
  98453. /**
  98454. * Checks if `value` is a buffer.
  98455. *
  98456. * @static
  98457. * @memberOf _
  98458. * @since 4.3.0
  98459. * @category Lang
  98460. * @param {*} value The value to check.
  98461. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
  98462. * @example
  98463. *
  98464. * _.isBuffer(new Buffer(2));
  98465. * // => true
  98466. *
  98467. * _.isBuffer(new Uint8Array(2));
  98468. * // => false
  98469. */
  98470. var isBuffer = nativeIsBuffer || stubFalse;
  98471. /**
  98472. * Checks if `value` is classified as a `Function` object.
  98473. *
  98474. * @static
  98475. * @memberOf _
  98476. * @since 0.1.0
  98477. * @category Lang
  98478. * @param {*} value The value to check.
  98479. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  98480. * @example
  98481. *
  98482. * _.isFunction(_);
  98483. * // => true
  98484. *
  98485. * _.isFunction(/abc/);
  98486. * // => false
  98487. */
  98488. function isFunction(value) {
  98489. // The use of `Object#toString` avoids issues with the `typeof` operator
  98490. // in Safari 8-9 which returns 'object' for typed array and other constructors.
  98491. var tag = isObject(value) ? objectToString.call(value) : '';
  98492. return tag == funcTag || tag == genTag;
  98493. }
  98494. /**
  98495. * Checks if `value` is a valid array-like length.
  98496. *
  98497. * **Note:** This method is loosely based on
  98498. * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
  98499. *
  98500. * @static
  98501. * @memberOf _
  98502. * @since 4.0.0
  98503. * @category Lang
  98504. * @param {*} value The value to check.
  98505. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  98506. * @example
  98507. *
  98508. * _.isLength(3);
  98509. * // => true
  98510. *
  98511. * _.isLength(Number.MIN_VALUE);
  98512. * // => false
  98513. *
  98514. * _.isLength(Infinity);
  98515. * // => false
  98516. *
  98517. * _.isLength('3');
  98518. * // => false
  98519. */
  98520. function isLength(value) {
  98521. return typeof value == 'number' &&
  98522. value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  98523. }
  98524. /**
  98525. * Checks if `value` is the
  98526. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  98527. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  98528. *
  98529. * @static
  98530. * @memberOf _
  98531. * @since 0.1.0
  98532. * @category Lang
  98533. * @param {*} value The value to check.
  98534. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  98535. * @example
  98536. *
  98537. * _.isObject({});
  98538. * // => true
  98539. *
  98540. * _.isObject([1, 2, 3]);
  98541. * // => true
  98542. *
  98543. * _.isObject(_.noop);
  98544. * // => true
  98545. *
  98546. * _.isObject(null);
  98547. * // => false
  98548. */
  98549. function isObject(value) {
  98550. var type = typeof value;
  98551. return !!value && (type == 'object' || type == 'function');
  98552. }
  98553. /**
  98554. * Checks if `value` is object-like. A value is object-like if it's not `null`
  98555. * and has a `typeof` result of "object".
  98556. *
  98557. * @static
  98558. * @memberOf _
  98559. * @since 4.0.0
  98560. * @category Lang
  98561. * @param {*} value The value to check.
  98562. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  98563. * @example
  98564. *
  98565. * _.isObjectLike({});
  98566. * // => true
  98567. *
  98568. * _.isObjectLike([1, 2, 3]);
  98569. * // => true
  98570. *
  98571. * _.isObjectLike(_.noop);
  98572. * // => false
  98573. *
  98574. * _.isObjectLike(null);
  98575. * // => false
  98576. */
  98577. function isObjectLike(value) {
  98578. return !!value && typeof value == 'object';
  98579. }
  98580. /**
  98581. * Checks if `value` is a plain object, that is, an object created by the
  98582. * `Object` constructor or one with a `[[Prototype]]` of `null`.
  98583. *
  98584. * @static
  98585. * @memberOf _
  98586. * @since 0.8.0
  98587. * @category Lang
  98588. * @param {*} value The value to check.
  98589. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
  98590. * @example
  98591. *
  98592. * function Foo() {
  98593. * this.a = 1;
  98594. * }
  98595. *
  98596. * _.isPlainObject(new Foo);
  98597. * // => false
  98598. *
  98599. * _.isPlainObject([1, 2, 3]);
  98600. * // => false
  98601. *
  98602. * _.isPlainObject({ 'x': 0, 'y': 0 });
  98603. * // => true
  98604. *
  98605. * _.isPlainObject(Object.create(null));
  98606. * // => true
  98607. */
  98608. function isPlainObject(value) {
  98609. if (!isObjectLike(value) ||
  98610. objectToString.call(value) != objectTag || isHostObject(value)) {
  98611. return false;
  98612. }
  98613. var proto = getPrototype(value);
  98614. if (proto === null) {
  98615. return true;
  98616. }
  98617. var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
  98618. return (typeof Ctor == 'function' &&
  98619. Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
  98620. }
  98621. /**
  98622. * Checks if `value` is classified as a typed array.
  98623. *
  98624. * @static
  98625. * @memberOf _
  98626. * @since 3.0.0
  98627. * @category Lang
  98628. * @param {*} value The value to check.
  98629. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  98630. * @example
  98631. *
  98632. * _.isTypedArray(new Uint8Array);
  98633. * // => true
  98634. *
  98635. * _.isTypedArray([]);
  98636. * // => false
  98637. */
  98638. var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
  98639. /**
  98640. * Converts `value` to a plain object flattening inherited enumerable string
  98641. * keyed properties of `value` to own properties of the plain object.
  98642. *
  98643. * @static
  98644. * @memberOf _
  98645. * @since 3.0.0
  98646. * @category Lang
  98647. * @param {*} value The value to convert.
  98648. * @returns {Object} Returns the converted plain object.
  98649. * @example
  98650. *
  98651. * function Foo() {
  98652. * this.b = 2;
  98653. * }
  98654. *
  98655. * Foo.prototype.c = 3;
  98656. *
  98657. * _.assign({ 'a': 1 }, new Foo);
  98658. * // => { 'a': 1, 'b': 2 }
  98659. *
  98660. * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
  98661. * // => { 'a': 1, 'b': 2, 'c': 3 }
  98662. */
  98663. function toPlainObject(value) {
  98664. return copyObject(value, keysIn(value));
  98665. }
  98666. /**
  98667. * Creates an array of the own enumerable property names of `object`.
  98668. *
  98669. * **Note:** Non-object values are coerced to objects. See the
  98670. * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  98671. * for more details.
  98672. *
  98673. * @static
  98674. * @since 0.1.0
  98675. * @memberOf _
  98676. * @category Object
  98677. * @param {Object} object The object to query.
  98678. * @returns {Array} Returns the array of property names.
  98679. * @example
  98680. *
  98681. * function Foo() {
  98682. * this.a = 1;
  98683. * this.b = 2;
  98684. * }
  98685. *
  98686. * Foo.prototype.c = 3;
  98687. *
  98688. * _.keys(new Foo);
  98689. * // => ['a', 'b'] (iteration order is not guaranteed)
  98690. *
  98691. * _.keys('hi');
  98692. * // => ['0', '1']
  98693. */
  98694. function keys(object) {
  98695. return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
  98696. }
  98697. /**
  98698. * Creates an array of the own and inherited enumerable property names of `object`.
  98699. *
  98700. * **Note:** Non-object values are coerced to objects.
  98701. *
  98702. * @static
  98703. * @memberOf _
  98704. * @since 3.0.0
  98705. * @category Object
  98706. * @param {Object} object The object to query.
  98707. * @returns {Array} Returns the array of property names.
  98708. * @example
  98709. *
  98710. * function Foo() {
  98711. * this.a = 1;
  98712. * this.b = 2;
  98713. * }
  98714. *
  98715. * Foo.prototype.c = 3;
  98716. *
  98717. * _.keysIn(new Foo);
  98718. * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
  98719. */
  98720. function keysIn(object) {
  98721. return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
  98722. }
  98723. /**
  98724. * This method is like `_.assign` except that it recursively merges own and
  98725. * inherited enumerable string keyed properties of source objects into the
  98726. * destination object. Source properties that resolve to `undefined` are
  98727. * skipped if a destination value exists. Array and plain object properties
  98728. * are merged recursively. Other objects and value types are overridden by
  98729. * assignment. Source objects are applied from left to right. Subsequent
  98730. * sources overwrite property assignments of previous sources.
  98731. *
  98732. * **Note:** This method mutates `object`.
  98733. *
  98734. * @static
  98735. * @memberOf _
  98736. * @since 0.5.0
  98737. * @category Object
  98738. * @param {Object} object The destination object.
  98739. * @param {...Object} [sources] The source objects.
  98740. * @returns {Object} Returns `object`.
  98741. * @example
  98742. *
  98743. * var object = {
  98744. * 'a': [{ 'b': 2 }, { 'd': 4 }]
  98745. * };
  98746. *
  98747. * var other = {
  98748. * 'a': [{ 'c': 3 }, { 'e': 5 }]
  98749. * };
  98750. *
  98751. * _.merge(object, other);
  98752. * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
  98753. */
  98754. var merge = createAssigner(function(object, source, srcIndex) {
  98755. baseMerge(object, source, srcIndex);
  98756. });
  98757. /**
  98758. * This method returns a new empty array.
  98759. *
  98760. * @static
  98761. * @memberOf _
  98762. * @since 4.13.0
  98763. * @category Util
  98764. * @returns {Array} Returns the new empty array.
  98765. * @example
  98766. *
  98767. * var arrays = _.times(2, _.stubArray);
  98768. *
  98769. * console.log(arrays);
  98770. * // => [[], []]
  98771. *
  98772. * console.log(arrays[0] === arrays[1]);
  98773. * // => false
  98774. */
  98775. function stubArray() {
  98776. return [];
  98777. }
  98778. /**
  98779. * This method returns `false`.
  98780. *
  98781. * @static
  98782. * @memberOf _
  98783. * @since 4.13.0
  98784. * @category Util
  98785. * @returns {boolean} Returns `false`.
  98786. * @example
  98787. *
  98788. * _.times(2, _.stubFalse);
  98789. * // => [false, false]
  98790. */
  98791. function stubFalse() {
  98792. return false;
  98793. }
  98794. module.exports = merge;
  98795. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(19)(module)))
  98796. /***/ }),
  98797. /* 19 */
  98798. /***/ (function(module, exports) {
  98799. module.exports = function(module) {
  98800. if(!module.webpackPolyfill) {
  98801. module.deprecate = function() {};
  98802. module.paths = [];
  98803. // module.parent = undefined by default
  98804. if(!module.children) module.children = [];
  98805. Object.defineProperty(module, "loaded", {
  98806. enumerable: true,
  98807. get: function() {
  98808. return module.l;
  98809. }
  98810. });
  98811. Object.defineProperty(module, "id", {
  98812. enumerable: true,
  98813. get: function() {
  98814. return module.i;
  98815. }
  98816. });
  98817. module.webpackPolyfill = 1;
  98818. }
  98819. return module;
  98820. };
  98821. /***/ }),
  98822. /* 20 */
  98823. /***/ (function(module, exports, __webpack_require__) {
  98824. var babylonDependency;try{babylonDependency=BABYLON||"undefined"!="function"&&__webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"../babylon.max\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()))}catch(e){babylonDependency=BABYLON||"undefined"!="function"&&__webpack_require__(0)}var BABYLON=babylonDependency,__decorate=this&&this.__decorate||function(e,t,r,n){var a,o=arguments.length,i=o<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--)(a=e[s])&&(i=(o<3?a(i):o>3?a(t,r,i):a(t,r))||i);return o>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,a,o,i,s){var l;if(this.isBinary(n)){var u=new e.Mesh("stlmesh",r);return this.parseBinary(u,n),o&&o.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]),o&&o.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,a=0;a<n;a++)if(r.getUint8(a)>127)return!0;return!1},t.prototype.parseBinary=function(t,r){for(var n=new DataView(r),a=n.getUint32(80,!0),o=0,i=new Float32Array(3*a*3),s=new Float32Array(3*a*3),l=new Uint32Array(3*a),u=0,c=0;c<a;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 T=f+12*m;i[o]=n.getFloat32(T,!0),i[o+2]=n.getFloat32(T+4,!0),i[o+1]=n.getFloat32(T+8,!0),s[o]=d,s[o+2]=h,s[o+1]=p,o+=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,a=[],o=[],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);)a.push(Number(c[1]),Number(c[5]),Number(c[3])),o.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,a),t.setVerticesData(e.VertexBuffer.NormalKind,o),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,a){for(var o,i,s=n.split("\n"),l=/\s+/,u=0;u<s.length;u++){var c=s[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?(i&&this.materials.push(i),i=new e.StandardMaterial(h,r)):"kd"===d?(o=h.split(l,3).map(parseFloat),i.diffuseColor=e.Color3.FromArray(o)):"ka"===d?(o=h.split(l,3).map(parseFloat),i.ambientColor=e.Color3.FromArray(o)):"ks"===d?(o=h.split(l,3).map(parseFloat),i.specularColor=e.Color3.FromArray(o)):"ke"===d?(o=h.split(l,3).map(parseFloat),i.emissiveColor=e.Color3.FromArray(o)):"ns"===d?i.specularPower=parseFloat(h):"d"===d?i.alpha=parseFloat(h):"map_ka"===d?i.ambientTexture=t._getTexture(a,h,r):"map_kd"===d?i.diffuseTexture=t._getTexture(a,h,r):"map_ks"===d?i.specularTexture=t._getTexture(a,h,r):"map_ns"===d||("map_bump"===d?i.bumpTexture=t._getTexture(a,h,r):"map_d"===d&&(i.opacityTexture=t._getTexture(a,h,r)))}}this.materials.push(i)},t._getTexture=function(t,r,n){if(!r)return null;var a=t;if("file:"===t){var o=r.lastIndexOf("\\");-1===o&&(o=r.lastIndexOf("/")),a+=o>-1?r.substr(o+1):r}else a+=r;return new e.Texture(a,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 a=e.Tools.BaseUrl+r+t;e.Tools.LoadFile(a,n,null,null,!1,(function(){console.warn("Error - Unable to load "+a)}))},r.prototype.importMesh=function(e,t,r,n,a,o,i){var s=this._parseSolid(e,t,r,n);return a&&s.forEach((function(e){a.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,a,o,i){for(var s,l=[],u=[],c=[],f=[],d=[],h=[],p=[],m=[],T=[],E=0,A=!1,_=[],y=[],g=[],v=[],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},I=function(e,t,n,a,o,i){var s;s=r.OPTIMIZE_WITH_UV?F(T,[e,n,t]):O(T,[e,n]),-1==s?(d.push(h.length),h.push(a),p.push(o),m.push(i),T[e].normals.push(n),T[e].idx.push(E++),r.OPTIMIZE_WITH_UV&&T[e].uv.push(t)):d.push(s)},S=function(){for(var e=0;e<h.length;e++)_.push(h[e].x,h[e].y,h[e].z),y.push(m[e].x,m[e].y,m[e].z),g.push(p[e].x,p[e].y);h=[],m=[],p=[],T=[],E=0},R=function(e,t){t+1<e.length&&(v.push(e[0],e[t],e[t+1]),t+=1,R(e,t))},w=function(){f.length>0&&(s=f[f.length-1],S(),d.reverse(),s.indices=d.slice(),s.positions=_.slice(),s.normals=y.slice(),s.uvs=g.slice(),d=[],_=[],y=[],g=[])},B=o.split("\n"),P=0;P<B.length;P++){var C,G=B[P].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){R(e,t);for(var r=0;r<v.length;r++){var n=v[r].split("/"),a=parseInt(n[0])-1,o=parseInt(n[1])-1,i=parseInt(n[2])-1;I(a,o,i,l[a],c[o],u[i])}v=[]})(C[1].trim().split(" "),1);else if(null!==(C=this.facePattern4.exec(G)))!(function(t,r){R(t,r);for(var n=0;n<v.length;n++){var a=v[n].split("//"),o=parseInt(a[0])-1,i=parseInt(a[1])-1;I(o,1,i,l[o],e.Vector2.Zero(),u[i])}v=[]})(C[1].trim().split(" "),1);else if(null!==(C=this.facePattern2.exec(G)))!(function(t,r){R(t,r);for(var n=0;n<v.length;n++){var a=v[n].split("/"),o=parseInt(a[0])-1,i=parseInt(a[1])-1;I(o,i,0,l[o],c[i],e.Vector3.Up())}v=[]})(C[1].trim().split(" "),1);else if(null!==(C=this.facePattern1.exec(G)))!(function(t,r){R(t,r);for(var n=0;n<v.length;n++){var a=parseInt(v[n])-1;I(a,0,0,l[a],e.Vector2.Zero(),e.Vector3.Up())}v=[]})(C[1].trim().split(" "),1);else if(this.group.test(G)||this.obj.test(G)){var D={name:G.substring(2).trim(),indices:void 0,positions:void 0,normals:void 0,uvs:void 0,materialName:""};w(),f.push(D),A=!0,M=!0,N=1}else if(this.usemtl.test(G)){if(L=G.substring(7).trim(),!M){w();var D={name:"_mm"+N.toString(),indices:void 0,positions:void 0,normals:void 0,uvs:void 0,materialName:L};N++,f.push(D)}A&&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)}A&&(s=f[f.length-1],d.reverse(),S(),s.indices=d,s.positions=_,s.normals=y,s.uvs=g),A||(d.reverse(),S(),f.push({name:e.Geometry.RandomId(),indices:d,positions:_,normals:y,uvs:g,materialName:L}));for(var U=[],V=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 Y=new e.Mesh(f[k].name,a);V.push(f[k].materialName);var H=new e.VertexData;H.positions=s.positions,H.normals=s.normals,H.uvs=s.uvs,H.indices=s.indices,H.applyToMesh(Y),U.push(Y)}return""!==b&&this._loadMTL(b,i,(function(e){x.parseMTL(a,e,i);for(var t=0;t<x.materials.length;t++){for(var r,n=0,o=[];(r=V.indexOf(x.materials[t].name,n))>-1;)o.push(r),n=r+1;if(-1==r&&0==o.length)x.materials[t].dispose();else for(var s=0;s<o.length;s++)U[o[s]].material=x.materials[t]}})),U},r.OPTIMIZE_WITH_UV=!1,r})();e.OBJFileLoader=r,e.SceneLoader&&e.SceneLoader.RegisterPlugin(new r)})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(e){e[e.AUTO=0]="AUTO",e[e.PASS_THROUGH=1]="PASS_THROUGH",e[e.FORCE_RIGHT_HANDED=2]="FORCE_RIGHT_HANDED"})(t=e.GLTFLoaderCoordinateSystemMode||(e.GLTFLoaderCoordinateSystemMode={}));var r=(function(){function e(){this.coordinateSystemMode=t.AUTO,this.name="gltf",this.extensions={".gltf":{isBinary:!1},".glb":{isBinary:!0}}}return e.prototype.importMeshAsync=function(t,r,n,a,o,i,s){var l=e._parse(n,s);if(l){this.onParsed&&this.onParsed(l);var u=this._getLoader(l,s);u&&u.importMeshAsync(t,r,l,a,o,i,s)}},e.prototype.loadAsync=function(t,r,n,a,o,i){var s=e._parse(r,i);if(s){this.onParsed&&this.onParsed(s);var l=this._getLoader(s,i);if(l)return l.loadAsync(t,s,n,a,o,i)}},e.prototype.canDirectLoad=function(e){return-1!==e.indexOf("scene")&&-1!==e.indexOf("node")},e._parse=function(t,r){try{return t instanceof ArrayBuffer?e._parseBinary(t,r):{json:JSON.parse(t),bin:null}}catch(e){return r(e.message),null}},e.prototype._getLoader=function(t,r){var n={major:2,minor:0},a=t.json.asset||{},o=e._parseVersion(a.version);if(!o)return r("Invalid version: "+a.version),null;if(void 0!==a.minVersion){var i=e._parseVersion(a.minVersion);if(!i)return r("Invalid minimum version: "+a.minVersion),null;if(e._compareVersion(i,n)>0)return r("Incompatible minimum version: "+a.minVersion),null}var s={1:e.CreateGLTFLoaderV1,2:e.CreateGLTFLoaderV2},l=s[o.major];return l?l(this):(r("Unsupported version: "+a.version),null)},e._parseBinary=function(t,r){var a={Magic:1179937895},o=new n(t),i=o.readUint32();if(i!==a.Magic)return r("Unexpected magic: "+i),null;var s=o.readUint32();switch(s){case 1:return e._parseV1(o,r);case 2:return e._parseV2(o,r)}return r("Unsupported version: "+s),null},e._parseV1=function(t,r){var n={JSON:0},a=t.readUint32();if(a!=t.getLength())return r("Length in header does not match actual data length: "+a+" != "+t.getLength()),null;var o,i=t.readUint32(),s=t.readUint32();switch(s){case n.JSON:o=JSON.parse(e._decodeBufferToText(t.readUint8Array(i)));break;default:return r("Unexpected content format: "+s),null}var l=t.getLength()-t.getPosition();return{json:o,bin:t.readUint8Array(l)}},e._parseV2=function(t,r){var n={JSON:1313821514,BIN:5130562},a=t.readUint32();if(a!==t.getLength())return r("Length in header does not match actual data length: "+a+" != "+t.getLength()),null;var o=t.readUint32(),i=t.readUint32();if(i!==n.JSON)return r("First chunk format is not JSON"),null;for(var s=JSON.parse(e._decodeBufferToText(t.readUint8Array(o))),l=null;t.getPosition()<t.getLength();)switch(o=t.readUint32(),i=t.readUint32()){case n.JSON:return r("Unexpected JSON chunk"),null;case n.BIN:l=t.readUint8Array(o);break;default:t.skipBytes(o)}return{json:s,bin:l}},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})(),a=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],o=["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 a=e[n];r[t][n]=a}},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(-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)for(var a=r.animations[n],o=null,l=0;l<a.channels.length;l++){var u=a.channels[l],c=a.samplers[u.sampler];if(c){var f=null,d=null;a.parameters?(f=a.parameters[c.input],d=a.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,T=r.scene.getNodeByID(m);if(null===T&&(T=r.scene.getNodeByName(m)),null!==T){var E=T instanceof e.Bone,A=u.target.path,_=i.indexOf(A);-1!==_&&(A=s[_]);var y=e.Animation.ANIMATIONTYPE_MATRIX;E||("rotationQuaternion"===A?(y=e.Animation.ANIMATIONTYPE_QUATERNION,T.rotationQuaternion=new e.Quaternion):y=e.Animation.ANIMATIONTYPE_VECTOR3);var g=null,v=[],L=0,b=!1;E&&o&&o.getKeys().length===h.length&&(g=o,b=!0),b||(g=new e.Animation(n,E?"_matrix":A,1,y,e.Animation.ANIMATIONLOOPMODE_CYCLE));for(var x=0;x<h.length;x++){var N=null;if("rotationQuaternion"===A?(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=T,O=e.Vector3.Zero(),F=new e.Quaternion,I=e.Vector3.Zero(),S=M.getBaseMatrix();b&&(S=o.getKeys()[x].value),S.decompose(I,F,O),"position"===A?O=N:"rotationQuaternion"===A?F=N:I=N,N=e.Matrix.Compose(I,F,O)}b?o.getKeys()[x].value=N:v.push({frame:h[x],value:N})}b||(g.setKeys(v),T.animations.push(g)),o=g,r.scene.stopAnimation(T),r.scene.beginAnimation(T,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]),a=e.Quaternion.FromArray(t.rotation||[0,0,0,1]),o=e.Vector3.FromArray(t.translation||[0,0,0]);r=e.Matrix.Compose(n,a,o)}else r=e.Matrix.FromArray(t.matrix);return r},m=function(t,r,n,a){for(var o=0;o<a.bones.length;o++)if(a.bones[o].name===n)return a.bones[o];var i=t.nodes;for(var s in i){var l=i[s];if(l.jointName)for(var u=l.children,o=0;o<u.length;o++){var c=t.nodes[u[o]];if(c.jointName&&c.jointName===n){var f=p(l),d=new e.Bone(l.name,a,m(t,r,l.jointName,a),f);return d.id=s,d}}}return null},T=function(e,t){for(var r=0;r<e.length;r++)for(var n=e[r],a=0;a<n.node.children.length;a++){var o=n.node.children[a];if(o===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 a in r)if(n=r[a],n.jointName===t)return{node:n,id:a};return null},A=function(e,t){for(var r=0;r<e.jointNames.length;r++)if(e.jointNames[r]===t)return!0;return!1},_=function(t,r,n,a){for(var o in t.nodes){var i=t.nodes[o],s=o;if(i.jointName&&!A(n,i.jointName)){var l=p(i),u=new e.Bone(i.name,r,null,l);u.id=s,a.push({bone:u,node:i,id:s})}}for(var c=0;c<a.length;c++)for(var f=a[c],d=f.node.children,h=0;h<d.length;h++){for(var m=null,T=0;T<a.length;T++)if(a[T].id===d[h]){m=a[T];break}m&&(m.bone._parent=f.bone,f.bone.children.push(m.bone))}},y=function(t,r,n,a,o){if(a||(a=new e.Skeleton(r.name,"",t.scene)),!r.babylonSkeleton)return a;var i=[],s=[];_(t,a,r,i),a.bones=[];for(var l=0;l<r.jointNames.length;l++){var u=E(t,r.jointNames[l]),c=u.node;if(c){var o=u.id,f=t.scene.getBoneByID(o);if(f)a.bones.push(f);else{for(var d=!1,h=null,A=0;A<l;A++){var y=E(t,r.jointNames[A]).node;if(y){var g=y.children;if(g){d=!1;for(var v=0;v<g.length;v++)if(g[v]===o){h=m(t,r,r.jointNames[A],a),d=!0;break}if(d)break}}else e.Tools.Warn("Joint named "+r.jointNames[A]+" does not exist when looking for parent")}var L=p(c);!h&&i.length>0&&(h=T(i,o))&&-1===s.indexOf(h)&&s.push(h);new e.Bone(c.jointName,a,h,L).id=o}}else e.Tools.Warn("Joint named "+r.jointNames[l]+" does not exist")}var b=a.bones;a.bones=[];for(var l=0;l<r.jointNames.length;l++){var u=E(t,r.jointNames[l]);if(u)for(var A=0;A<b.length;A++)if(b[A].id===u.id){a.bones.push(b[A]);break}}a.prepare();for(var l=0;l<s.length;l++)a.bones.push(s[l]);return a},g=function(r,n,a,o,i){if(i||(i=new e.Mesh(n.name,r.scene),i.id=o),!n.babylonNode)return i;var s=new e.MultiMaterial("multimat"+o,r.scene);i.material||(i.material=s);for(var l=new e.VertexData,u=new e.Geometry(o,r.scene,l,!1,i),c=new Array,d=new Array,h=new Array,p=new Array,m=0;m<a.length;m++){var T=a[m],E=r.meshes[T];if(E)for(var A=0;A<E.primitives.length;A++){var _=new e.VertexData,y=E.primitives[A];y.mode;var g=y.attributes,v=null,L=null;for(var b in g)if(v=r.accessors[g[b]],L=t.GLTFUtils.GetBufferFromAccessor(r,v),"NORMAL"===b)_.normals=new Float32Array(L.length),_.normals.set(L);else if("POSITION"===b){if(e.GLTFFileLoader.HomogeneousCoordinates){_.positions=new Float32Array(L.length-L.length/4);for(var x=0;x<L.length;x+=4)_.positions[x]=L[x],_.positions[x+1]=L[x+1],_.positions[x+2]=L[x+2]}else _.positions=new Float32Array(L.length),_.positions.set(L);d.push(_.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),_.set(O,M)}else"JOINT"===b?(_.matricesIndices=new Float32Array(L.length),_.matricesIndices.set(L)):"WEIGHT"===b?(_.matricesWeights=new Float32Array(L.length),_.matricesWeights.set(L)):"COLOR"===b&&(_.colors=new Float32Array(L.length),_.colors.set(L));if(v=r.accessors[y.indices])L=t.GLTFUtils.GetBufferFromAccessor(r,v),_.indices=new Int32Array(L.length),_.indices.set(L),p.push(_.indices.length);else{for(var F=[],x=0;x<_.positions.length/3;x++)F.push(x);_.indices=new Int32Array(F),p.push(_.indices.length)}l.merge(_),_=void 0;var I=r.scene.getMaterialByID(y.material);s.subMaterials.push(null===I?t.GLTFUtils.GetDefaultMaterial(r.scene):I),c.push(0===c.length?0:c[c.length-1]+d[d.length-2]),h.push(0===h.length?0:h[h.length-1]+p[p.length-2])}}u.setAllVerticesData(l,!1),i.computeWorldMatrix(!0),i.subMeshes=[];for(var S=0,m=0;m<a.length;m++){var T=a[m],E=r.meshes[T];if(E)for(var A=0;A<E.primitives.length;A++)E.primitives[A].mode,e.SubMesh.AddToMesh(S,c[S],d[S],h[S],p[S],i,i,!0),S++}return i},v=function(e,t,r,n){e.position&&(e.position=t),(e.rotationQuaternion||e.rotation)&&(e.rotationQuaternion=r),e.scaling&&(e.scaling=n)},L=function(t,r,n){if(r.matrix){var a=new e.Vector3(0,0,0),o=new e.Quaternion,i=new e.Vector3(0,0,0);e.Matrix.FromArray(r.matrix).decompose(i,o,a),v(t,a,o,i)}else v(t,e.Vector3.FromArray(r.translation),e.Quaternion.FromArray(r.rotation),e.Vector3.FromArray(r.scale));t.computeWorldMatrix(!0)},b=function(t,r,n,a){var o=null;if(t.importOnlyMeshes&&(r.skin||r.meshes)&&t.importMeshesNames.length>0&&-1===t.importMeshesNames.indexOf(r.name))return null;if(r.skin){if(r.meshes){var i=t.skins[r.skin],s=g(t,r,r.meshes,n,r.babylonNode);s.skeleton=t.scene.getLastSkeletonByID(r.skin),null===s.skeleton&&(s.skeleton=y(t,i,0,i.babylonSkeleton,r.skin),i.babylonSkeleton||(i.babylonSkeleton=s.skeleton)),o=s}}else if(r.meshes){var s=g(t,r,r.mesh?[r.mesh]:r.meshes,n,r.babylonNode);o=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()),o=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),o=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)),o=p}else if("directional"===d.type){var m=d[d.type],T=new e.DirectionalLight(r.light,e.Vector3.Zero(),t.scene);T.name=r.name,m.color&&(T.diffuse=e.Color3.FromArray(m.color)),o=T}else if("point"===d.type){var E=d[d.type],A=new e.PointLight(r.light,e.Vector3.Zero(),t.scene);A.name=r.name,E.color&&(A.diffuse=e.Color3.FromArray(E.color)),o=A}else if("spot"===d.type){var _=d[d.type],b=new e.SpotLight(r.light,e.Vector3.Zero(),e.Vector3.Zero(),0,0,t.scene);b.name=r.name,_.color&&(b.diffuse=e.Color3.FromArray(_.color)),_.fallOfAngle&&(b.angle=_.fallOfAngle),_.fallOffExponent&&(b.exponent=_.fallOffExponent),o=b}}if(!r.jointName){if(r.babylonNode)return r.babylonNode;if(null===o){var x=new e.Mesh(r.name,t.scene);r.babylonNode=x,o=x}}if(null!==o){if(r.matrix&&o instanceof e.Mesh)L(o,r);else{var N=r.translation||[0,0,0],M=r.rotation||[0,0,0,1],O=r.scale||[1,1,1];v(o,e.Vector3.FromArray(N),e.Quaternion.FromArray(M),e.Vector3.FromArray(O))}o.updateCache(!0),r.babylonNode=o}return o},x=function(e,t,r,n){var a=e.nodes[t],o=null;if(n=!(e.importOnlyMeshes&&!n)||(-1!==e.importMeshesNames.indexOf(a.name)||0===e.importMeshesNames.length),!a.jointName&&n&&null!==(o=b(e,a,t))&&(o.id=t,o.parent=r),a.children)for(var i=0;i<a.children.length;i++)x(e,a.children[i],o,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 a=e.scene.skeletons[r];e.scene.beginAnimation(a,0,Number.MAX_VALUE,!0,1)}},M=function(e,r,n,a,o,i,s){var l=i.values||o.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,a.getEffect())}}else t.GLTFUtils.SetMatrix(r.scene,e,c,u,a.getEffect());else{var h=l[o.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;a.getEffect().setTexture(u,p)}else t.GLTFUtils.SetUniform(a.getEffect(),u,h,f)}}s(a)},O=function(e,r,n,a,o){var i=a.values||n.parameters,s=n.uniforms;for(var l in o){var u=o[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&&(r.setTexture(e,t),delete o[e])}};c===t.EParameterType.SAMPLER_2D?t.GLTFLoaderExtension.LoadTextureAsync(e,a.values?f:u.value,d(l),(function(){return d(null)})):u.value&&t.GLTFUtils.SetUniform(r,l,a.values?f:u.value,c)&&delete o[l]}}},F=function(e,t,r){return function(n,a){t.dispose(!0),r("Cannot compile program named "+e.name+". Error: "+a+". Default material will be applied")}},I=function(e,t,r,n,a,o){return function(i){O(e,t,r,n,a),t.onBind=function(i){M(i,e,a,t,r,n,o)}}},S=function(e,t,r){for(var n in t.uniforms){var i=t.uniforms[n],s=t.parameters[i];if(e.currentIdentifier===n&&s.semantic&&!s.source&&!s.node){var l=a.indexOf(s.semantic);if(-1!==l)return delete r[n],o[l]}}return e.currentIdentifier},R=function(e){for(var r in e.materials)t.GLTFLoaderExtension.LoadMaterialAsync(e,r,(function(e){}),(function(){}))},w=(function(){function i(){}return i.CreateRuntime=function(e,t,r){var n={extensions:{},accessors:{},buffers:{},bufferViews:{},meshes:{},lights:{},cameras:{},nodes:{},images:{},textures:{},shaders:{},programs:{},samplers:{},techniques:{},materials:{},animations:{},skins:{},extensionsUsed:[],scenes:{},buffersCount:0,shaderscount:0,scene:t,rootUrl:r,loadedBufferCount:0,loadedBufferViews:{},loadedShaderCount:0,importOnlyMeshes:!1,dummyNodes:[]};return e.extensions&&c(e.extensions,"extensions",n),e.extensionsUsed&&c(e.extensionsUsed,"extensionsUsed",n),e.buffers&&l(e.buffers,n),e.bufferViews&&c(e.bufferViews,"bufferViews",n),e.accessors&&c(e.accessors,"accessors",n),e.meshes&&c(e.meshes,"meshes",n),e.lights&&c(e.lights,"lights",n),e.cameras&&c(e.cameras,"cameras",n),e.nodes&&c(e.nodes,"nodes",n),e.images&&c(e.images,"images",n),e.textures&&c(e.textures,"textures",n),e.shaders&&u(e.shaders,n),e.programs&&c(e.programs,"programs",n),e.samplers&&c(e.samplers,"samplers",n),e.techniques&&c(e.techniques,"techniques",n),e.materials&&c(e.materials,"materials",n),e.animations&&c(e.animations,"animations",n),e.skins&&c(e.skins,"skins",n),e.scenes&&(n.scenes=e.scenes),e.scene&&e.scenes&&(n.currentScene=e.scenes[e.scene]),n},i.LoadBufferAsync=function(r,n,a,o,i){var s=r.buffers[n];t.GLTFUtils.IsBase64(s.uri)?setTimeout((function(){return a(new Uint8Array(t.GLTFUtils.DecodeBase64(s.uri)))})):e.Tools.LoadFile(r.rootUrl+s.uri,(function(e){return a(new Uint8Array(e))}),i,null,!0,(function(e){o(e.status+" "+e.statusText)}))},i.LoadTextureBufferAsync=function(r,n,a,o){var i=r.textures[n];if(!i||!i.source)return void o(null);if(i.babylonTexture)return void a(null);var s=r.images[i.source];t.GLTFUtils.IsBase64(s.uri)?setTimeout((function(){return a(new Uint8Array(t.GLTFUtils.DecodeBase64(s.uri)))})):e.Tools.LoadFile(r.rootUrl+s.uri,(function(e){return a(new Uint8Array(e))}),null,null,!0,(function(e){o(e.status+" "+e.statusText)}))},i.CreateTextureAsync=function(r,n,a,o,i){var s=r.textures[n];if(s.babylonTexture)return void o(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([a]),d=URL.createObjectURL(f),h=function(){return URL.revokeObjectURL(d)},p=new e.Texture(d,r.scene,!u,!0,c,h,h);p.wrapU=t.GLTFUtils.GetWrapMode(l.wrapS),p.wrapV=t.GLTFUtils.GetWrapMode(l.wrapT),p.name=n,s.babylonTexture=p,o(p)},i.LoadShaderStringAsync=function(r,n,a,o){var i=r.shaders[n];if(t.GLTFUtils.IsBase64(i.uri)){a(atob(i.uri.split(",")[1]))}else e.Tools.LoadFile(r.rootUrl+i.uri,a,null,null,!1,(function(e){o(e.status+" "+e.statusText)}))},i.LoadMaterialAsync=function(i,s,l,u){var c=i.materials[s],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)}
  98825. var p=i.programs[f.program],m=f.states,T=e.Effect.ShadersStore[p.vertexShader+"VertexShader"],E=e.Effect.ShadersStore[p.fragmentShader+"PixelShader"],A="",_="",y=new n(T),g=new n(E),v={},L=[],b=[],x=[];for(var N in f.uniforms){var M=f.uniforms[N],O=f.parameters[M];if(v[N]=O,!O.semantic||O.node||O.source)O.type===t.EParameterType.SAMPLER_2D?x.push(N):L.push(N);else{var R=a.indexOf(O.semantic);-1!==R?(L.push(o[R]),delete v[N]):L.push(N)}}for(var w in f.attributes){var B=f.attributes[w],P=f.parameters[B];P.semantic&&b.push(d(P))}for(;!y.isEnd()&&y.getNextToken();){var C=y.currentToken;if(C===r.IDENTIFIER){var G=!1;for(var w in f.attributes){var B=f.attributes[w],P=f.parameters[B];if(y.currentIdentifier===w&&P.semantic){A+=d(P),G=!0;break}}G||(A+=S(y,f,v))}else A+=y.currentString}for(;!g.isEnd()&&g.getNextToken();){var C=g.currentToken;C===r.IDENTIFIER?_+=S(g,f,v):_+=g.currentString}var D={vertex:p.vertexShader+s,fragment:p.fragmentShader+s},U={attributes:b,uniforms:L,samplers:x,needAlphaBlending:m&&m.enable&&-1!==m.enable.indexOf(3042)};e.Effect.ShadersStore[p.vertexShader+s+"VertexShader"]=A,e.Effect.ShadersStore[p.fragmentShader+s+"PixelShader"]=_;var V=new e.ShaderMaterial(s,i.scene,D,U);if(V.onError=F(p,V,u),V.onCompiled=I(i,V,f,c,v,l),V.sideOrientation=e.Material.CounterClockWiseSideOrientation,m&&m.functions){var k=m.functions;k.cullFace&&k.cullFace[0]!==t.ECullingType.BACK&&(V.backFaceCulling=!1);var Y=k.blendFuncSeparate;Y&&(Y[0]===t.EBlendingFunction.SRC_ALPHA&&Y[1]===t.EBlendingFunction.ONE_MINUS_SRC_ALPHA&&Y[2]===t.EBlendingFunction.ONE&&Y[3]===t.EBlendingFunction.ONE?V.alphaMode=e.Engine.ALPHA_COMBINE:Y[0]===t.EBlendingFunction.ONE&&Y[1]===t.EBlendingFunction.ONE&&Y[2]===t.EBlendingFunction.ZERO&&Y[3]===t.EBlendingFunction.ONE?V.alphaMode=e.Engine.ALPHA_ONEONE:Y[0]===t.EBlendingFunction.SRC_ALPHA&&Y[1]===t.EBlendingFunction.ONE&&Y[2]===t.EBlendingFunction.ZERO&&Y[3]===t.EBlendingFunction.ONE?V.alphaMode=e.Engine.ALPHA_ADD:Y[0]===t.EBlendingFunction.ZERO&&Y[1]===t.EBlendingFunction.ONE_MINUS_SRC_COLOR&&Y[2]===t.EBlendingFunction.ONE&&Y[3]===t.EBlendingFunction.ONE?V.alphaMode=e.Engine.ALPHA_SUBTRACT:Y[0]===t.EBlendingFunction.DST_COLOR&&Y[1]===t.EBlendingFunction.ZERO&&Y[2]===t.EBlendingFunction.ONE&&Y[3]===t.EBlendingFunction.ONE?V.alphaMode=e.Engine.ALPHA_MULTIPLY:Y[0]===t.EBlendingFunction.SRC_ALPHA&&Y[1]===t.EBlendingFunction.ONE_MINUS_SRC_COLOR&&Y[2]===t.EBlendingFunction.ONE&&Y[3]===t.EBlendingFunction.ONE&&(V.alphaMode=e.Engine.ALPHA_MAXIMIZED))}},i})();t.GLTFLoaderBase=w;var B=(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.importMeshAsync=function(r,n,a,o,i,s,l){var u=this;return n.useRightHandedSystem=!0,t.GLTFLoaderExtension.LoadRuntimeAsync(n,a,o,(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,a=new Array;for(var o in t.nodes){var l=t.nodes[o];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&&a.push(f.babylonSkeleton)}u._loadBuffersAsync(t,(function(){u._loadShadersAsync(t,(function(){R(t),N(t),!e.GLTFFileLoader.IncrementalLoading&&i&&i(n,null,a)}))}),s),e.GLTFFileLoader.IncrementalLoading&&i&&i(n,null,a)}),l),!0},r.prototype.loadAsync=function(r,n,a,o,i,s){var l=this;r.useRightHandedSystem=!0,t.GLTFLoaderExtension.LoadRuntimeAsync(r,n,a,(function(r){t.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(r,(function(){l._createNodes(r),l._loadBuffersAsync(r,(function(){l._loadShadersAsync(r,(function(){R(r),N(r),e.GLTFFileLoader.IncrementalLoading||o()}))})),e.GLTFFileLoader.IncrementalLoading&&o()}),s)}),s)},r.prototype._loadShadersAsync=function(r,n){var a=!1,o=function(a,o){t.GLTFLoaderExtension.LoadShaderStringAsync(r,a,(function(i){r.loadedShaderCount++,i&&(e.Effect.ShadersStore[a+(o.type===t.EShaderType.VERTEX?"VertexShader":"PixelShader")]=i),r.loadedShaderCount===r.shaderscount&&n()}),(function(){e.Tools.Error("Error when loading shader program named "+a+" located at "+o.uri)}))};for(var i in r.shaders){a=!0;var s=r.shaders[i];s?o.bind(this,i,s)():e.Tools.Error("No shader named: "+i)}a||n()},r.prototype._loadBuffersAsync=function(r,n,a){var o=!1,i=function(a,o){t.GLTFLoaderExtension.LoadBufferAsync(r,a,(function(t){r.loadedBufferCount++,t&&(t.byteLength!=r.buffers[a].byteLength&&e.Tools.Error("Buffer named "+a+" is length "+t.byteLength+". Expected: "+o.byteLength),r.loadedBufferViews[a]=t),r.loadedBufferCount===r.buffersCount&&n()}),(function(){e.Tools.Error("Error when loading buffer named "+a+" located at "+o.uri)}))};for(var s in r.buffers){o=!0;var l=r.buffers[s];l?i.bind(this,s,l)():e.Tools.Error("No buffer named: "+s)}o||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=B,e.GLTFFileLoader.CreateGLTFLoaderV1=function(){return new B}})(e.GLTF1||(e.GLTF1={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(t){var r=(function(){function r(){}return r.SetMatrix=function(r,n,a,o,i){var s=null;switch("MODEL"===a.semantic?s=n.getWorldMatrix():"PROJECTION"===a.semantic?s=r.getProjectionMatrix():"VIEW"===a.semantic?s=r.getViewMatrix():"MODELVIEWINVERSETRANSPOSE"===a.semantic?s=e.Matrix.Transpose(n.getWorldMatrix().multiply(r.getViewMatrix()).invert()):"MODELVIEW"===a.semantic?s=n.getWorldMatrix().multiply(r.getViewMatrix()):"MODELVIEWPROJECTION"===a.semantic?s=n.getWorldMatrix().multiply(r.getTransformMatrix()):"MODELINVERSE"===a.semantic?s=n.getWorldMatrix().invert():"VIEWINVERSE"===a.semantic?s=r.getViewMatrix().invert():"PROJECTIONINVERSE"===a.semantic?s=r.getProjectionMatrix().invert():"MODELVIEWINVERSE"===a.semantic?s=n.getWorldMatrix().multiply(r.getViewMatrix()).invert():"MODELVIEWPROJECTIONINVERSE"===a.semantic?s=n.getWorldMatrix().multiply(r.getTransformMatrix()).invert():"MODELINVERSETRANSPOSE"===a.semantic&&(s=e.Matrix.Transpose(n.getWorldMatrix().invert())),a.type){case t.EParameterType.FLOAT_MAT2:i.setMatrix2x2(o,e.Matrix.GetAsMatrix2x2(s));break;case t.EParameterType.FLOAT_MAT3:i.setMatrix3x3(o,e.Matrix.GetAsMatrix3x3(s));break;case t.EParameterType.FLOAT_MAT4:i.setMatrix(o,s)}},r.SetUniform=function(r,n,a,o){switch(o){case t.EParameterType.FLOAT:return r.setFloat(n,a),!0;case t.EParameterType.FLOAT_VEC2:return r.setVector2(n,e.Vector2.FromArray(a)),!0;case t.EParameterType.FLOAT_VEC3:return r.setVector3(n,e.Vector3.FromArray(a)),!0;case t.EParameterType.FLOAT_VEC4:return r.setVector4(n,e.Vector4.FromArray(a)),!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)),a=0;a<r;a++)n[a]=t.charCodeAt(a);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,a,o){var n=r.byteOffset+n,i=e.loadedBufferViews[r.buffer];if(n+a>i.byteLength)throw new Error("Buffer access is out of range");var s=i.buffer;switch(n+=i.byteOffset,o){case t.EComponentType.BYTE:return new Int8Array(s,n,a);case t.EComponentType.UNSIGNED_BYTE:return new Uint8Array(s,n,a);case t.EComponentType.SHORT:return new Int16Array(s,n,a);case t.EComponentType.UNSIGNED_SHORT:return new Uint16Array(s,n,a);default:return new Float32Array(s,n,a)}},r.GetBufferFromAccessor=function(e,t){var n=e.bufferViews[t.bufferView],a=t.count*r.GetByteStrideFromType(t);return r.GetBufferFromBufferView(e,n,t.byteOffset,a,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"},a={attributes:["position"],uniforms:["worldView","projection","u_emission"],samplers:new Array,needAlphaBlending:!1};r._DefaultMaterial=new e.ShaderMaterial("GLTFDefaultMaterial",t,n,a),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,a){return!1},t.prototype.loadRuntimeExtensionsAsync=function(e,t,r){return!1},t.prototype.loadBufferAsync=function(e,t,r,n,a){return!1},t.prototype.loadTextureBufferAsync=function(e,t,r,n){return!1},t.prototype.createTextureAsync=function(e,t,r,n,a){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,a,o,i){t.ApplyExtensions((function(e){return e.loadRuntimeAsync(r,n,a,o,i)}),(function(){setTimeout((function(){o(e.GLTFLoaderBase.CreateRuntime(n.json,r,a))}))}))},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,a,o,i){t.ApplyExtensions((function(e){return e.loadBufferAsync(r,n,a,o,i)}),(function(){e.GLTFLoaderBase.LoadBufferAsync(r,n,a,o,i)}))},t.LoadTextureAsync=function(e,r,n,a){t.LoadTextureBufferAsync(e,r,(function(o){return t.CreateTextureAsync(e,r,o,n,a)}),a)},t.LoadShaderStringAsync=function(r,n,a,o){t.ApplyExtensions((function(e){return e.loadShaderStringAsync(r,n,a,o)}),(function(){e.GLTFLoaderBase.LoadShaderStringAsync(r,n,a,o)}))},t.LoadMaterialAsync=function(r,n,a,o){t.ApplyExtensions((function(e){return e.loadMaterialAsync(r,n,a,o)}),(function(){e.GLTFLoaderBase.LoadMaterialAsync(r,n,a,o)}))},t.LoadTextureBufferAsync=function(r,n,a,o){t.ApplyExtensions((function(e){return e.loadTextureBufferAsync(r,n,a,o)}),(function(){e.GLTFLoaderBase.LoadTextureBufferAsync(r,n,a,o)}))},t.CreateTextureAsync=function(r,n,a,o,i){t.ApplyExtensions((function(e){return e.createTextureAsync(r,n,a,o,i)}),(function(){e.GLTFLoaderBase.CreateTextureAsync(r,n,a,o,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,a,o){var i=r.json.extensionsUsed;return!(!i||-1===i.indexOf(this.name))&&(this._bin=r.bin,a(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,a){var o=t.textures[r],i=t.images[o.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,a){var o=t.shaders[r];if(!(o.extensions&&this.name in o.extensions))return!1;var i=o.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 a=t.extensions[this.name];if(!a)return!1;var o=a.lights;if(o)for(var i in o){var s=o[i];switch(s.type){case"ambient":var l=new e.HemisphericLight(s.name,new e.Vector3(0,1,0),t.scene),u=s.ambient;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;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;d.diffuse=e.Color3.FromArray(h.color||[1,1,1]);break;case"spot":var p=s.spot,m=new e.SpotLight(s.name,new e.Vector3(0,10,0),new e.Vector3(0,-1,0),s.spot.fallOffAngle||Math.PI,s.spot.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,a){var o=t.materials[r];if(!o||!o.extensions)return!1;var i=o.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",a):s.ambientColor=e.Color3.FromArray(i.values.ambient||[0,0,0]),"string"==typeof i.values.diffuse?this._loadTexture(t,i.values.diffuse,s,"diffuseTexture",a):s.diffuseColor=e.Color3.FromArray(i.values.diffuse||[0,0,0]),"string"==typeof i.values.emission?this._loadTexture(t,i.values.emission,s,"emissiveTexture",a):s.emissiveColor=e.Color3.FromArray(i.values.emission||[0,0,0]),"string"==typeof i.values.specular?this._loadTexture(t,i.values.specular,s,"specularTexture",a):s.specularColor=e.Color3.FromArray(i.values.specular||[0,0,0]),!0},n.prototype._loadTexture=function(e,r,n,a,o){t.GLTFLoaderBase.LoadTextureBufferAsync(e,r,(function(i){t.GLTFLoaderBase.CreateTextureAsync(e,r,i,(function(e){return n[a]=e}),o)}),o)},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._renderReady=!1,this._disposed=!1,this._renderReadyObservable=new e.Observable,this._renderPendingCount=0,this._loaderPendingCount=0,this._loaderTrackers=new Array,this._parent=t}return n.RegisterExtension=function(r){if(n.Extensions[r.name])return void e.Tools.Error("Extension with the same name '"+r.name+"' already exists");n.Extensions[r.name]=r,t.GLTFLoaderExtension._Extensions.push(r)},n.prototype.dispose=function(){this._disposed||(this._disposed=!0,this._gltf.textures&&this._gltf.textures.forEach((function(e){e.url&&URL.revokeObjectURL(e.url)})),this._gltf=void 0,this._babylonScene=void 0,this._rootUrl=void 0,this._defaultMaterial=void 0,this._successCallback=void 0,this._errorCallback=void 0,this._renderReady=!1,this._renderReadyObservable.clear(),this._renderPendingCount=0,this._loaderPendingCount=0)},n.prototype.importMeshAsync=function(e,t,r,n,a,o,i){var s=this;this._loadAsync(e,t,r,n,(function(){a(s._getMeshes(),null,s._getSkeletons())}),o,i)},n.prototype.loadAsync=function(e,t,r,n,a,o){this._loadAsync(null,e,t,r,n,a,o)},n.prototype._loadAsync=function(e,r,n,a,o,i,s){var l=this;this._tryCatchOnError((function(){l._loadData(n),l._babylonScene=r,l._rootUrl=a,l._successCallback=o,l._progressCallback=i,l._errorCallback=s,t.GLTFUtils.AssignIndices(l._gltf.accessors),t.GLTFUtils.AssignIndices(l._gltf.animations),t.GLTFUtils.AssignIndices(l._gltf.buffers),t.GLTFUtils.AssignIndices(l._gltf.bufferViews),t.GLTFUtils.AssignIndices(l._gltf.images),t.GLTFUtils.AssignIndices(l._gltf.materials),t.GLTFUtils.AssignIndices(l._gltf.meshes),t.GLTFUtils.AssignIndices(l._gltf.nodes),t.GLTFUtils.AssignIndices(l._gltf.scenes),t.GLTFUtils.AssignIndices(l._gltf.skins),t.GLTFUtils.AssignIndices(l._gltf.textures),l._addPendingData(l),l._loadDefaultScene(e),l._loadAnimations(),l._removePendingData(l)}))},n.prototype._onError=function(t){this._disposed||(e.Tools.Error("glTF Loader: "+t),this._errorCallback&&this._errorCallback(t),this.dispose())},n.prototype._onProgress=function(e){this._disposed||this._progressCallback&&this._progressCallback(e)},n.prototype._executeWhenRenderReady=function(e){this._renderReady?e():this._renderReadyObservable.add(e)},n.prototype._onRenderReady=function(){this._rootNode.babylonMesh.setEnabled(!0),this._startAnimations(),this._successCallback(),this._renderReadyObservable.notifyObservers(this),this._parent.onReady&&this._parent.onReady()},n.prototype._onComplete=function(){this._parent.onComplete&&this._parent.onComplete(),this.dispose()},n.prototype._loadData=function(t){if(this._gltf=t.json,t.bin){var r=this._gltf.buffers;if(r&&r[0]&&!r[0].uri){var n=r[0];n.byteLength!=t.bin.byteLength&&e.Tools.Warn("Binary buffer length ("+n.byteLength+") from JSON does not match chunk length ("+t.bin.byteLength+")"),n.loadedData=t.bin}else e.Tools.Warn("Unexpected BIN chunk")}},n.prototype._getMeshes=function(){var e=[this._rootNode.babylonMesh],t=this._gltf.nodes;return t&&t.forEach((function(t){t.babylonMesh&&e.push(t.babylonMesh)})),e},n.prototype._getSkeletons=function(){var t=new Array,r=this._gltf.skins;return r&&r.forEach((function(r){r.babylonSkeleton instanceof e.Skeleton&&t.push(r.babylonSkeleton)})),t},n.prototype._getAnimationTargets=function(){var e=new Array,t=this._gltf.animations;return t&&t.forEach((function(t){e.push.apply(e,t.targets)})),e},n.prototype._startAnimations=function(){var e=this;this._getAnimationTargets().forEach((function(t){return e._babylonScene.beginAnimation(t,0,Number.MAX_VALUE,!0)}))},n.prototype._loadDefaultScene=function(e){var r=t.GLTFUtils.GetArrayItem(this._gltf.scenes,this._gltf.scene||0);if(!r)throw new Error("Failed to find scene "+(this._gltf.scene||0));this._loadScene("#/scenes/"+r.index,r,e)},n.prototype._loadScene=function(r,n,a){switch(this._rootNode={babylonMesh:new e.Mesh("__root__",this._babylonScene)},this._parent.coordinateSystemMode){case e.GLTFLoaderCoordinateSystemMode.AUTO:this._babylonScene.useRightHandedSystem||(this._rootNode.babylonMesh.rotation=new e.Vector3(0,Math.PI,0),this._rootNode.babylonMesh.scaling=new e.Vector3(1,1,-1));break;case e.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:break;case e.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:this._babylonScene.useRightHandedSystem=!0;break;default:return void e.Tools.Error("Invalid coordinate system mode ("+this._parent.coordinateSystemMode+")")}var o=n.nodes;if(this._traverseNodes(r,o,(function(e,t){return e.parent=t,!0}),this._rootNode),a){a instanceof Array||(a=[a]);var i=new Array;this._traverseNodes(r,o,(function(e){return-1===a.indexOf(e.name)||(i.push(e.index),!1)}),this._rootNode),o=i}for(var s=0;s<o.length;s++){var l=t.GLTFUtils.GetArrayItem(this._gltf.nodes,o[s]);if(!l)throw new Error(r+": Failed to find node "+o[s]);this._loadNode("#/nodes/"+o[s],l)}this._rootNode.babylonMesh.setEnabled(!1)},n.prototype._loadNode=function(r,n){if(!t.GLTFLoaderExtension.LoadNode(this,r,n)){if(n.babylonMesh=new e.Mesh(n.name||"mesh"+n.index,this._babylonScene),this._loadTransform(n),null!=n.mesh){var a=t.GLTFUtils.GetArrayItem(this._gltf.meshes,n.mesh);if(!a)throw new Error(r+": Failed to find mesh "+n.mesh);this._loadMesh("#/meshes/"+n.mesh,n,a)}if(n.babylonMesh.parent=n.parent?n.parent.babylonMesh:null,n.babylonAnimationTargets=n.babylonAnimationTargets||[],n.babylonAnimationTargets.push(n.babylonMesh),null!=n.skin){var o=t.GLTFUtils.GetArrayItem(this._gltf.skins,n.skin);if(!o)throw new Error(r+": Failed to find skin "+n.skin);n.babylonMesh.skeleton=this._loadSkin("#/skins/"+n.skin,o)}if(n.camera,n.children)for(var i=0;i<n.children.length;i++){var s=t.GLTFUtils.GetArrayItem(this._gltf.nodes,n.children[i]);if(!s)throw new Error(r+": Failed to find child node "+n.children[i]);this._loadNode("#/nodes/"+n.children[i],s)}}},n.prototype._loadMesh=function(r,n,a){var o=this;if(n.babylonMesh.name=n.babylonMesh.name||a.name,!a.primitives||0===a.primitives.length)throw new Error(r+": Primitives are missing");this._createMorphTargets(r,n,a),this._loadAllVertexDataAsync(r,a,(function(){o._loadMorphTargets(r,n,a);for(var i=a.primitives,s=new e.VertexData,l=0,u=i;l<u.length;l++){var c=u[l];s.merge(c.vertexData)}new e.Geometry(n.babylonMesh.name,o._babylonScene,s,!1,n.babylonMesh),n.babylonMesh.subMeshes=[];for(var f=0,d=0,h=0;h<i.length;h++){var s=i[h].vertexData,p=s.positions.length,m=s.indices.length;e.SubMesh.AddToMesh(h,f,p,d,m,n.babylonMesh),f+=p,d+=m}var T=new e.MultiMaterial(n.babylonMesh.name,o._babylonScene);n.babylonMesh.material=T;for(var E=T.subMaterials,h=0;h<i.length;h++){var c=i[h];if(null==c.material)E[h]=o._getDefaultMaterial();else{var A=t.GLTFUtils.GetArrayItem(o._gltf.materials,c.material);if(!A)throw new Error(r+": Failed to find material "+c.material);o._loadMaterial("#/materials/"+A.index,A,(function(e,t){t&&o._parent.onMaterialLoaded&&o._parent.onMaterialLoaded(e),o._parent.onBeforeMaterialReadyAsync?(o._addLoaderPendingData(A),o._parent.onBeforeMaterialReadyAsync(e,n.babylonMesh,null!=E[h],(function(){E[h]=e,o._removeLoaderPendingData(A)}))):E[h]=e}))}}}))},n.prototype._loadAllVertexDataAsync=function(e,t,r){for(var n=t.primitives,a=n.length,o=this,i=0;i<n.length;i++)!(function(){var s=n[i];o._loadVertexDataAsync(e+"/primitive/"+i,t,s,(function(e){s.vertexData=e,0==--a&&r()}))})()},n.prototype._loadVertexDataAsync=function(r,n,a,o){var i=this,s=a.attributes;if(!s)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 l,u=new e.VertexData,c=Object.keys(s).length,f=this;for(var d in s)!(function(n){if(!(l=t.GLTFUtils.GetArrayItem(f._gltf.accessors,s[n])))throw new Error(r+": Failed to find attribute '"+n+"' accessor "+s[n]);f._loadAccessorAsync("#/accessors/"+l.index,l,(function(s){switch(n){case"NORMAL":u.normals=s;break;case"POSITION":u.positions=s;break;case"TANGENT":u.tangents=s;break;case"TEXCOORD_0":u.uvs=s;break;case"TEXCOORD_1":u.uvs2=s;break;case"JOINTS_0":u.matricesIndices=new Float32Array(Array.prototype.slice.apply(s));break;case"WEIGHTS_0":u.matricesWeights=s;break;case"COLOR_0":u.colors=s;break;default:e.Tools.Warn("Ignoring unrecognized attribute '"+n+"'")}if(0==--c)if(null==a.indices)u.indices=new Uint32Array(u.positions.length/3),u.indices.forEach((function(e,t){return u.indices[t]=t})),o(u);else{var l=t.GLTFUtils.GetArrayItem(i._gltf.accessors,a.indices);if(!l)throw new Error(r+": Failed to find indices accessor "+a.indices);i._loadAccessorAsync("#/accessors/"+l.index,l,(function(e){u.indices=e,o(u)}))}}))})(d)},n.prototype._createMorphTargets=function(t,r,n){var a=n.primitives,o=a[0].targets;if(o){for(var i=0,s=a;i<s.length;i++){var l=s[i];if(!l.targets||l.targets.length!=o.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<o.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 a=r.babylonMesh.morphTargetManager;a&&this._loadAllMorphTargetVertexDataAsync(t,r,n,(function(){for(var t=a.numTargets,r=0;r<t;r++){for(var o=new e.VertexData,i=0,s=n.primitives;i<s.length;i++){var l=s[i];o.merge(l.targetsVertexData[r])}var u=a.getTarget(r);u.setNormals(o.normals),u.setPositions(o.positions),u.setTangents(o.tangents)}}))},n.prototype._loadAllMorphTargetVertexDataAsync=function(e,t,r,n){for(var a=r.primitives.length*t.babylonMesh.morphTargetManager.numTargets,o=0,i=r.primitives;o<i.length;o++){var s=i[o],l=s.targets;s.targetsVertexData=new Array(l.length);for(var u=this,c=0;c<l.length;c++)!(function(t){u._loadMorphTargetVertexDataAsync(e+"/targets/"+t,s.vertexData,l[t],(function(e){s.targetsVertexData[t]=e,0==--a&&n()}))})(c)}},n.prototype._loadMorphTargetVertexDataAsync=function(r,n,a,o){var i,s=new e.VertexData,l=Object.keys(a).length,u=this;for(var c in a)!(function(c){if(!(i=t.GLTFUtils.GetArrayItem(u._gltf.accessors,a[c])))throw new Error(r+": Failed to find attribute '"+c+"' accessor "+a[c]);u._loadAccessorAsync("#/accessors/"+i.index,i,(function(t){var r=t;switch(c){case"NORMAL":for(var a=0;a<r.length;a++)r[a]+=n.normals[a];s.normals=r;break;case"POSITION":for(var a=0;a<r.length;a++)r[a]+=n.positions[a];s.positions=r;break;case"TANGENT":for(var a=0,i=0;a<r.length;a++,i++)r[a]+=n.tangents[i],(a+1)%3==0&&i++;s.tangents=r;break;default:e.Tools.Warn("Ignoring unrecognized attribute '"+c+"'")}0==--l&&o(s)}))})(c)},n.prototype._loadTransform=function(t){var r=e.Vector3.Zero(),n=e.Quaternion.Identity(),a=e.Vector3.One();if(t.matrix){e.Matrix.FromArray(t.matrix).decompose(a,n,r)}else t.translation&&(r=e.Vector3.FromArray(t.translation)),t.rotation&&(n=e.Quaternion.FromArray(t.rotation)),t.scale&&(a=e.Vector3.FromArray(t.scale));t.babylonMesh.position=r,t.babylonMesh.rotationQuaternion=n,t.babylonMesh.scaling=a},n.prototype._loadSkin=function(r,n){var a=this,o="skeleton"+n.index;if(n.babylonSkeleton=new e.Skeleton(n.name||o,o,this._babylonScene),null==n.inverseBindMatrices)this._loadBones(r,n,null);else{var i=t.GLTFUtils.GetArrayItem(this._gltf.accessors,n.inverseBindMatrices);if(!i)throw new Error(r+": Failed to find inverse bind matrices attribute "+n.inverseBindMatrices);this._loadAccessorAsync("#/accessors/"+i.index,i,(function(e){a._loadBones(r,n,e)}))}return n.babylonSkeleton},n.prototype._createBone=function(t,r,n,a,o,i){var s=new e.Bone(t.name||"bone"+t.index,r.babylonSkeleton,n,a,null,o,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,r,n){for(var a={},o=0;o<r.joints.length;o++){var i=t.GLTFUtils.GetArrayItem(this._gltf.nodes,r.joints[o]);if(!i)throw new Error(e+": Failed to find joint "+r.joints[o]);this._loadBone(i,r,n,a)}},n.prototype._loadBone=function(t,r,n,a){var o=a[t.index];if(o)return o;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;return t.index!==r.skeleton&&t.parent!==this._rootNode&&(l=this._loadBone(t.parent,r,n,a),s.multiplyToRef(l.getInvertedAbsoluteTransform(),s)),o=this._createBone(t,r,l,this._getNodeMatrix(t),s,i),a[t.index]=o,o},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,r,n,a){void 0===a&&(a=null);for(var o=0;o<r.length;o++){var i=t.GLTFUtils.GetArrayItem(this._gltf.nodes,r[o]);if(!i)throw new Error(e+": Failed to find node "+r[o]);this._traverseNode(e,i,n,a)}},n.prototype._traverseNode=function(e,r,n,a){void 0===a&&(a=null),t.GLTFLoaderExtension.TraverseNode(this,e,r,n,a)||n(r,a)&&r.children&&this._traverseNodes(e,r.children,n,r)},n.prototype._loadAnimations=function(){var e=this._gltf.animations;if(e)for(var r=0;r<e.length;r++)for(var n=e[r],a="#/animations/"+r,o=0;o<n.channels.length;o++){var i=t.GLTFUtils.GetArrayItem(n.channels,o);if(!i)throw new Error(a+": Failed to find channel "+o);var s=t.GLTFUtils.GetArrayItem(n.samplers,i.sampler);if(!s)throw new Error(a+": Failed to find sampler "+i.sampler);this._loadAnimationChannel(n,a+"/channels/"+o,i,a+"/samplers/"+i.sampler,s)}},n.prototype._loadAnimationChannel=function(r,n,a,o,i){var s=t.GLTFUtils.GetArrayItem(this._gltf.nodes,a.target.node);if(!s)throw new Error(n+": Failed to find target node "+a.target.node);var l,u;switch(a.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(n+": Invalid target path '"+a.target.path+"'")}var c,f,d=function(){if(c&&f){var t,n=0;switch(l){case"position":t=function(){var t=e.Vector3.FromArray(f,n);return n+=3,t};break;case"rotationQuaternion":t=function(){var t=e.Quaternion.FromArray(f,n);return n+=4,t};break;case"scaling":t=function(){var t=e.Vector3.FromArray(f,n);return n+=3,t};break;case"influence":t=function(){for(var e=s.babylonMesh.morphTargetManager.numTargets,t=new Array(e),r=0;r<e;r++)t[r]=f[n++];return t}}var a;switch(i.interpolation){case"LINEAR":a=function(e){return{frame:c[e],value:t()}};break;case"CUBICSPLINE":a=function(e){return{frame:c[e],inTangent:t(),value:t(),outTangent:t()}};break;default:throw new Error(o+": Invalid interpolation '"+i.interpolation+"'")}for(var d=new Array(c.length),h=0;h<c.length;h++)d[h]=a(h);if(r.targets=r.targets||[],
  98826. "influence"===l)for(var p=s.babylonMesh.morphTargetManager,m=0;m<p.numTargets;m++){var T=p.getTarget(m),E=(r.name||"anim"+r.index)+"_"+m,A=new e.Animation(E,l,1,u);A.setKeys(d.map((function(e){return{frame:e.frame,inTangent:e.inTangent?e.inTangent[m]:void 0,value:e.value[m],outTangent:e.outTangent?e.outTangent[m]:void 0}}))),T.animations.push(A),r.targets.push(T)}else{var E=r.name||"anim"+r.index,A=new e.Animation(E,l,1,u);A.setKeys(d);for(var _=0;_<s.babylonAnimationTargets.length;_++){var y=s.babylonAnimationTargets[_];y.animations.push(A.clone()),r.targets.push(y)}}}},h=t.GLTFUtils.GetArrayItem(this._gltf.accessors,i.input);if(!h)throw new Error(o+": Failed to find input accessor "+i.input);this._loadAccessorAsync("#/accessors/"+h.index,h,(function(e){c=e,d()}));var p=t.GLTFUtils.GetArrayItem(this._gltf.accessors,i.output);if(!p)throw new Error(o+": Failed to find output accessor "+i.output);this._loadAccessorAsync("#/accessors/"+p.index,p,(function(e){f=e,d()}))},n.prototype._loadBufferAsync=function(r,n,a){var o=this;if(this._addPendingData(n),n.loadedData)a(n.loadedData),this._removePendingData(n);else if(n.loadedObservable)n.loadedObservable.add((function(e){a(e.loadedData),o._removePendingData(e)}));else{if(!n.uri)throw new Error(r+": Uri is missing");if(t.GLTFUtils.IsBase64(n.uri)){var i=t.GLTFUtils.DecodeBase64(n.uri);n.loadedData=new Uint8Array(i),a(n.loadedData),this._removePendingData(n)}else{if(!t.GLTFUtils.ValidateUri(n.uri))throw new Error(r+": Uri '"+n.uri+"' is invalid");n.loadedObservable=new e.Observable,n.loadedObservable.add((function(e){a(e.loadedData),o._removePendingData(e)})),e.Tools.LoadFile(this._rootUrl+n.uri,(function(e){o._tryCatchOnError((function(){n.loadedData=new Uint8Array(e),n.loadedObservable.notifyObservers(n),n.loadedObservable=null}))}),(function(e){o._tryCatchOnError((function(){o._onProgress(e)}))}),this._babylonScene.database,!0,(function(e){o._tryCatchOnError((function(){throw new Error(r+": Failed to load '"+n.uri+"'"+(e?": "+e.status+" "+e.statusText:""))}))}))}}},n.prototype._loadBufferViewAsync=function(e,r,n){var a=this,o=t.GLTFUtils.GetArrayItem(this._gltf.buffers,r.buffer);if(!o)throw new Error(e+": Failed to find buffer "+r.buffer);this._loadBufferAsync("#/buffers/"+o.index,o,(function(t){if(!a._disposed){try{var o=new Uint8Array(t.buffer,t.byteOffset+(r.byteOffset||0),r.byteLength)}catch(t){throw new Error(e+": "+t.message)}n(o)}}))},n.prototype._loadAccessorAsync=function(e,r,n){var a=this;if(r.sparse)throw new Error(e+": Sparse accessors are not currently supported");if(r.normalized)throw new Error(e+": Normalized accessors are not currently supported");var o=t.GLTFUtils.GetArrayItem(this._gltf.bufferViews,r.bufferView);if(!o)throw new Error(e+": Failed to find buffer view "+r.bufferView);this._loadBufferViewAsync("#/bufferViews/"+o.index,o,(function(i){var s=a._getNumComponentsOfType(r.type);if(0===s)throw new Error(e+": Invalid type ("+r.type+")");var l;switch(r.componentType){case t.EComponentType.BYTE:l=a._buildArrayBuffer(Float32Array,e,i,r.byteOffset,r.count,s,o.byteStride);break;case t.EComponentType.UNSIGNED_BYTE:l=a._buildArrayBuffer(Uint8Array,e,i,r.byteOffset,r.count,s,o.byteStride);break;case t.EComponentType.SHORT:l=a._buildArrayBuffer(Int16Array,e,i,r.byteOffset,r.count,s,o.byteStride);break;case t.EComponentType.UNSIGNED_SHORT:l=a._buildArrayBuffer(Uint16Array,e,i,r.byteOffset,r.count,s,o.byteStride);break;case t.EComponentType.UNSIGNED_INT:l=a._buildArrayBuffer(Uint32Array,e,i,r.byteOffset,r.count,s,o.byteStride);break;case t.EComponentType.FLOAT:l=a._buildArrayBuffer(Float32Array,e,i,r.byteOffset,r.count,s,o.byteStride);break;default:throw new Error(e+": Invalid component type ("+r.componentType+")")}n(l)}))},n.prototype._getNumComponentsOfType=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._buildArrayBuffer=function(e,t,r,n,a,o,i){try{var n=r.byteOffset+(n||0),s=a*o;if(null==i||i===o*e.BYTES_PER_ELEMENT)return new e(r.buffer,n,s);for(var l=i/e.BYTES_PER_ELEMENT,u=new e(r.buffer,n,l*a),c=new e(s),f=0,d=0;d<s;){for(var h=0;h<o;h++)c[d]=u[f+h],d++;f+=l}return c}catch(e){throw new Error(t+": "+e)}},n.prototype._addPendingData=function(e){this._renderReady||this._renderPendingCount++,this._addLoaderPendingData(e)},n.prototype._removePendingData=function(e){this._renderReady||0==--this._renderPendingCount&&(this._renderReady=!0,this._onRenderReady()),this._removeLoaderPendingData(e)},n.prototype._addLoaderPendingData=function(e){this._loaderPendingCount++,this._loaderTrackers.forEach((function(t){return t._addPendingData(e)}))},n.prototype._removeLoaderPendingData=function(e){this._loaderTrackers.forEach((function(t){return t._removePendingData(e)})),0==--this._loaderPendingCount&&this._onComplete()},n.prototype._whenAction=function(e,t){var n=this,a=new r(function(){n._loaderTrackers.splice(n._loaderTrackers.indexOf(a)),t()});this._loaderTrackers.push(a),this._addLoaderPendingData(a),e(),this._removeLoaderPendingData(a)},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(r,n){var a=n.babylonMaterial;a.metallic=1,a.roughness=1;var o=n.pbrMetallicRoughness;if(o){if(a.albedoColor=o.baseColorFactor?e.Color3.FromArray(o.baseColorFactor):new e.Color3(1,1,1),a.metallic=null==o.metallicFactor?1:o.metallicFactor,a.roughness=null==o.roughnessFactor?1:o.roughnessFactor,o.baseColorTexture){var i=t.GLTFUtils.GetArrayItem(this._gltf.textures,o.baseColorTexture.index);if(!i)throw new Error(r+": Failed to find base color texture "+o.baseColorTexture.index);a.albedoTexture=this._loadTexture("#/textures/"+i.index,i,o.baseColorTexture.texCoord)}if(o.metallicRoughnessTexture){var i=t.GLTFUtils.GetArrayItem(this._gltf.textures,o.metallicRoughnessTexture.index);if(!i)throw new Error(r+": Failed to find metallic roughness texture "+o.metallicRoughnessTexture.index);a.metallicTexture=this._loadTexture("#/textures/"+i.index,i,o.metallicRoughnessTexture.texCoord),a.useMetallnessFromMetallicTextureBlue=!0,a.useRoughnessFromMetallicTextureGreen=!0,a.useRoughnessFromMetallicTextureAlpha=!1}this._loadMaterialAlphaProperties(r,n,o.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(r,n){var a=n.babylonMaterial;if(a.emissiveColor=n.emissiveFactor?e.Color3.FromArray(n.emissiveFactor):new e.Color3(0,0,0),n.doubleSided&&(a.backFaceCulling=!1,a.twoSidedLighting=!0),n.normalTexture){var o=t.GLTFUtils.GetArrayItem(this._gltf.textures,n.normalTexture.index);if(!o)throw new Error(r+": Failed to find normal texture "+n.normalTexture.index);a.bumpTexture=this._loadTexture("#/textures/"+o.index,o,n.normalTexture.texCoord),a.invertNormalMapX=!this._babylonScene.useRightHandedSystem,a.invertNormalMapY=this._babylonScene.useRightHandedSystem,null!=n.normalTexture.scale&&(a.bumpTexture.level=n.normalTexture.scale)}if(n.occlusionTexture){var o=t.GLTFUtils.GetArrayItem(this._gltf.textures,n.occlusionTexture.index);if(!o)throw new Error(r+": Failed to find occlusion texture "+n.occlusionTexture.index);a.ambientTexture=this._loadTexture("#/textures/"+o.index,o,n.occlusionTexture.texCoord),a.useAmbientInGrayScale=!0,null!=n.occlusionTexture.strength&&(a.ambientTextureStrength=n.occlusionTexture.strength)}if(n.emissiveTexture){var o=t.GLTFUtils.GetArrayItem(this._gltf.textures,n.emissiveTexture.index);if(!o)throw new Error(r+": Failed to find emissive texture "+n.emissiveTexture.index);a.emissiveTexture=this._loadTexture("#/textures/"+o.index,o,n.emissiveTexture.texCoord)}},n.prototype._loadMaterialAlphaProperties=function(e,t,r){var n=t.babylonMaterial;switch(t.alphaMode||"OPAQUE"){case"OPAQUE":break;case"MASK":n.alphaCutOff=null==t.alphaCutoff?.5:t.alphaCutoff,r&&(0==r[3]?n.alphaCutOff=1:n.alphaCutOff/=r[3]),n.albedoTexture&&(n.albedoTexture.hasAlpha=!0);break;case"BLEND":r&&(n.alpha=r[3]),n.albedoTexture&&(n.albedoTexture.hasAlpha=!0,n.useAlphaFromAlbedoTexture=!0);break;default:throw new Error(e+": Invalid alpha mode '"+t.alphaMode+"'")}},n.prototype._loadTexture=function(r,n,a){var o=this,i=null==n.sampler?{}:t.GLTFUtils.GetArrayItem(this._gltf.samplers,n.sampler);if(!i)throw new Error(r+": Failed to find sampler "+n.sampler);var s=i.minFilter===t.ETextureMinFilter.NEAREST||i.minFilter===t.ETextureMinFilter.LINEAR,l=t.GLTFUtils.GetTextureSamplingMode(i.magFilter,i.minFilter);this._addPendingData(n);var u=new e.Texture(null,this._babylonScene,s,!1,l,function(){o._tryCatchOnError((function(){o._removePendingData(n)}))},function(e){o._tryCatchOnError((function(){throw new Error(r+": "+e)}))});if(n.url)u.updateURL(n.url);else if(n.dataReadyObservable)n.dataReadyObservable.add((function(e){u.updateURL(e.url)}));else{n.dataReadyObservable=new e.Observable,n.dataReadyObservable.add((function(e){u.updateURL(e.url)}));var c=t.GLTFUtils.GetArrayItem(this._gltf.images,n.source);if(!c)throw new Error(r+": Failed to find source "+n.source);this._loadImage("#/images/"+c.index,c,(function(e){n.url=URL.createObjectURL(new Blob([e],{type:c.mimeType})),n.dataReadyObservable.notifyObservers(n)}))}return u.coordinatesIndex=a||0,u.wrapU=t.GLTFUtils.GetTextureWrapMode(i.wrapS),u.wrapV=t.GLTFUtils.GetTextureWrapMode(i.wrapT),u.name=n.name||"texture"+n.index,this._parent.onTextureLoaded&&this._parent.onTextureLoaded(u),u},n.prototype._loadImage=function(r,n,a){var o=this;if(n.uri){if(!t.GLTFUtils.ValidateUri(n.uri))throw new Error(r+": Uri '"+n.uri+"' is invalid");t.GLTFUtils.IsBase64(n.uri)?a(new Uint8Array(t.GLTFUtils.DecodeBase64(n.uri))):e.Tools.LoadFile(this._rootUrl+n.uri,(function(e){o._tryCatchOnError((function(){a(e)}))}),(function(e){o._tryCatchOnError((function(){o._onProgress(e)}))}),this._babylonScene.database,!0,(function(e){o._tryCatchOnError((function(){throw new Error(r+": Failed to load '"+n.uri+"'"+(e?": "+e.status+" "+e.statusText:""))}))}))}else{var i=t.GLTFUtils.GetArrayItem(this._gltf.bufferViews,n.bufferView);if(!i)throw new Error(r+": Failed to find buffer view "+n.bufferView);this._loadBufferViewAsync("#/bufferViews/"+i.index,i,a)}},n.prototype._tryCatchOnError=function(e){try{e()}catch(e){this._onError(e.message)}},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(t){var r=(function(){function r(){}return 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)),a=0;a<r;a++)n[a]=t.charCodeAt(a);return n.buffer},r.ValidateUri=function(e){return-1===e.indexOf("..")},r.AssignIndices=function(e){if(e)for(var t=0;t<e.length;t++)e[t].index=t},r.GetArrayItem=function(e,t){return e&&e[t]?e[t]:null},r.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}},r.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}},r})();t.GLTFUtils=r})(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,a){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){var r=this;if(!e.extensions)return!1;var n=e.extensions[this.name];return!!n&&(e.extensions[this.name]=void 0,t(n,(function(){e.extensions[r.name]=n})),!0)},e.TraverseNode=function(e,t,r,n,a){return this._ApplyExtensions((function(o){return o._traverseNode(e,t,r,n,a)}))},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(a){return a._loadMaterial(e,t,r,n)}))},e._ApplyExtensions=function(t){var r=e._Extensions;if(!r)return!1;for(var n=0;n<r.length;n++){var a=r[n];if(a.enabled&&t(a))return!0}return!1},e._Extensions=[],e})();e.GLTFLoaderExtension=t})(e.GLTF2||(e.GLTF2={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(t){!(function(r){var n=(function(r){function n(){return null!==r&&r.apply(this,arguments)||this}return __extends(n,r),Object.defineProperty(n.prototype,"name",{get:function(){return"MSFT_lod"},enumerable:!0,configurable:!0}),n.prototype._traverseNode=function(e,r,n,a,o){return this._loadExtension(n,(function(i,s){for(var l=i.ids.length-1;l>=0;l--){var u=t.GLTFUtils.GetArrayItem(e._gltf.nodes,i.ids[l]);if(!u)throw new Error(r+": Failed to find node "+i.ids[l]);e._traverseNode(r,u,a,o)}e._traverseNode(r,n,a,o),s()}))},n.prototype._loadNode=function(e,t,r){var n=this;return this._loadExtension(r,(function(a,o){var i=[r.index].concat(a.ids).map((function(t){return e._gltf.nodes[t]}));e._addLoaderPendingData(r),n._loadNodeLOD(e,t,i,i.length-1,(function(){e._removeLoaderPendingData(r),o()}))}))},n.prototype._loadNodeLOD=function(e,t,r,a,o){var i=this;e._whenAction((function(){e._loadNode(t,r[a])}),(function(){if(a!==r.length-1){r[a+1].babylonMesh.setEnabled(!1)}if(0===a)return void o();setTimeout((function(){i._loadNodeLOD(e,t,r,a-1,o)}),n.MinimalLODDelay)}))},n.prototype._loadMaterial=function(e,t,r,n){var a=this;return this._loadExtension(r,(function(o,i){var s=[r.index].concat(o.ids).map((function(t){return e._gltf.materials[t]}));e._addLoaderPendingData(r),a._loadMaterialLOD(e,t,s,s.length-1,n,(function(){r.extensions[a.name]=o,e._removeLoaderPendingData(r),i()}))}))},n.prototype._loadMaterialLOD=function(t,r,a,o,i,s){var l=this;t._loadMaterial(r,a[o],(function(u,c){if(i(u,c),0===o)return void s();t._executeWhenRenderReady((function(){e.BaseTexture.WhenAllReady(u.getActiveTextures(),(function(){setTimeout((function(){l._loadMaterialLOD(t,r,a,o-1,i,s)}),n.MinimalLODDelay)}))}))}))},n.MinimalLODDelay=250,n})(t.GLTFLoaderExtension);r.MSFTLOD=n,t.GLTFLoader.RegisterExtension(new n)})(t.Extensions||(t.Extensions={}))})(e.GLTF2||(e.GLTF2={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(t){!(function(r){var n=(function(r){function n(){return null!==r&&r.apply(this,arguments)||this}return __extends(n,r),Object.defineProperty(n.prototype,"name",{get:function(){return"KHR_materials_pbrSpecularGlossiness"},enumerable:!0,configurable:!0}),n.prototype._loadMaterial=function(e,t,r,n){var a=this;return this._loadExtension(r,(function(o,i){e._createPbrMaterial(r),e._loadMaterialBaseProperties(t,r),a._loadSpecularGlossinessProperties(e,t,r,o),n(r.babylonMaterial,!0)}))},n.prototype._loadSpecularGlossinessProperties=function(r,n,a,o){var i=a.babylonMaterial;if(i.albedoColor=o.diffuseFactor?e.Color3.FromArray(o.diffuseFactor):new e.Color3(1,1,1),i.reflectivityColor=o.specularFactor?e.Color3.FromArray(o.specularFactor):new e.Color3(1,1,1),i.microSurface=null==o.glossinessFactor?1:o.glossinessFactor,o.diffuseTexture){var s=t.GLTFUtils.GetArrayItem(r._gltf.textures,o.diffuseTexture.index);if(!s)throw new Error(n+": Failed to find diffuse texture "+o.diffuseTexture.index);i.albedoTexture=r._loadTexture("textures["+s.index+"]",s,o.diffuseTexture.texCoord)}if(o.specularGlossinessTexture){var s=t.GLTFUtils.GetArrayItem(r._gltf.textures,o.specularGlossinessTexture.index);if(!s)throw new Error(n+": Failed to find diffuse texture "+o.specularGlossinessTexture.index);i.reflectivityTexture=r._loadTexture("textures["+s.index+"]",s,o.specularGlossinessTexture.texCoord),i.reflectivityTexture.hasAlpha=!0,i.useMicroSurfaceFromReflectivityMapAlpha=!0}r._loadMaterialAlphaProperties(n,a,o.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){e&&e.BABYLON||( true?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.BJSLoaders=t():e.BABYLON=t())})(this,(function(){return BABYLON}));
  98827. /***/ }),
  98828. /* 21 */
  98829. /***/ (function(module, exports, __webpack_require__) {
  98830. var babylonDependency;try{babylonDependency=BABYLON||"undefined"!="function"&&__webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"../babylon.max\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()))}catch(e){babylonDependency=BABYLON||"undefined"!="function"&&__webpack_require__(0)}var BABYLON=babylonDependency,__decorate=this&&this.__decorate||function(e,i,t,n){var r,o=arguments.length,a=o<3?i:null===n?n=Object.getOwnPropertyDescriptor(i,t):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,i,t,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(i,t,a):r(i,t))||a);return o>3&&a&&Object.defineProperty(i,t,a),a},__extends=this&&this.__extends||(function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,i){e.__proto__=i}||function(e,i){for(var t in i)i.hasOwnProperty(t)&&(e[t]=i[t])};return function(i,t){function n(){this.constructor=i}e(i,t),i.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}})(),BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.CLIPPLANE=!1,i.POINTSIZE=!1,i.FOG=!1,i.NORMAL=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(e,i){return t.call(this,e,i)||this}return __extends(n,t),n.prototype.needAlphaBlending=function(){return!0},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},Object.defineProperty(n.prototype,"activeLight",{get:function(){return this._activeLight},set:function(e){this._activeLight=e},enumerable:!0,configurable:!0}),n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(this._activeLight)for(var f=0,l=t._lightSources;f<l.length;f++){var u=l[f];if(u.shadowEnabled){if(this._activeLight===u)break;var c=t._lightSources.indexOf(this._activeLight);-1!==c&&(t._lightSources.splice(c,1),t._lightSources.splice(0,0,this._activeLight));break}}if(e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,r),e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,1),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!1,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var d=new e.EffectFallbacks;o.FOG&&d.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,d,1),o.NUM_BONE_INFLUENCERS>0&&d.addCPUSkinningFallback(0,t);var m=[e.VertexBuffer.PositionKind];o.NORMAL&&m.push(e.VertexBuffer.NormalKind),e.MaterialHelper.PrepareAttributesForBones(m,t,o,d),e.MaterialHelper.PrepareAttributesForInstances(m,o);var v=o.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","alpha","mBones","vClipPlane"],p=new Array,g=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:h,uniformBuffersNames:g,samplers:p,defines:o,maxSimultaneousLights:1}),n.setEffect(a.getEngine().createEffect("shadowOnly",{attributes:m,uniformsNames:h,uniformBuffersNames:g,samplers:p,defines:v,fallbacks:d,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:1}},s),o)}return!!n.effect.isReady()&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(r,a)&&(e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._activeEffect.setFloat("alpha",this.alpha),this._activeEffect.setVector3("vEyePosition",r._mirroredCameraPosition?r._mirroredCameraPosition:r.activeCamera.position)),r.lightsEnabled&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o,1),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._afterBind(t,this._activeEffect)}},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.ShadowOnlyMaterial",i},n.prototype.getClassName=function(){return"ShadowOnlyMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},n})(e.PushMaterial);e.ShadowOnlyMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.shadowOnlyVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n",BABYLON.Effect.ShadersStore.shadowOnlyPixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform float alpha;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#include<lightFragment>[0..1]\n\nvec4 color=vec4(0.,0.,0.,(1.0-clamp(shadow,0.,1.))*alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.LIGHT0=!1,i.LIGHT1=!1,i.LIGHT2=!1,i.LIGHT3=!1,i.SPOTLIGHT0=!1,i.SPOTLIGHT1=!1,i.SPOTLIGHT2=!1,i.SPOTLIGHT3=!1,i.HEMILIGHT0=!1,i.HEMILIGHT1=!1,i.HEMILIGHT2=!1,i.HEMILIGHT3=!1,i.DIRLIGHT0=!1,i.DIRLIGHT1=!1,i.DIRLIGHT2=!1,i.DIRLIGHT3=!1,i.POINTLIGHT0=!1,i.POINTLIGHT1=!1,i.POINTLIGHT2=!1,i.POINTLIGHT3=!1,i.SHADOW0=!1,i.SHADOW1=!1,i.SHADOW2=!1,i.SHADOW3=!1,i.SHADOWS=!1,i.SHADOWESM0=!1,i.SHADOWESM1=!1,i.SHADOWESM2=!1,i.SHADOWESM3=!1,i.SHADOWPCF0=!1,i.SHADOWPCF1=!1,i.SHADOWPCF2=!1,i.SHADOWPCF3=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r._maxSimultaneousLights=4,r.topColor=new e.Color3(1,0,0),r.topColorAlpha=1,r.bottomColor=new e.Color3(0,0,1),r.bottomColorAlpha=1,r.offset=0,r.smoothness=1,r.disableLighting=!1,r._scaledDiffuse=new e.Color3,r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.alpha<1||this.topColorAlpha<1||this.bottomColorAlpha<1},n.prototype.needAlphaTesting=function(){return!0},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,r),e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,this._maxSimultaneousLights),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!1,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,f),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.NORMAL&&l.push(e.VertexBuffer.NormalKind),o.UV1&&l.push(e.VertexBuffer.UVKind),o.UV2&&l.push(e.VertexBuffer.UV2Kind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","diffuseMatrix","topColor","bottomColor","offset","smoothness"],d=["diffuseSampler"],m=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:m,samplers:d,defines:o,maxSimultaneousLights:4}),n.setEffect(a.getEngine().createEffect("gradient",{attributes:l,uniformsNames:c,uniformBuffersNames:m,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},s),o)}return!!n.effect.isReady()&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._effect),this._mustRebind(r,a)&&(e.MaterialHelper.BindClipPlane(this._effect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._activeEffect.setVector3("vEyePosition",r._mirroredCameraPosition?r._mirroredCameraPosition:r.activeCamera.position)),this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._activeEffect.setColor4("topColor",this.topColor,this.topColorAlpha),this._activeEffect.setColor4("bottomColor",this.bottomColor,this.bottomColorAlpha),this._activeEffect.setFloat("offset",this.offset),this._activeEffect.setFloat("smoothness",this.smoothness),this._afterBind(t,this._activeEffect)}},n.prototype.getAnimatables=function(){return[]},n.prototype.dispose=function(e){t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.GradientMaterial",i},n.prototype.getClassName=function(){return"GradientMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),__decorate([e.serializeAsColor3()],n.prototype,"topColor",void 0),__decorate([e.serialize()],n.prototype,"topColorAlpha",void 0),__decorate([e.serializeAsColor3()],n.prototype,"bottomColor",void 0),__decorate([e.serialize()],n.prototype,"bottomColorAlpha",void 0),__decorate([e.serialize()],n.prototype,"offset",void 0),__decorate([e.serialize()],n.prototype,"smoothness",void 0),__decorate([e.serialize()],n.prototype,"disableLighting",void 0),n})(e.PushMaterial);e.GradientMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.gradientVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex> \ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n",BABYLON.Effect.ShadersStore.gradientPixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n\nuniform vec4 topColor;\nuniform vec4 bottomColor;\nuniform float offset;\nuniform float smoothness;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\nfloat h=normalize(vPositionW).y+offset;\nfloat mysmoothness=clamp(smoothness,0.01,max(smoothness,10.));\nvec4 baseColor=mix(bottomColor,topColor,max(pow(max(h,0.0),mysmoothness),0.0));\n\nvec3 diffuseColor=baseColor.rgb;\n\nfloat alpha=baseColor.a;\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}\n";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.LIGHT0=!1,i.LIGHT1=!1,i.LIGHT2=!1,i.LIGHT3=!1,i.SPOTLIGHT0=!1,i.SPOTLIGHT1=!1,i.SPOTLIGHT2=!1,i.SPOTLIGHT3=!1,i.HEMILIGHT0=!1,i.HEMILIGHT1=!1,i.HEMILIGHT2=!1,i.HEMILIGHT3=!1,i.DIRLIGHT0=!1,i.DIRLIGHT1=!1,i.DIRLIGHT2=!1,i.DIRLIGHT3=!1,i.POINTLIGHT0=!1,i.POINTLIGHT1=!1,i.POINTLIGHT2=!1,i.POINTLIGHT3=!1,i.SHADOW0=!1,i.SHADOW1=!1,i.SHADOW2=!1,i.SHADOW3=!1,i.SHADOWS=!1,i.SHADOWESM0=!1,i.SHADOWESM1=!1,i.SHADOWESM2=!1,i.SHADOWESM3=!1,i.SHADOWPCF0=!1,i.SHADOWPCF1=!1,i.SHADOWPCF2=!1,i.SHADOWPCF3=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.diffuseColor=new e.Color3(1,1,1),r._disableLighting=!1,r._maxSimultaneousLights=4,r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(o._areTexturesDirty&&(o._needUVs=!1,a.texturesEnabled&&this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;o._needUVs=!0,o.DIFFUSE=!0}if(e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,this._maxSimultaneousLights,this._disableLighting),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,r),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,f),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.NORMAL&&l.push(e.VertexBuffer.NormalKind),o.UV1&&l.push(e.VertexBuffer.UVKind),o.UV2&&l.push(e.VertexBuffer.UV2Kind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","diffuseMatrix"],d=["diffuseSampler"],m=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:m,samplers:d,defines:o,maxSimultaneousLights:4}),n.setEffect(a.getEngine().createEffect("normal",{attributes:l,uniformsNames:c,uniformBuffersNames:m,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},s),o)}return!!n.effect.isReady()&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(r,a)&&(this.diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this.diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._activeEffect.setVector3("vEyePosition",r._mirroredCameraPosition?r._mirroredCameraPosition:r.activeCamera.position)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._afterBind(t,this._activeEffect)}},n.prototype.getAnimatables=function(){var e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||this.diffuseTexture===e},n.prototype.dispose=function(e){this.diffuseTexture&&this.diffuseTexture.dispose(),t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.NormalMaterial",i},n.prototype.getClassName=function(){return"NormalMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serializeAsTexture("diffuseTexture")],n.prototype,"_diffuseTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture",void 0),__decorate([e.serializeAsColor3()],n.prototype,"diffuseColor",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),n})(e.PushMaterial);e.NormalMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.normalVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n",BABYLON.Effect.ShadersStore.normalPixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef NORMAL\nbaseColor=mix(baseColor,vec4(vNormalW,1.0),0.5);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.LIGHT0=!1,i.LIGHT1=!1,i.LIGHT2=!1,i.LIGHT3=!1,i.SPOTLIGHT0=!1,i.SPOTLIGHT1=!1,i.SPOTLIGHT2=!1,i.SPOTLIGHT3=!1,i.HEMILIGHT0=!1,i.HEMILIGHT1=!1,i.HEMILIGHT2=!1,i.HEMILIGHT3=!1,i.DIRLIGHT0=!1,i.DIRLIGHT1=!1,i.DIRLIGHT2=!1,i.DIRLIGHT3=!1,i.POINTLIGHT0=!1,i.POINTLIGHT1=!1,i.POINTLIGHT2=!1,i.POINTLIGHT3=!1,i.SHADOW0=!1,i.SHADOW1=!1,i.SHADOW2=!1,i.SHADOW3=!1,i.SHADOWS=!1,i.SHADOWESM0=!1,i.SHADOWESM1=!1,i.SHADOWESM2=!1,i.SHADOWESM3=!1,i.SHADOWPCF0=!1,i.SHADOWPCF1=!1,i.SHADOWPCF2=!1,i.SHADOWPCF3=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.speed=1,r.movingSpeed=1,r.lowFrequencySpeed=1,r.fogDensity=.15,r._lastTime=0,r.diffuseColor=new e.Color3(1,1,1),r._disableLighting=!1,r._maxSimultaneousLights=4,r._scaledDiffuse=new e.Color3,r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(o._areTexturesDirty&&(o._needUVs=!1,a.texturesEnabled&&this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;o._needUVs=!0,o.DIFFUSE=!0}if(e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,this._maxSimultaneousLights,this._disableLighting),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,r),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,f),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.NORMAL&&l.push(e.VertexBuffer.NormalKind),o.UV1&&l.push(e.VertexBuffer.UVKind),o.UV2&&l.push(e.VertexBuffer.UV2Kind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","diffuseMatrix","time","speed","movingSpeed","fogColor","fogDensity","lowFrequencySpeed"],d=["diffuseSampler","noiseTexture"],m=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:m,samplers:d,defines:o,maxSimultaneousLights:this.maxSimultaneousLights}),n.setEffect(a.getEngine().createEffect("lava",{attributes:l,uniformsNames:c,uniformBuffersNames:m,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},s),o)}return!!n.effect.isReady()&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(r,a)&&(this.diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this.diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),this.noiseTexture&&this._activeEffect.setTexture("noiseTexture",this.noiseTexture),e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._activeEffect.setVector3("vEyePosition",r._mirroredCameraPosition?r._mirroredCameraPosition:r.activeCamera.position)),this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._lastTime+=r.getEngine().getDeltaTime(),this._activeEffect.setFloat("time",this._lastTime*this.speed/1e3),this.fogColor||(this.fogColor=e.Color3.Black()),this._activeEffect.setColor3("fogColor",this.fogColor),this._activeEffect.setFloat("fogDensity",this.fogDensity),this._activeEffect.setFloat("lowFrequencySpeed",this.lowFrequencySpeed),this._activeEffect.setFloat("movingSpeed",this.movingSpeed),this._afterBind(t,this._activeEffect)}},n.prototype.getAnimatables=function(){var e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.noiseTexture&&this.noiseTexture.animations&&this.noiseTexture.animations.length>0&&e.push(this.noiseTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||this.diffuseTexture===e},n.prototype.dispose=function(e){this.diffuseTexture&&this.diffuseTexture.dispose(),this.noiseTexture&&this.noiseTexture.dispose(),t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.LavaMaterial",i},n.prototype.getClassName=function(){return"LavaMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serializeAsTexture("diffuseTexture")],n.prototype,"_diffuseTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture",void 0),__decorate([e.serializeAsTexture()],n.prototype,"noiseTexture",void 0),__decorate([e.serializeAsColor3()],n.prototype,"fogColor",void 0),__decorate([e.serialize()],n.prototype,"speed",void 0),__decorate([e.serialize()],n.prototype,"movingSpeed",void 0),
  98831. __decorate([e.serialize()],n.prototype,"lowFrequencySpeed",void 0),__decorate([e.serialize()],n.prototype,"fogDensity",void 0),__decorate([e.serializeAsColor3()],n.prototype,"diffuseColor",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),n})(e.PushMaterial);e.LavaMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.lavaVertexShader="precision highp float;\n\nuniform float time;\nuniform float lowFrequencySpeed;\n\nvarying float noise;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n\n\nvec3 mod289(vec3 x)\n{\nreturn x-floor(x*(1.0/289.0))*289.0;\n}\nvec4 mod289(vec4 x)\n{\nreturn x-floor(x*(1.0/289.0))*289.0;\n}\nvec4 permute(vec4 x)\n{\nreturn mod289(((x*34.0)+1.0)*x);\n}\nvec4 taylorInvSqrt(vec4 r)\n{\nreturn 1.79284291400159-0.85373472095314*r;\n}\nvec3 fade(vec3 t) {\nreturn t*t*t*(t*(t*6.0-15.0)+10.0);\n}\n\nfloat pnoise(vec3 P,vec3 rep)\n{\nvec3 Pi0=mod(floor(P),rep); \nvec3 Pi1=mod(Pi0+vec3(1.0),rep); \nPi0=mod289(Pi0);\nPi1=mod289(Pi1);\nvec3 Pf0=fract(P); \nvec3 Pf1=Pf0-vec3(1.0); \nvec4 ix=vec4(Pi0.x,Pi1.x,Pi0.x,Pi1.x);\nvec4 iy=vec4(Pi0.yy,Pi1.yy);\nvec4 iz0=Pi0.zzzz;\nvec4 iz1=Pi1.zzzz;\nvec4 ixy=permute(permute(ix)+iy);\nvec4 ixy0=permute(ixy+iz0);\nvec4 ixy1=permute(ixy+iz1);\nvec4 gx0=ixy0*(1.0/7.0);\nvec4 gy0=fract(floor(gx0)*(1.0/7.0))-0.5;\ngx0=fract(gx0);\nvec4 gz0=vec4(0.5)-abs(gx0)-abs(gy0);\nvec4 sz0=step(gz0,vec4(0.0));\ngx0-=sz0*(step(0.0,gx0)-0.5);\ngy0-=sz0*(step(0.0,gy0)-0.5);\nvec4 gx1=ixy1*(1.0/7.0);\nvec4 gy1=fract(floor(gx1)*(1.0/7.0))-0.5;\ngx1=fract(gx1);\nvec4 gz1=vec4(0.5)-abs(gx1)-abs(gy1);\nvec4 sz1=step(gz1,vec4(0.0));\ngx1-=sz1*(step(0.0,gx1)-0.5);\ngy1-=sz1*(step(0.0,gy1)-0.5);\nvec3 g000=vec3(gx0.x,gy0.x,gz0.x);\nvec3 g100=vec3(gx0.y,gy0.y,gz0.y);\nvec3 g010=vec3(gx0.z,gy0.z,gz0.z);\nvec3 g110=vec3(gx0.w,gy0.w,gz0.w);\nvec3 g001=vec3(gx1.x,gy1.x,gz1.x);\nvec3 g101=vec3(gx1.y,gy1.y,gz1.y);\nvec3 g011=vec3(gx1.z,gy1.z,gz1.z);\nvec3 g111=vec3(gx1.w,gy1.w,gz1.w);\nvec4 norm0=taylorInvSqrt(vec4(dot(g000,g000),dot(g010,g010),dot(g100,g100),dot(g110,g110)));\ng000*=norm0.x;\ng010*=norm0.y;\ng100*=norm0.z;\ng110*=norm0.w;\nvec4 norm1=taylorInvSqrt(vec4(dot(g001,g001),dot(g011,g011),dot(g101,g101),dot(g111,g111)));\ng001*=norm1.x;\ng011*=norm1.y;\ng101*=norm1.z;\ng111*=norm1.w;\nfloat n000=dot(g000,Pf0);\nfloat n100=dot(g100,vec3(Pf1.x,Pf0.yz));\nfloat n010=dot(g010,vec3(Pf0.x,Pf1.y,Pf0.z));\nfloat n110=dot(g110,vec3(Pf1.xy,Pf0.z));\nfloat n001=dot(g001,vec3(Pf0.xy,Pf1.z));\nfloat n101=dot(g101,vec3(Pf1.x,Pf0.y,Pf1.z));\nfloat n011=dot(g011,vec3(Pf0.x,Pf1.yz));\nfloat n111=dot(g111,Pf1);\nvec3 fade_xyz=fade(Pf0);\nvec4 n_z=mix(vec4(n000,n100,n010,n110),vec4(n001,n101,n011,n111),fade_xyz.z);\nvec2 n_yz=mix(n_z.xy,n_z.zw,fade_xyz.y);\nfloat n_xyz=mix(n_yz.x,n_yz.y,fade_xyz.x);\nreturn 2.2*n_xyz;\n}\n\nfloat turbulence( vec3 p ) {\nfloat w=100.0;\nfloat t=-.5;\nfor (float f=1.0 ; f<=10.0 ; f++ ){\nfloat power=pow( 2.0,f );\nt+=abs( pnoise( vec3( power*p ),vec3( 10.0,10.0,10.0 ) )/power );\n}\nreturn t;\n}\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef NORMAL\n\nnoise=10.0*-.10*turbulence( .5*normal+time*1.15 );\n\nfloat b=lowFrequencySpeed*5.0*pnoise( 0.05*position +vec3(time*1.025),vec3( 100.0 ) );\n\nfloat displacement =-1.5*noise+b;\n\nvec3 newPosition=position+normal*displacement;\ngl_Position=viewProjection*finalWorld*vec4( newPosition,1.0 );\nvec4 worldPos=finalWorld*vec4(newPosition,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}",BABYLON.Effect.ShadersStore.lavaPixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n\nvarying vec3 vPositionW;\n\nuniform float time;\nuniform float speed;\nuniform float movingSpeed;\nuniform vec3 fogColor;\nuniform sampler2D noiseTexture;\nuniform float fogDensity;\n\nvarying float noise;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nfloat random( vec3 scale,float seed ){\nreturn fract( sin( dot( gl_FragCoord.xyz+seed,scale ) )*43758.5453+seed ) ;\n}\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\n\nvec4 noiseTex=texture2D( noiseTexture,vDiffuseUV );\nvec2 T1=vDiffuseUV+vec2( 1.5,-1.5 )*time*0.02;\nvec2 T2=vDiffuseUV+vec2( -0.5,2.0 )*time*0.01*speed;\nT1.x+=noiseTex.x*2.0;\nT1.y+=noiseTex.y*2.0;\nT2.x-=noiseTex.y*0.2+time*0.001*movingSpeed;\nT2.y+=noiseTex.z*0.2+time*0.002*movingSpeed;\nfloat p=texture2D( noiseTexture,T1*3.0 ).a;\nvec4 lavaColor=texture2D( diffuseSampler,T2*4.0);\nvec4 temp=lavaColor*( vec4( p,p,p,p )*2. )+( lavaColor*lavaColor-0.1 );\nbaseColor=temp;\nfloat depth=gl_FragCoord.z*4.0;\nconst float LOG2=1.442695;\nfloat fogFactor=exp2(-fogDensity*fogDensity*depth*depth*LOG2 );\nfogFactor=1.0-clamp( fogFactor,0.0,1.0 );\nbaseColor=mix( baseColor,vec4( fogColor,baseColor.w ),fogFactor );\ndiffuseColor=baseColor.rgb;\n\n\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.diffuseColor=new e.Color3(1,1,1),r._disableLighting=!1,r._maxSimultaneousLights=4,r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(o._areTexturesDirty&&(o._needUVs=!1,a.texturesEnabled&&this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;o._needUVs=!0,o.DIFFUSE=!0}if(e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,this._maxSimultaneousLights,this._disableLighting),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,r),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,f,this.maxSimultaneousLights),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.NORMAL&&l.push(e.VertexBuffer.NormalKind),o.UV1&&l.push(e.VertexBuffer.UVKind),o.UV2&&l.push(e.VertexBuffer.UV2Kind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","diffuseMatrix"],d=["diffuseSampler"],m=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:m,samplers:d,defines:o,maxSimultaneousLights:this.maxSimultaneousLights}),n.setEffect(a.getEngine().createEffect("simple",{attributes:l,uniformsNames:c,uniformBuffersNames:m,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights-1}},s),o)}return!!n.effect.isReady()&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(r,a)&&(this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._activeEffect.setVector3("vEyePosition",r._mirroredCameraPosition?r._mirroredCameraPosition:r.activeCamera.position)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._afterBind(t,this._activeEffect)}},n.prototype.getAnimatables=function(){var e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||this.diffuseTexture===e},n.prototype.dispose=function(e){this._diffuseTexture&&this._diffuseTexture.dispose(),t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.SimpleMaterial",i},n.prototype.getClassName=function(){return"SimpleMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serializeAsTexture("diffuseTexture")],n.prototype,"_diffuseTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture",void 0),__decorate([e.serializeAsColor3("diffuseColor")],n.prototype,"diffuseColor",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),n})(e.PushMaterial);e.SimpleMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.simpleVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n",BABYLON.Effect.ShadersStore.simplePixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif \n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.BUMP=!1,i.REFLECTION=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.SPECULARTERM=!1,i.LOGARITHMICDEPTH=!1,i.FRESNELSEPARATE=!1,i.BUMPSUPERIMPOSE=!1,i.BUMPAFFECTSREFLECTION=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n,r){void 0===r&&(r=new e.Vector2(512,512));var o=t.call(this,i,n)||this;return o.renderTargetSize=r,o.diffuseColor=new e.Color3(1,1,1),o.specularColor=new e.Color3(0,0,0),o.specularPower=64,o._disableLighting=!1,o._maxSimultaneousLights=4,o.windForce=6,o.windDirection=new e.Vector2(0,1),o.waveHeight=.4,o.bumpHeight=.4,o._bumpSuperimpose=!1,o._fresnelSeparate=!1,o._bumpAffectsReflection=!1,o.waterColor=new e.Color3(.1,.1,.6),o.colorBlendFactor=.2,o.waterColor2=new e.Color3(.1,.1,.6),o.colorBlendFactor2=.2,o.waveLength=.1,o.waveSpeed=1,o._renderTargets=new e.SmartArray(16),o._mesh=null,o._reflectionTransform=e.Matrix.Zero(),o._lastTime=0,o._lastDeltaTime=0,o._createRenderTargets(n,r),o.getRenderTargetTextures=function(){return o._renderTargets.reset(),o._renderTargets.push(o._reflectionRTT),o._renderTargets.push(o._refractionRTT),o._renderTargets},o}return __extends(n,t),Object.defineProperty(n.prototype,"useLogarithmicDepth",{get:function(){return this._useLogarithmicDepth},set:function(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported,this._markAllSubMeshesAsMiscDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"refractionTexture",{get:function(){return this._refractionRTT},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"reflectionTexture",{get:function(){return this._reflectionRTT},enumerable:!0,configurable:!0}),n.prototype.addToRenderList=function(e){this._refractionRTT.renderList.push(e),this._reflectionRTT.renderList.push(e)},n.prototype.enableRenderTargets=function(e){var i=e?1:0;this._refractionRTT.refreshRate=i,this._reflectionRTT.refreshRate=i},n.prototype.getRenderList=function(){return this._refractionRTT.renderList},Object.defineProperty(n.prototype,"renderTargetsEnabled",{get:function(){return!(0===this._refractionRTT.refreshRate)},enumerable:!0,configurable:!0}),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(o._areTexturesDirty&&(o._needUVs=!1,a.texturesEnabled)){if(this.bumpTexture&&e.StandardMaterial.BumpTextureEnabled){if(!this.bumpTexture.isReady())return!1;o._needUVs=!0,o.BUMP=!0}e.StandardMaterial.ReflectionTextureEnabled&&(o.REFLECTION=!0)}if(e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,r),e.MaterialHelper.PrepareDefinesForMisc(t,a,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,o),o._areMiscDirty&&(this._fresnelSeparate&&(o.FRESNELSEPARATE=!0),this._bumpSuperimpose&&(o.BUMPSUPERIMPOSE=!0),this._bumpAffectsReflection&&(o.BUMPAFFECTSREFLECTION=!0)),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!0,this._maxSimultaneousLights,this._disableLighting),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!0),this._mesh=t,o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),o.LOGARITHMICDEPTH&&f.addFallback(0,"LOGARITHMICDEPTH"),e.MaterialHelper.HandleFallbacksForShadows(o,f,this.maxSimultaneousLights),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.NORMAL&&l.push(e.VertexBuffer.NormalKind),o.UV1&&l.push(e.VertexBuffer.UVKind),o.UV2&&l.push(e.VertexBuffer.UV2Kind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vNormalInfos","mBones","vClipPlane","normalMatrix","logarithmicDepthConstant","worldReflectionViewProjection","windDirection","waveLength","time","windForce","cameraPosition","bumpHeight","waveHeight","waterColor","waterColor2","colorBlendFactor","colorBlendFactor2","waveSpeed"],d=["normalSampler","refractionSampler","reflectionSampler"],m=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:m,samplers:d,defines:o,maxSimultaneousLights:this.maxSimultaneousLights}),n.setEffect(a.getEngine().createEffect("water",{attributes:l,uniformsNames:c,uniformBuffersNames:m,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},s),o)}return!!n.effect.isReady()&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(r,a)&&(this.bumpTexture&&e.StandardMaterial.BumpTextureEnabled&&(this._activeEffect.setTexture("normalSampler",this.bumpTexture),this._activeEffect.setFloat2("vNormalInfos",this.bumpTexture.coordinatesIndex,this.bumpTexture.level),this._activeEffect.setMatrix("normalMatrix",this.bumpTexture.getTextureMatrix())),e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._activeEffect.setVector3("vEyePosition",r._mirroredCameraPosition?r._mirroredCameraPosition:r.activeCamera.position)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),o.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),e.MaterialHelper.BindLogDepth(o,this._activeEffect,r),e.StandardMaterial.ReflectionTextureEnabled&&(this._activeEffect.setTexture("refractionSampler",this._refractionRTT),this._activeEffect.setTexture("reflectionSampler",this._reflectionRTT));var s=this._mesh.getWorldMatrix().multiply(this._reflectionTransform).multiply(r.getProjectionMatrix()),f=r.getEngine().getDeltaTime();f!==this._lastDeltaTime&&(this._lastDeltaTime=f,this._lastTime+=this._lastDeltaTime),this._activeEffect.setMatrix("worldReflectionViewProjection",s),this._activeEffect.setVector2("windDirection",this.windDirection),this._activeEffect.setFloat("waveLength",this.waveLength),this._activeEffect.setFloat("time",this._lastTime/1e5),this._activeEffect.setFloat("windForce",this.windForce),this._activeEffect.setFloat("waveHeight",this.waveHeight),this._activeEffect.setFloat("bumpHeight",this.bumpHeight),this._activeEffect.setColor4("waterColor",this.waterColor,1),this._activeEffect.setFloat("colorBlendFactor",this.colorBlendFactor),this._activeEffect.setColor4("waterColor2",this.waterColor2,1),this._activeEffect.setFloat("colorBlendFactor2",this.colorBlendFactor2),this._activeEffect.setFloat("waveSpeed",this.waveSpeed),this._afterBind(t,this._activeEffect)}},n.prototype._createRenderTargets=function(i,t){var n=this;this._refractionRTT=new e.RenderTargetTexture(name+"_refraction",{width:t.x,height:t.y},i,!1,!0),this._refractionRTT.wrapU=e.Texture.MIRROR_ADDRESSMODE,this._refractionRTT.wrapV=e.Texture.MIRROR_ADDRESSMODE,this._refractionRTT.ignoreCameraViewport=!0,this._reflectionRTT=new e.RenderTargetTexture(name+"_reflection",{width:t.x,height:t.y},i,!1,!0),this._reflectionRTT.wrapU=e.Texture.MIRROR_ADDRESSMODE,this._reflectionRTT.wrapV=e.Texture.MIRROR_ADDRESSMODE,this._reflectionRTT.ignoreCameraViewport=!0;var r,o,a=null,s=e.Matrix.Zero();this._refractionRTT.onBeforeRender=function(){n._mesh&&(r=n._mesh.isVisible,n._mesh.isVisible=!1),a=i.clipPlane;var t=n._mesh?n._mesh.position.y:0;i.clipPlane=e.Plane.FromPositionAndNormal(new e.Vector3(0,t+.05,0),new e.Vector3(0,1,0))},this._refractionRTT.onAfterRender=function(){n._mesh&&(n._mesh.isVisible=r),i.clipPlane=a},this._reflectionRTT.onBeforeRender=function(){n._mesh&&(r=n._mesh.isVisible,n._mesh.isVisible=!1),a=i.clipPlane;var t=n._mesh?n._mesh.position.y:0;i.clipPlane=e.Plane.FromPositionAndNormal(new e.Vector3(0,t-.05,0),new e.Vector3(0,-1,0)),e.Matrix.ReflectionToRef(i.clipPlane,s),o=i.getViewMatrix(),s.multiplyToRef(o,n._reflectionTransform),i.setTransformMatrix(n._reflectionTransform,i.getProjectionMatrix()),i.getEngine().cullBackFaces=!1,i._mirroredCameraPosition=e.Vector3.TransformCoordinates(i.activeCamera.position,s)},this._reflectionRTT.onAfterRender=function(){n._mesh&&(n._mesh.isVisible=r),i.clipPlane=a,i.setTransformMatrix(o,i.getProjectionMatrix()),i.getEngine().cullBackFaces=!0,i._mirroredCameraPosition=null}},n.prototype.getAnimatables=function(){var e=[];return this.bumpTexture&&this.bumpTexture.animations&&this.bumpTexture.animations.length>0&&e.push(this.bumpTexture),this._reflectionRTT&&this._reflectionRTT.animations&&this._reflectionRTT.animations.length>0&&e.push(this._reflectionRTT),this._refractionRTT&&this._refractionRTT.animations&&this._refractionRTT.animations.length>0&&e.push(this._refractionRTT),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._bumpTexture&&e.push(this._bumpTexture),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||this._bumpTexture===e},n.prototype.dispose=function(e){this.bumpTexture&&this.bumpTexture.dispose();var i=this.getScene().customRenderTargets.indexOf(this._refractionRTT);-1!=i&&this.getScene().customRenderTargets.splice(i,1),i=-1,i=this.getScene().customRenderTargets.indexOf(this._reflectionRTT),-1!=i&&this.getScene().customRenderTargets.splice(i,1),this._reflectionRTT&&this._reflectionRTT.dispose(),this._refractionRTT&&this._refractionRTT.dispose(),t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.WaterMaterial",i.reflectionTexture.isRenderTarget=!0,i.refractionTexture.isRenderTarget=!0,i},n.prototype.getClassName=function(){return"WaterMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},n.CreateDefaultMesh=function(i,t){return e.Mesh.CreateGround(i,512,512,32,t,!1)},__decorate([e.serializeAsTexture("bumpTexture")],n.prototype,"_bumpTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"bumpTexture",void 0),__decorate([e.serializeAsColor3()],n.prototype,"diffuseColor",void 0),__decorate([e.serializeAsColor3()],n.prototype,"specularColor",void 0),__decorate([e.serialize()],n.prototype,"specularPower",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),__decorate([e.serialize()],n.prototype,"windForce",void 0),__decorate([e.serializeAsVector2()],n.prototype,"windDirection",void 0),__decorate([e.serialize()],n.prototype,"waveHeight",void 0),__decorate([e.serialize()],n.prototype,"bumpHeight",void 0),__decorate([e.serialize("bumpSuperimpose")],n.prototype,"_bumpSuperimpose",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsMiscDirty")],n.prototype,"bumpSuperimpose",void 0),__decorate([e.serialize("fresnelSeparate")],n.prototype,"_fresnelSeparate",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsMiscDirty")],n.prototype,"fresnelSeparate",void 0),__decorate([e.serialize("bumpAffectsReflection")],n.prototype,"_bumpAffectsReflection",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsMiscDirty")],n.prototype,"bumpAffectsReflection",void 0),__decorate([e.serializeAsColor3()],n.prototype,"waterColor",void 0),__decorate([e.serialize()],n.prototype,"colorBlendFactor",void 0),__decorate([e.serializeAsColor3()],n.prototype,"waterColor2",void 0),__decorate([e.serialize()],n.prototype,"colorBlendFactor2",void 0),__decorate([e.serialize()],n.prototype,"waveLength",void 0),__decorate([e.serialize()],n.prototype,"waveSpeed",void 0),__decorate([e.serialize()],n.prototype,"useLogarithmicDepth",null),n})(e.PushMaterial);e.WaterMaterial=t})(BABYLON||(BABYLON={})),
  98832. BABYLON.Effect.ShadersStore.waterVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef BUMP\nvarying vec2 vNormalUV;\n#ifdef BUMPSUPERIMPOSE\nvarying vec2 vNormalUV2;\n#endif\nuniform mat4 normalMatrix;\nuniform vec2 vNormalInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<logDepthDeclaration>\n\nuniform mat4 worldReflectionViewProjection;\nuniform vec2 windDirection;\nuniform float waveLength;\nuniform float time;\nuniform float windForce;\nuniform float waveHeight;\nuniform float waveSpeed;\n\nvarying vec3 vPosition;\nvarying vec3 vRefractionMapTexCoord;\nvarying vec3 vReflectionMapTexCoord;\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef BUMP\nif (vNormalInfos.x == 0.)\n{\nvNormalUV=vec2(normalMatrix*vec4((uv*1.0)/waveLength+time*windForce*windDirection,1.0,0.0));\n#ifdef BUMPSUPERIMPOSE\nvNormalUV2=vec2(normalMatrix*vec4((uv*0.721)/waveLength+time*1.2*windForce*windDirection,1.0,0.0));\n#endif\n}\nelse\n{\nvNormalUV=vec2(normalMatrix*vec4((uv2*1.0)/waveLength+time*windForce*windDirection ,1.0,0.0));\n#ifdef BUMPSUPERIMPOSE\nvNormalUV2=vec2(normalMatrix*vec4((uv2*0.721)/waveLength+time*1.2*windForce*windDirection ,1.0,0.0));\n#endif\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\nvec3 p=position;\nfloat newY=(sin(((p.x/0.05)+time*waveSpeed))*waveHeight*windDirection.x*5.0)\n+(cos(((p.z/0.05)+time*waveSpeed))*waveHeight*windDirection.y*5.0);\np.y+=abs(newY);\ngl_Position=viewProjection*finalWorld*vec4(p,1.0);\n#ifdef REFLECTION\nworldPos=viewProjection*finalWorld*vec4(p,1.0);\n\nvPosition=position;\nvRefractionMapTexCoord.x=0.5*(worldPos.w+worldPos.x);\nvRefractionMapTexCoord.y=0.5*(worldPos.w+worldPos.y);\nvRefractionMapTexCoord.z=worldPos.w;\nworldPos=worldReflectionViewProjection*vec4(position,1.0);\nvReflectionMapTexCoord.x=0.5*(worldPos.w+worldPos.x);\nvReflectionMapTexCoord.y=0.5*(worldPos.w+worldPos.y);\nvReflectionMapTexCoord.z=worldPos.w;\n#endif\n#include<logDepthVertex>\n}\n",BABYLON.Effect.ShadersStore.waterPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef BUMP\nvarying vec2 vNormalUV;\nvarying vec2 vNormalUV2;\nuniform sampler2D normalSampler;\nuniform vec2 vNormalInfos;\n#endif\nuniform sampler2D refractionSampler;\nuniform sampler2D reflectionSampler;\n\nconst float LOG2=1.442695;\nuniform vec3 cameraPosition;\nuniform vec4 waterColor;\nuniform float colorBlendFactor;\nuniform vec4 waterColor2;\nuniform float colorBlendFactor2;\nuniform float bumpHeight;\nuniform float time;\n\nvarying vec3 vRefractionMapTexCoord;\nvarying vec3 vReflectionMapTexCoord;\nvarying vec3 vPosition;\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n#ifdef BUMP\n#ifdef BUMPSUPERIMPOSE\nbaseColor=0.6*texture2D(normalSampler,vNormalUV)+0.4*texture2D(normalSampler,vec2(vNormalUV2.x,vNormalUV2.y));\n#else\nbaseColor=texture2D(normalSampler,vNormalUV);\n#endif\nvec3 bumpColor=baseColor.rgb;\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vNormalInfos.y;\n#else\nvec3 bumpColor=vec3(1.0);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec2 perturbation=bumpHeight*(baseColor.rg-0.5);\n#ifdef BUMPAFFECTSREFLECTION\nvec3 normalW=normalize(vNormalW+vec3(perturbation.x*8.0,0.0,perturbation.y*8.0));\nif (normalW.y<0.0) {\nnormalW.y=-normalW.y;\n}\n#else\nvec3 normalW=normalize(vNormalW);\n#endif\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\nvec2 perturbation=bumpHeight*(vec2(1.0,1.0)-0.5);\n#endif\n#ifdef FRESNELSEPARATE\n#ifdef REFLECTION\n\nvec3 eyeVector=normalize(vEyePosition-vPosition);\nvec2 projectedRefractionTexCoords=clamp(vRefractionMapTexCoord.xy/vRefractionMapTexCoord.z+perturbation*0.5,0.0,1.0);\nvec4 refractiveColor=texture2D(refractionSampler,projectedRefractionTexCoords);\nvec2 projectedReflectionTexCoords=clamp(vec2(\nvReflectionMapTexCoord.x/vReflectionMapTexCoord.z+perturbation.x*0.3,\nvReflectionMapTexCoord.y/vReflectionMapTexCoord.z+perturbation.y\n),0.0,1.0);\nvec4 reflectiveColor=texture2D(reflectionSampler,projectedReflectionTexCoords);\nvec3 upVector=vec3(0.0,1.0,0.0);\nfloat fresnelTerm=clamp(abs(pow(dot(eyeVector,upVector),3.0)),0.05,0.65);\nfloat IfresnelTerm=1.0-fresnelTerm;\nrefractiveColor=colorBlendFactor*waterColor+(1.0-colorBlendFactor)*refractiveColor;\nreflectiveColor=IfresnelTerm*colorBlendFactor2*waterColor+(1.0-colorBlendFactor2*IfresnelTerm)*reflectiveColor;\nvec4 combinedColor=refractiveColor*fresnelTerm+reflectiveColor*IfresnelTerm;\nbaseColor=combinedColor;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularBase=vec3(0.,0.,0.);\nvec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\nvec3 finalDiffuse=clamp(baseColor.rgb,0.0,1.0);\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#else \n#ifdef REFLECTION\n\nvec3 eyeVector=normalize(vEyePosition-vPosition);\nvec2 projectedRefractionTexCoords=clamp(vRefractionMapTexCoord.xy/vRefractionMapTexCoord.z+perturbation,0.0,1.0);\nvec4 refractiveColor=texture2D(refractionSampler,projectedRefractionTexCoords);\nvec2 projectedReflectionTexCoords=clamp(vReflectionMapTexCoord.xy/vReflectionMapTexCoord.z+perturbation,0.0,1.0);\nvec4 reflectiveColor=texture2D(reflectionSampler,projectedReflectionTexCoords);\nvec3 upVector=vec3(0.0,1.0,0.0);\nfloat fresnelTerm=max(dot(eyeVector,upVector),0.0);\nvec4 combinedColor=refractiveColor*fresnelTerm+reflectiveColor*(1.0-fresnelTerm);\nbaseColor=colorBlendFactor*waterColor+(1.0-colorBlendFactor)*combinedColor;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularBase=vec3(0.,0.,0.);\nvec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\nvec3 finalDiffuse=clamp(baseColor.rgb,0.0,1.0);\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#endif\n\nvec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include<logDepthFragment>\n#include<fogFragment>\ngl_FragColor=color;\n}\n";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.UV1=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.BonesPerMesh=0,i.NUM_BONE_INFLUENCERS=0,i.INSTANCES=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.diffuseColor=new e.Color3(1,1,1),r.speed=1,r._scaledDiffuse=new e.Color3,r._lastTime=0,r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return!1},n.prototype.needAlphaTesting=function(){return!0},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(o._areTexturesDirty&&(o._needUVs=!1,this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;o._needUVs=!0,o.DIFFUSE=!0}if(o._areMiscDirty&&(o.POINTSIZE=this.pointsCloud||a.forcePointsCloud,o.FOG=a.fogEnabled&&t.applyFog&&a.fogMode!==e.Scene.FOGMODE_NONE&&this.fogEnabled),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,r),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!1,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.UV1&&l.push(e.VertexBuffer.UVKind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString();n.setEffect(a.getEngine().createEffect("fire",{attributes:l,uniformsNames:["world","view","viewProjection","vEyePosition","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","diffuseMatrix","time","speed"],uniformBuffersNames:[],samplers:["diffuseSampler","distortionSampler","opacitySampler"],defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError},s),o)}return!!n.effect.isReady()&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene();if(n._materialDefines){var o=n.effect;if(this._activeEffect=o,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(r,o)){if(this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix()),this._activeEffect.setTexture("distortionSampler",this._distortionTexture),this._activeEffect.setTexture("opacitySampler",this._opacityTexture)),r.clipPlane){var a=r.clipPlane;this._activeEffect.setFloat4("vClipPlane",a.normal.x,a.normal.y,a.normal.z,a.d)}this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._activeEffect.setVector3("vEyePosition",r._mirroredCameraPosition?r._mirroredCameraPosition:r.activeCamera.position)}this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._lastTime+=r.getEngine().getDeltaTime(),this._activeEffect.setFloat("time",this._lastTime),this._activeEffect.setFloat("speed",this.speed),this._afterBind(t,this._activeEffect)}},n.prototype.getAnimatables=function(){var e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._distortionTexture&&this._distortionTexture.animations&&this._distortionTexture.animations.length>0&&e.push(this._distortionTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),this._distortionTexture&&e.push(this._distortionTexture),this._opacityTexture&&e.push(this._opacityTexture),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||(this._diffuseTexture===e||(this._distortionTexture===e||this._opacityTexture===e))},n.prototype.getClassName=function(){return"FireMaterial"},n.prototype.dispose=function(e){this._diffuseTexture&&this._diffuseTexture.dispose(),this._distortionTexture&&this._distortionTexture.dispose(),t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.customType="BABYLON.FireMaterial",e.diffuseColor=this.diffuseColor.asArray(),e.speed=this.speed,this._diffuseTexture&&(e._diffuseTexture=this._diffuseTexture.serialize()),this._distortionTexture&&(e._distortionTexture=this._distortionTexture.serialize()),this._opacityTexture&&(e._opacityTexture=this._opacityTexture.serialize()),e},n.Parse=function(i,t,r){var o=new n(i.name,t);return o.diffuseColor=e.Color3.FromArray(i.diffuseColor),o.speed=i.speed,o.alpha=i.alpha,o.id=i.id,e.Tags.AddTagsTo(o,i.tags),o.backFaceCulling=i.backFaceCulling,o.wireframe=i.wireframe,i._diffuseTexture&&(o._diffuseTexture=e.Texture.Parse(i._diffuseTexture,t,r)),i._distortionTexture&&(o._distortionTexture=e.Texture.Parse(i._distortionTexture,t,r)),i._opacityTexture&&(o._opacityTexture=e.Texture.Parse(i._opacityTexture,t,r)),i.checkReadyOnlyOnce&&(o.checkReadyOnlyOnce=i.checkReadyOnlyOnce),o},__decorate([e.serializeAsTexture("diffuseTexture")],n.prototype,"_diffuseTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture",void 0),__decorate([e.serializeAsTexture("distortionTexture")],n.prototype,"_distortionTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"distortionTexture",void 0),__decorate([e.serializeAsTexture("opacityTexture")],n.prototype,"_opacityTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"opacityTexture",void 0),__decorate([e.serialize("diffuseColor")],n.prototype,"diffuseColor",void 0),__decorate([e.serialize()],n.prototype,"speed",void 0),n})(e.PushMaterial);e.FireMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.fireVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n\nuniform float time;\nuniform float speed;\n#ifdef DIFFUSE\nvarying vec2 vDistortionCoords1;\nvarying vec2 vDistortionCoords2;\nvarying vec2 vDistortionCoords3;\n#endif\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n\n#ifdef DIFFUSE\nvDiffuseUV=uv;\nvDiffuseUV.y-=0.2;\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n#ifdef DIFFUSE\n\nvec3 layerSpeed=vec3(-0.2,-0.52,-0.1)*speed;\nvDistortionCoords1.x=uv.x;\nvDistortionCoords1.y=uv.y+layerSpeed.x*time/1000.0;\nvDistortionCoords2.x=uv.x;\nvDistortionCoords2.y=uv.y+layerSpeed.y*time/1000.0;\nvDistortionCoords3.x=uv.x;\nvDistortionCoords3.y=uv.y+layerSpeed.z*time/1000.0;\n#endif\n}\n",BABYLON.Effect.ShadersStore.firePixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\nuniform sampler2D distortionSampler;\nuniform sampler2D opacitySampler;\n#ifdef DIFFUSE\nvarying vec2 vDistortionCoords1;\nvarying vec2 vDistortionCoords2;\nvarying vec2 vDistortionCoords3;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nvec4 bx2(vec4 x)\n{\nreturn vec4(2.0)*x-vec4(1.0);\n}\nvoid main(void) {\n\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\n\nfloat alpha=1.0;\n#ifdef DIFFUSE\n\nconst float distortionAmount0=0.092;\nconst float distortionAmount1=0.092;\nconst float distortionAmount2=0.092;\nvec2 heightAttenuation=vec2(0.3,0.39);\nvec4 noise0=texture2D(distortionSampler,vDistortionCoords1);\nvec4 noise1=texture2D(distortionSampler,vDistortionCoords2);\nvec4 noise2=texture2D(distortionSampler,vDistortionCoords3);\nvec4 noiseSum=bx2(noise0)*distortionAmount0+bx2(noise1)*distortionAmount1+bx2(noise2)*distortionAmount2;\nvec4 perturbedBaseCoords=vec4(vDiffuseUV,0.0,1.0)+noiseSum*(vDiffuseUV.y*heightAttenuation.x+heightAttenuation.y);\nvec4 opacityColor=texture2D(opacitySampler,perturbedBaseCoords.xy);\n#ifdef ALPHATEST\nif (opacityColor.r<0.1)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor=texture2D(diffuseSampler,perturbedBaseCoords.xy)*2.0;\nbaseColor*=opacityColor;\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 diffuseBase=vec3(1.0,1.0,1.0);\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec4 color=vec4(baseColor.rgb,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.HEIGHTMAP=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.HIGHLEVEL=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.diffuseColor=new e.Color3(1,1,1),r.furLength=1,r.furAngle=0,r.furColor=new e.Color3(.44,.21,.02),r.furOffset=0,r.furSpacing=12,r.furGravity=new e.Vector3(0,0,0),r.furSpeed=100,r.furDensity=20,r._disableLighting=!1,r._maxSimultaneousLights=4,r.highLevelFur=!0,r._furTime=0,r}return __extends(n,t),Object.defineProperty(n.prototype,"furTime",{get:function(){return this._furTime},set:function(e){this._furTime=e},enumerable:!0,configurable:!0}),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.updateFur=function(){for(var e=1;e<this._meshes.length;e++){var i=this._meshes[e].material;i.furLength=this.furLength,i.furAngle=this.furAngle,i.furGravity=this.furGravity,i.furSpacing=this.furSpacing,i.furSpeed=this.furSpeed,i.furColor=this.furColor,i.diffuseTexture=this.diffuseTexture,i.furTexture=this.furTexture,i.highLevelFur=this.highLevelFur,i.furTime=this.furTime,i.furDensity=this.furDensity}},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(o._areTexturesDirty&&a.texturesEnabled){if(this.diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled){if(!this.diffuseTexture.isReady())return!1;o._needUVs=!0,o.DIFFUSE=!0}if(this.heightTexture&&s.getCaps().maxVertexTextureImageUnits){if(!this.heightTexture.isReady())return!1;o._needUVs=!0,o.HEIGHTMAP=!0}}if(this.highLevelFur!==o.HIGHLEVEL&&(o.HIGHLEVEL=!0,o.markAsUnprocessed()),e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,this._maxSimultaneousLights,this._disableLighting),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,r),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,f,this.maxSimultaneousLights),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.NORMAL&&l.push(e.VertexBuffer.NormalKind),o.UV1&&l.push(e.VertexBuffer.UVKind),o.UV2&&l.push(e.VertexBuffer.UV2Kind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","diffuseMatrix","furLength","furAngle","furColor","furOffset","furGravity","furTime","furSpacing","furDensity"],d=["diffuseSampler","heightTexture","furTexture"],m=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:m,samplers:d,defines:o,maxSimultaneousLights:this.maxSimultaneousLights}),n.setEffect(a.getEngine().createEffect("fur",{attributes:l,uniformsNames:c,uniformBuffersNames:m,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},s),o)}return!!n.effect.isReady()&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),r.getCachedMaterial()!==this&&(this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),this._heightTexture&&this._activeEffect.setTexture("heightTexture",this._heightTexture),e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._activeEffect.setVector3("vEyePosition",r._mirroredCameraPosition?r._mirroredCameraPosition:r.activeCamera.position)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._activeEffect.setFloat("furLength",this.furLength),this._activeEffect.setFloat("furAngle",this.furAngle),this._activeEffect.setColor4("furColor",this.furColor,1),this.highLevelFur&&(this._activeEffect.setVector3("furGravity",this.furGravity),this._activeEffect.setFloat("furOffset",this.furOffset),this._activeEffect.setFloat("furSpacing",this.furSpacing),this._activeEffect.setFloat("furDensity",this.furDensity),this._furTime+=this.getScene().getEngine().getDeltaTime()/this.furSpeed,this._activeEffect.setFloat("furTime",this._furTime),this._activeEffect.setTexture("furTexture",this.furTexture)),this._afterBind(t,this._activeEffect)}},n.prototype.getAnimatables=function(){var e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.heightTexture&&this.heightTexture.animations&&this.heightTexture.animations.length>0&&e.push(this.heightTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),this._heightTexture&&e.push(this._heightTexture),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||(this.diffuseTexture===e||this._heightTexture===e)},n.prototype.dispose=function(e){if(this.diffuseTexture&&this.diffuseTexture.dispose(),this._meshes)for(var i=1;i<this._meshes.length;i++)this._meshes[i].material.dispose(e),this._meshes[i].dispose();t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.FurMaterial",this._meshes&&(i.sourceMeshName=this._meshes[0].name,i.quality=this._meshes.length),i},n.prototype.getClassName=function(){return"FurMaterial"},n.Parse=function(i,t,r){var o=e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r);return i.sourceMeshName&&o.highLevelFur&&t.executeWhenReady((function(){var e=t.getMeshByName(i.sourceMeshName);if(e){var r=n.GenerateTexture("Fur Texture",t);o.furTexture=r,n.FurifyMesh(e,i.quality)}})),o},n.GenerateTexture=function(i,t){for(var n=new e.DynamicTexture("FurTexture "+i,256,t,!0),r=n.getContext(),o=0;o<2e4;++o)r.fillStyle="rgba(255, "+Math.floor(255*Math.random())+", "+Math.floor(255*Math.random())+", 1)",r.fillRect(Math.random()*n.getSize().width,Math.random()*n.getSize().height,2,2);return n.update(!1),n.wrapU=e.Texture.WRAP_ADDRESSMODE,n.wrapV=e.Texture.WRAP_ADDRESSMODE,n},n.FurifyMesh=function(i,t){var r,o=[i],a=i.material;if(!(a instanceof n))throw"The material of the source mesh must be a Fur Material";for(r=1;r<t;r++){var s=new e.FurMaterial(a.name+r,i.getScene());i.getScene().materials.pop(),e.Tags.EnableFor(s),e.Tags.AddTagsTo(s,"furShellMaterial"),s.furLength=a.furLength,s.furAngle=a.furAngle,s.furGravity=a.furGravity,s.furSpacing=a.furSpacing,s.furSpeed=a.furSpeed,s.furColor=a.furColor,s.diffuseTexture=a.diffuseTexture,s.furOffset=r/t,s.furTexture=a.furTexture,s.highLevelFur=a.highLevelFur,s.furTime=a.furTime,s.furDensity=a.furDensity;var f=i.clone(i.name+r);f.material=s,f.skeleton=i.skeleton,f.position=e.Vector3.Zero(),o.push(f)}for(r=1;r<o.length;r++)o[r].parent=i;return i.material._meshes=o,o},__decorate([e.serializeAsTexture("diffuseTexture")],n.prototype,"_diffuseTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture",void 0),__decorate([e.serializeAsTexture("heightTexture")],n.prototype,"_heightTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"heightTexture",void 0),__decorate([e.serializeAsColor3()],n.prototype,"diffuseColor",void 0),__decorate([e.serialize()],n.prototype,"furLength",void 0),__decorate([e.serialize()],n.prototype,"furAngle",void 0),__decorate([e.serializeAsColor3()],n.prototype,"furColor",void 0),__decorate([e.serialize()],n.prototype,"furOffset",void 0),__decorate([e.serialize()],n.prototype,"furSpacing",void 0),__decorate([e.serializeAsVector3()],n.prototype,"furGravity",void 0),__decorate([e.serialize()],n.prototype,"furSpeed",void 0),__decorate([e.serialize()],n.prototype,"furDensity",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),__decorate([e.serialize()],n.prototype,"highLevelFur",void 0),__decorate([e.serialize()],n.prototype,"furTime",null),n})(e.PushMaterial);e.FurMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.furVertexShader="precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform float furLength;\nuniform float furAngle;\n#ifdef HIGHLEVEL\nuniform float furOffset;\nuniform vec3 furGravity;\nuniform float furTime;\nuniform float furSpacing;\nuniform float furDensity;\n#endif\n#ifdef HEIGHTMAP\nuniform sampler2D heightTexture;\n#endif\n#ifdef HIGHLEVEL\nvarying vec2 vFurUV;\n#endif\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\nvarying float vfur_length;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nfloat Rand(vec3 rv) {\nfloat x=dot(rv,vec3(12.9898,78.233,24.65487));\nreturn fract(sin(x)*43758.5453);\n}\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\n\nfloat r=Rand(position);\n#ifdef HEIGHTMAP\n#if __VERSION__>100\nvfur_length=furLength*texture(heightTexture,uv).x;\n#else\nvfur_length=furLength*texture2D(heightTexture,uv).r;\n#endif\n#else \nvfur_length=(furLength*r);\n#endif\nvec3 tangent1=vec3(normal.y,-normal.x,0);\nvec3 tangent2=vec3(-normal.z,0,normal.x);\nr=Rand(tangent1*r);\nfloat J=(2.0+4.0*r);\nr=Rand(tangent2*r);\nfloat K=(2.0+2.0*r);\ntangent1=tangent1*J+tangent2*K;\ntangent1=normalize(tangent1);\nvec3 newPosition=position+normal*vfur_length*cos(furAngle)+tangent1*vfur_length*sin(furAngle);\n#ifdef HIGHLEVEL\n\nvec3 forceDirection=vec3(0.0,0.0,0.0);\nforceDirection.x=sin(furTime+position.x*0.05)*0.2;\nforceDirection.y=cos(furTime*0.7+position.y*0.04)*0.2;\nforceDirection.z=sin(furTime*0.7+position.z*0.04)*0.2;\nvec3 displacement=vec3(0.0,0.0,0.0);\ndisplacement=furGravity+forceDirection;\nfloat displacementFactor=pow(furOffset,3.0);\nvec3 aNormal=normal;\naNormal.xyz+=displacement*displacementFactor;\nnewPosition=vec3(newPosition.x,newPosition.y,newPosition.z)+(normalize(aNormal)*furOffset*furSpacing);\n#endif\n#ifdef NORMAL\n#ifdef HIGHLEVEL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0))*aNormal);\n#else\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#endif\n\ngl_Position=viewProjection*finalWorld*vec4(newPosition,1.0);\nvec4 worldPos=finalWorld*vec4(newPosition,1.0);\nvPositionW=vec3(worldPos);\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#ifdef HIGHLEVEL\nvFurUV=vDiffuseUV*furDensity;\n#endif\n#else\n#ifdef HIGHLEVEL\nvFurUV=uv*furDensity;\n#endif\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n",
  98833. BABYLON.Effect.ShadersStore.furPixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n\nuniform vec4 furColor;\nuniform float furLength;\nvarying vec3 vPositionW;\nvarying float vfur_length;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef HIGHLEVEL\nuniform float furOffset;\nuniform sampler2D furTexture;\nvarying vec2 vFurUV;\n#endif\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<fogFragmentDeclaration>\n#include<clipPlaneFragmentDeclaration>\nfloat Rand(vec3 rv) {\nfloat x=dot(rv,vec3(12.9898,78.233,24.65487));\nreturn fract(sin(x)*43758.5453);\n}\nvoid main(void) {\n\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=furColor;\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor*=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef HIGHLEVEL\n\nvec4 furTextureColor=texture2D(furTexture,vec2(vFurUV.x,vFurUV.y));\nif (furTextureColor.a<=0.0 || furTextureColor.g<furOffset) {\ndiscard;\n}\nfloat occlusion=mix(0.0,furTextureColor.b*1.2,furOffset);\nbaseColor=vec4(baseColor.xyz*occlusion,1.1-furOffset);\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase.rgb*baseColor.rgb,0.0,1.0);\n\n#ifdef HIGHLEVEL\nvec4 color=vec4(finalDiffuse,alpha);\n#else\nfloat r=vfur_length/furLength*0.5;\nvec4 color=vec4(finalDiffuse*(0.5+r),alpha);\n#endif\n#include<fogFragment>\ngl_FragColor=color;\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.BUMP=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.SPECULARTERM=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.diffuseColor=new e.Color3(1,1,1),r.specularColor=new e.Color3(0,0,0),r.specularPower=64,r._disableLighting=!1,r._maxSimultaneousLights=4,r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(a.texturesEnabled){if(this.mixTexture&&e.StandardMaterial.DiffuseTextureEnabled){if(!this.mixTexture.isReady())return!1;o._needUVs=!0,o.DIFFUSE=!0}(this.bumpTexture1||this.bumpTexture2||this.bumpTexture3)&&e.StandardMaterial.BumpTextureEnabled&&(o._needUVs=!0,o._needNormals=!0,o.BUMP=!0)}if(e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,this._maxSimultaneousLights,this._disableLighting),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,r),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,f,this.maxSimultaneousLights),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.NORMAL&&l.push(e.VertexBuffer.NormalKind),o.UV1&&l.push(e.VertexBuffer.UVKind),o.UV2&&l.push(e.VertexBuffer.UV2Kind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vTextureInfos","mBones","vClipPlane","textureMatrix","diffuse1Infos","diffuse2Infos","diffuse3Infos"],d=["textureSampler","diffuse1Sampler","diffuse2Sampler","diffuse3Sampler","bump1Sampler","bump2Sampler","bump3Sampler"],m=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:m,samplers:d,defines:o,maxSimultaneousLights:this.maxSimultaneousLights}),n.setEffect(a.getEngine().createEffect("terrain",{attributes:l,uniformsNames:c,uniformBuffersNames:m,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},s),o)}return!!n.effect.isReady()&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(r,a)&&(this.mixTexture&&(this._activeEffect.setTexture("textureSampler",this._mixTexture),this._activeEffect.setFloat2("vTextureInfos",this._mixTexture.coordinatesIndex,this._mixTexture.level),this._activeEffect.setMatrix("textureMatrix",this._mixTexture.getTextureMatrix()),e.StandardMaterial.DiffuseTextureEnabled&&(this._diffuseTexture1&&(this._activeEffect.setTexture("diffuse1Sampler",this._diffuseTexture1),this._activeEffect.setFloat2("diffuse1Infos",this._diffuseTexture1.uScale,this._diffuseTexture1.vScale)),this._diffuseTexture2&&(this._activeEffect.setTexture("diffuse2Sampler",this._diffuseTexture2),this._activeEffect.setFloat2("diffuse2Infos",this._diffuseTexture2.uScale,this._diffuseTexture2.vScale)),this._diffuseTexture3&&(this._activeEffect.setTexture("diffuse3Sampler",this._diffuseTexture3),this._activeEffect.setFloat2("diffuse3Infos",this._diffuseTexture3.uScale,this._diffuseTexture3.vScale))),e.StandardMaterial.BumpTextureEnabled&&r.getEngine().getCaps().standardDerivatives&&(this._bumpTexture1&&this._activeEffect.setTexture("bump1Sampler",this._bumpTexture1),this._bumpTexture2&&this._activeEffect.setTexture("bump2Sampler",this._bumpTexture2),this._bumpTexture3&&this._activeEffect.setTexture("bump3Sampler",this._bumpTexture3))),e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._activeEffect.setVector3("vEyePosition",r._mirroredCameraPosition?r._mirroredCameraPosition:r.activeCamera.position)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),o.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._afterBind(t,this._activeEffect)}},n.prototype.getAnimatables=function(){var e=[];return this.mixTexture&&this.mixTexture.animations&&this.mixTexture.animations.length>0&&e.push(this.mixTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._mixTexture&&e.push(this._mixTexture),this._diffuseTexture1&&e.push(this._diffuseTexture1),this._diffuseTexture2&&e.push(this._diffuseTexture2),this._diffuseTexture3&&e.push(this._diffuseTexture3),this._bumpTexture1&&e.push(this._bumpTexture1),this._bumpTexture2&&e.push(this._bumpTexture2),this._bumpTexture3&&e.push(this._bumpTexture3),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||(this._mixTexture===e||(this._diffuseTexture1===e||(this._diffuseTexture2===e||(this._diffuseTexture3===e||(this._bumpTexture1===e||(this._bumpTexture2===e||this._bumpTexture3===e))))))},n.prototype.dispose=function(e){this.mixTexture&&this.mixTexture.dispose(),t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.TerrainMaterial",i},n.prototype.getClassName=function(){return"TerrainMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serializeAsTexture("mixTexture")],n.prototype,"_mixTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"mixTexture",void 0),__decorate([e.serializeAsTexture("diffuseTexture1")],n.prototype,"_diffuseTexture1",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture1",void 0),__decorate([e.serializeAsTexture("diffuseTexture2")],n.prototype,"_diffuseTexture2",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture2",void 0),__decorate([e.serializeAsTexture("diffuseTexture3")],n.prototype,"_diffuseTexture3",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture3",void 0),__decorate([e.serializeAsTexture("bumpTexture1")],n.prototype,"_bumpTexture1",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"bumpTexture1",void 0),__decorate([e.serializeAsTexture("bumpTexture2")],n.prototype,"_bumpTexture2",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"bumpTexture2",void 0),__decorate([e.serializeAsTexture("bumpTexture3")],n.prototype,"_bumpTexture3",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"bumpTexture3",void 0),__decorate([e.serializeAsColor3()],n.prototype,"diffuseColor",void 0),__decorate([e.serializeAsColor3()],n.prototype,"specularColor",void 0),__decorate([e.serialize()],n.prototype,"specularPower",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),n})(e.PushMaterial);e.TerrainMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.terrainVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;\nuniform mat4 textureMatrix;\nuniform vec2 vTextureInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vTextureInfos.x == 0.)\n{\nvTextureUV=vec2(textureMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvTextureUV=vec2(textureMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n",BABYLON.Effect.ShadersStore.terrainPixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;\nuniform sampler2D textureSampler;\nuniform vec2 vTextureInfos;\nuniform sampler2D diffuse1Sampler;\nuniform sampler2D diffuse2Sampler;\nuniform sampler2D diffuse3Sampler;\nuniform vec2 diffuse1Infos;\nuniform vec2 diffuse2Infos;\nuniform vec2 diffuse3Infos;\n#endif\n#ifdef BUMP\nuniform sampler2D bump1Sampler;\nuniform sampler2D bump2Sampler;\nuniform sampler2D bump3Sampler;\n#endif\n\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,vec3 mixColor)\n{ \nvec3 bump1Color=texture2D(bump1Sampler,vTextureUV*diffuse1Infos).xyz;\nvec3 bump2Color=texture2D(bump2Sampler,vTextureUV*diffuse2Infos).xyz;\nvec3 bump3Color=texture2D(bump3Sampler,vTextureUV*diffuse3Infos).xyz;\nbump1Color.rgb*=mixColor.r;\nbump2Color.rgb=mix(bump1Color.rgb,bump2Color.rgb,mixColor.g);\nvec3 map=mix(bump2Color.rgb,bump3Color.rgb,mixColor.b);\nmap=map*255./127.-128./127.;\nmat3 TBN=cotangent_frame(vNormalW*vTextureInfos.y,-viewDir,vTextureUV);\nreturn normalize(TBN*map);\n}\n#endif\nvoid main(void) {\n\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(textureSampler,vTextureUV);\n#if defined(BUMP) && defined(DIFFUSE)\nnormalW=perturbNormal(viewDirectionW,baseColor.rgb);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vTextureInfos.y;\nvec4 diffuse1Color=texture2D(diffuse1Sampler,vTextureUV*diffuse1Infos);\nvec4 diffuse2Color=texture2D(diffuse2Sampler,vTextureUV*diffuse2Infos);\nvec4 diffuse3Color=texture2D(diffuse3Sampler,vTextureUV*diffuse3Infos);\ndiffuse1Color.rgb*=baseColor.r;\ndiffuse2Color.rgb=mix(diffuse1Color.rgb,diffuse2Color.rgb,baseColor.g);\nbaseColor.rgb=mix(diffuse2Color.rgb,diffuse3Color.rgb,baseColor.b);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor*baseColor.rgb,0.0,1.0);\n\nvec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}\n";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSEX=!1,i.DIFFUSEY=!1,i.DIFFUSEZ=!1,i.BUMPX=!1,i.BUMPY=!1,i.BUMPZ=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.SPECULARTERM=!1,i.NORMAL=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.tileSize=1,r.diffuseColor=new e.Color3(1,1,1),r.specularColor=new e.Color3(.2,.2,.2),r.specularPower=64,r._disableLighting=!1,r._maxSimultaneousLights=4,r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(o._areTexturesDirty&&a.texturesEnabled){if(e.StandardMaterial.DiffuseTextureEnabled)for(var f=[this.diffuseTextureX,this.diffuseTextureY,this.diffuseTextureZ],l=["DIFFUSEX","DIFFUSEY","DIFFUSEZ"],u=0;u<f.length;u++)if(f[u]){if(!f[u].isReady())return!1;o[l[u]]=!0}if(e.StandardMaterial.BumpTextureEnabled)for(var f=[this.normalTextureX,this.normalTextureY,this.normalTextureZ],l=["BUMPX","BUMPY","BUMPZ"],u=0;u<f.length;u++)if(f[u]){if(!f[u].isReady())return!1;o[l[u]]=!0}}if(e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,this._maxSimultaneousLights,this._disableLighting),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,r),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var c=new e.EffectFallbacks;o.FOG&&c.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,c,this.maxSimultaneousLights),o.NUM_BONE_INFLUENCERS>0&&c.addCPUSkinningFallback(0,t);var d=[e.VertexBuffer.PositionKind];o.NORMAL&&d.push(e.VertexBuffer.NormalKind),o.VERTEXCOLOR&&d.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(d,t,o,c),e.MaterialHelper.PrepareAttributesForInstances(d,o);var m=o.toString(),v=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","mBones","vClipPlane","tileSize"],h=["diffuseSamplerX","diffuseSamplerY","diffuseSamplerZ","normalSamplerX","normalSamplerY","normalSamplerZ"],p=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:v,uniformBuffersNames:p,samplers:h,defines:o,maxSimultaneousLights:this.maxSimultaneousLights}),n.setEffect(a.getEngine().createEffect("triplanar",{attributes:d,uniformsNames:v,uniformBuffersNames:p,samplers:h,defines:m,fallbacks:c,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},s),o)}return!!n.effect.isReady()&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._activeEffect.setFloat("tileSize",this.tileSize),r.getCachedMaterial()!==this&&(this.diffuseTextureX&&this._activeEffect.setTexture("diffuseSamplerX",this.diffuseTextureX),this.diffuseTextureY&&this._activeEffect.setTexture("diffuseSamplerY",this.diffuseTextureY),this.diffuseTextureZ&&this._activeEffect.setTexture("diffuseSamplerZ",this.diffuseTextureZ),this.normalTextureX&&this._activeEffect.setTexture("normalSamplerX",this.normalTextureX),this.normalTextureY&&this._activeEffect.setTexture("normalSamplerY",this.normalTextureY),this.normalTextureZ&&this._activeEffect.setTexture("normalSamplerZ",this.normalTextureZ),e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._activeEffect.setVector3("vEyePosition",r._mirroredCameraPosition?r._mirroredCameraPosition:r.activeCamera.position)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),o.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._afterBind(t,this._activeEffect)}},n.prototype.getAnimatables=function(){var e=[];return this.mixTexture&&this.mixTexture.animations&&this.mixTexture.animations.length>0&&e.push(this.mixTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._diffuseTextureX&&e.push(this._diffuseTextureX),this._diffuseTextureY&&e.push(this._diffuseTextureY),this._diffuseTextureZ&&e.push(this._diffuseTextureZ),this._normalTextureX&&e.push(this._normalTextureX),this._normalTextureY&&e.push(this._normalTextureY),this._normalTextureZ&&e.push(this._normalTextureZ),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||(this._diffuseTextureX===e||(this._diffuseTextureY===e||(this._diffuseTextureZ===e||(this._normalTextureX===e||(this._normalTextureY===e||this._normalTextureZ===e)))))},n.prototype.dispose=function(e){this.mixTexture&&this.mixTexture.dispose(),t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.TriPlanarMaterial",i},n.prototype.getClassName=function(){return"TriPlanarMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serializeAsTexture()],n.prototype,"mixTexture",void 0),__decorate([e.serializeAsTexture("diffuseTextureX")],n.prototype,"_diffuseTextureX",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTextureX",void 0),__decorate([e.serializeAsTexture("diffuseTexturY")],n.prototype,"_diffuseTextureY",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTextureY",void 0),__decorate([e.serializeAsTexture("diffuseTextureZ")],n.prototype,"_diffuseTextureZ",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTextureZ",void 0),__decorate([e.serializeAsTexture("normalTextureX")],n.prototype,"_normalTextureX",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"normalTextureX",void 0),__decorate([e.serializeAsTexture("normalTextureY")],n.prototype,"_normalTextureY",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"normalTextureY",void 0),__decorate([e.serializeAsTexture("normalTextureZ")],n.prototype,"_normalTextureZ",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"normalTextureZ",void 0),__decorate([e.serialize()],n.prototype,"tileSize",void 0),__decorate([e.serializeAsColor3()],n.prototype,"diffuseColor",void 0),__decorate([e.serializeAsColor3()],n.prototype,"specularColor",void 0),__decorate([e.serialize()],n.prototype,"specularPower",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),n})(e.PushMaterial);e.TriPlanarMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.triplanarVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSEX\nvarying vec2 vTextureUVX;\n#endif\n#ifdef DIFFUSEY\nvarying vec2 vTextureUVY;\n#endif\n#ifdef DIFFUSEZ\nvarying vec2 vTextureUVZ;\n#endif\nuniform float tileSize;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying mat3 tangentSpace;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef DIFFUSEX\nvTextureUVX=worldPos.zy/tileSize;\n#endif\n#ifdef DIFFUSEY\nvTextureUVY=worldPos.xz/tileSize;\n#endif\n#ifdef DIFFUSEZ\nvTextureUVZ=worldPos.xy/tileSize;\n#endif\n#ifdef NORMAL\n\nvec3 xtan=vec3(0,0,1);\nvec3 xbin=vec3(0,1,0);\nvec3 ytan=vec3(1,0,0);\nvec3 ybin=vec3(0,0,1);\nvec3 ztan=vec3(1,0,0);\nvec3 zbin=vec3(0,1,0);\nvec3 normalizedNormal=normalize(normal);\nnormalizedNormal*=normalizedNormal;\nvec3 worldBinormal=normalize(xbin*normalizedNormal.x+ybin*normalizedNormal.y+zbin*normalizedNormal.z);\nvec3 worldTangent=normalize(xtan*normalizedNormal.x+ytan*normalizedNormal.y+ztan*normalizedNormal.z);\nworldTangent=(world*vec4(worldTangent,1.0)).xyz;\nworldBinormal=(world*vec4(worldBinormal,1.0)).xyz;\nvec3 worldNormal=normalize(cross(worldTangent,worldBinormal));\ntangentSpace[0]=worldTangent;\ntangentSpace[1]=worldBinormal;\ntangentSpace[2]=worldNormal;\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n",BABYLON.Effect.ShadersStore.triplanarPixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef DIFFUSEX\nvarying vec2 vTextureUVX;\nuniform sampler2D diffuseSamplerX;\n#ifdef BUMPX\nuniform sampler2D normalSamplerX;\n#endif\n#endif\n#ifdef DIFFUSEY\nvarying vec2 vTextureUVY;\nuniform sampler2D diffuseSamplerY;\n#ifdef BUMPY\nuniform sampler2D normalSamplerY;\n#endif\n#endif\n#ifdef DIFFUSEZ\nvarying vec2 vTextureUVZ;\nuniform sampler2D diffuseSamplerZ;\n#ifdef BUMPZ\nuniform sampler2D normalSamplerZ;\n#endif\n#endif\n#ifdef NORMAL\nvarying mat3 tangentSpace;\n#endif\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(0.,0.,0.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=tangentSpace[2];\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec4 baseNormal=vec4(0.0,0.0,0.0,1.0);\nnormalW*=normalW;\n#ifdef DIFFUSEX\nbaseColor+=texture2D(diffuseSamplerX,vTextureUVX)*normalW.x;\n#ifdef BUMPX\nbaseNormal+=texture2D(normalSamplerX,vTextureUVX)*normalW.x;\n#endif\n#endif\n#ifdef DIFFUSEY\nbaseColor+=texture2D(diffuseSamplerY,vTextureUVY)*normalW.y;\n#ifdef BUMPY\nbaseNormal+=texture2D(normalSamplerY,vTextureUVY)*normalW.y;\n#endif\n#endif\n#ifdef DIFFUSEZ\nbaseColor+=texture2D(diffuseSamplerZ,vTextureUVZ)*normalW.z;\n#ifdef BUMPZ\nbaseNormal+=texture2D(normalSamplerZ,vTextureUVZ)*normalW.z;\n#endif\n#endif\n#ifdef NORMAL\nnormalW=normalize((2.0*baseNormal.xyz-1.0)*tangentSpace);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularBase=vec3(0.,0.,0.);\nvec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n\nvec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}\n";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.CLIPPLANE=!1,i.POINTSIZE=!1,i.FOG=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.luminance=1,r.turbidity=10,r.rayleigh=2,r.mieCoefficient=.005,r.mieDirectionalG=.8,r.distance=500,r.inclination=.49,r.azimuth=.25,r.sunPosition=new e.Vector3(0,100,0),r.useSunPosition=!1,r._cameraPosition=e.Vector3.Zero(),r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;if(e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!1),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var s=new e.EffectFallbacks;o.FOG&&s.addFallback(1,"FOG");var f=[e.VertexBuffer.PositionKind];o.VERTEXCOLOR&&f.push(e.VertexBuffer.ColorKind);var l=o.toString();n.setEffect(a.getEngine().createEffect("sky",f,["world","viewProjection","view","vFogInfos","vFogColor","pointSize","vClipPlane","luminance","turbidity","rayleigh","mieCoefficient","mieDirectionalG","sunPosition","cameraPosition"],[],l,s,this.onCompiled,this.onError),o)}return!!n.effect.isReady()&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene();if(n._materialDefines){var o=n.effect;if(this._activeEffect=o,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),this._mustRebind(r,o)){if(r.clipPlane){var a=r.clipPlane;this._activeEffect.setFloat4("vClipPlane",a.normal.x,a.normal.y,a.normal.z,a.d)}this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize)}r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect);var s=r.activeCamera;if(s){var f=s.getWorldMatrix();this._cameraPosition.x=f.m[12],this._cameraPosition.y=f.m[13],
  98834. this._cameraPosition.z=f.m[14],this._activeEffect.setVector3("cameraPosition",this._cameraPosition)}if(this.luminance>0&&this._activeEffect.setFloat("luminance",this.luminance),this._activeEffect.setFloat("turbidity",this.turbidity),this._activeEffect.setFloat("rayleigh",this.rayleigh),this._activeEffect.setFloat("mieCoefficient",this.mieCoefficient),this._activeEffect.setFloat("mieDirectionalG",this.mieDirectionalG),!this.useSunPosition){var l=Math.PI*(this.inclination-.5),u=2*Math.PI*(this.azimuth-.5);this.sunPosition.x=this.distance*Math.cos(u),this.sunPosition.y=this.distance*Math.sin(u)*Math.sin(l),this.sunPosition.z=this.distance*Math.sin(u)*Math.cos(l)}this._activeEffect.setVector3("sunPosition",this.sunPosition),this._afterBind(t,this._activeEffect)}},n.prototype.getAnimatables=function(){return[]},n.prototype.dispose=function(e){t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.SkyMaterial",i},n.prototype.getClassName=function(){return"SkyMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serialize()],n.prototype,"luminance",void 0),__decorate([e.serialize()],n.prototype,"turbidity",void 0),__decorate([e.serialize()],n.prototype,"rayleigh",void 0),__decorate([e.serialize()],n.prototype,"mieCoefficient",void 0),__decorate([e.serialize()],n.prototype,"mieDirectionalG",void 0),__decorate([e.serialize()],n.prototype,"distance",void 0),__decorate([e.serialize()],n.prototype,"inclination",void 0),__decorate([e.serialize()],n.prototype,"azimuth",void 0),__decorate([e.serializeAsVector3()],n.prototype,"sunPosition",void 0),__decorate([e.serialize()],n.prototype,"useSunPosition",void 0),n})(e.PushMaterial);e.SkyMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.skyVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\nvoid main(void) {\ngl_Position=viewProjection*world*vec4(position,1.0);\nvec4 worldPos=world*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n",BABYLON.Effect.ShadersStore.skyPixelShader="precision highp float;\n\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\nuniform vec3 cameraPosition;\nuniform float luminance;\nuniform float turbidity;\nuniform float rayleigh;\nuniform float mieCoefficient;\nuniform float mieDirectionalG;\nuniform vec3 sunPosition;\n\n#include<fogFragmentDeclaration>\n\nconst float e=2.71828182845904523536028747135266249775724709369995957;\nconst float pi=3.141592653589793238462643383279502884197169;\nconst float n=1.0003;\nconst float N=2.545E25;\nconst float pn=0.035;\nconst vec3 lambda=vec3(680E-9,550E-9,450E-9);\nconst vec3 K=vec3(0.686,0.678,0.666);\nconst float v=4.0;\nconst float rayleighZenithLength=8.4E3;\nconst float mieZenithLength=1.25E3;\nconst vec3 up=vec3(0.0,1.0,0.0);\nconst float EE=1000.0;\nconst float sunAngularDiameterCos=0.999956676946448443553574619906976478926848692873900859324;\nconst float cutoffAngle=pi/1.95;\nconst float steepness=1.5;\nvec3 totalRayleigh(vec3 lambda)\n{\nreturn (8.0*pow(pi,3.0)*pow(pow(n,2.0)-1.0,2.0)*(6.0+3.0*pn))/(3.0*N*pow(lambda,vec3(4.0))*(6.0-7.0*pn));\n}\nvec3 simplifiedRayleigh()\n{\nreturn 0.0005/vec3(94,40,18);\n}\nfloat rayleighPhase(float cosTheta)\n{ \nreturn (3.0/(16.0*pi))*(1.0+pow(cosTheta,2.0));\n}\nvec3 totalMie(vec3 lambda,vec3 K,float T)\n{\nfloat c=(0.2*T )*10E-18;\nreturn 0.434*c*pi*pow((2.0*pi)/lambda,vec3(v-2.0))*K;\n}\nfloat hgPhase(float cosTheta,float g)\n{\nreturn (1.0/(4.0*pi))*((1.0-pow(g,2.0))/pow(1.0-2.0*g*cosTheta+pow(g,2.0),1.5));\n}\nfloat sunIntensity(float zenithAngleCos)\n{\nreturn EE*max(0.0,1.0-exp(-((cutoffAngle-acos(zenithAngleCos))/steepness)));\n}\nfloat A=0.15;\nfloat B=0.50;\nfloat C=0.10;\nfloat D=0.20;\nfloat EEE=0.02;\nfloat F=0.30;\nfloat W=1000.0;\nvec3 Uncharted2Tonemap(vec3 x)\n{\nreturn ((x*(A*x+C*B)+D*EEE)/(x*(A*x+B)+D*F))-EEE/F;\n}\nvoid main(void) {\n\n#include<clipPlaneFragment>\n\nfloat sunfade=1.0-clamp(1.0-exp((sunPosition.y/450000.0)),0.0,1.0);\nfloat rayleighCoefficient=rayleigh-(1.0*(1.0-sunfade));\nvec3 sunDirection=normalize(sunPosition);\nfloat sunE=sunIntensity(dot(sunDirection,up));\nvec3 betaR=simplifiedRayleigh()*rayleighCoefficient;\nvec3 betaM=totalMie(lambda,K,turbidity)*mieCoefficient;\nfloat zenithAngle=acos(max(0.0,dot(up,normalize(vPositionW-cameraPosition))));\nfloat sR=rayleighZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));\nfloat sM=mieZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));\nvec3 Fex=exp(-(betaR*sR+betaM*sM));\nfloat cosTheta=dot(normalize(vPositionW-cameraPosition),sunDirection);\nfloat rPhase=rayleighPhase(cosTheta*0.5+0.5);\nvec3 betaRTheta=betaR*rPhase;\nfloat mPhase=hgPhase(cosTheta,mieDirectionalG);\nvec3 betaMTheta=betaM*mPhase;\nvec3 Lin=pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*(1.0-Fex),vec3(1.5));\nLin*=mix(vec3(1.0),pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*Fex,vec3(1.0/2.0)),clamp(pow(1.0-dot(up,sunDirection),5.0),0.0,1.0));\nvec3 direction=normalize(vPositionW-cameraPosition);\nfloat theta=acos(direction.y);\nfloat phi=atan(direction.z,direction.x);\nvec2 uv=vec2(phi,theta)/vec2(2.0*pi,pi)+vec2(0.5,0.0);\nvec3 L0=vec3(0.1)*Fex;\nfloat sundisk=smoothstep(sunAngularDiameterCos,sunAngularDiameterCos+0.00002,cosTheta);\nL0+=(sunE*19000.0*Fex)*sundisk;\nvec3 whiteScale=1.0/Uncharted2Tonemap(vec3(W));\nvec3 texColor=(Lin+L0); \ntexColor*=0.04 ;\ntexColor+=vec3(0.0,0.001,0.0025)*0.3;\nfloat g_fMaxLuminance=1.0;\nfloat fLumScaled=0.1/luminance; \nfloat fLumCompressed=(fLumScaled*(1.0+(fLumScaled/(g_fMaxLuminance*g_fMaxLuminance))))/(1.0+fLumScaled); \nfloat ExposureBias=fLumCompressed;\nvec3 curr=Uncharted2Tonemap((log2(2.0/pow(luminance,4.0)))*texColor);\n\n\n\nvec3 retColor=curr*whiteScale;\n\n\nfloat alpha=1.0;\n#ifdef VERTEXCOLOR\nretColor.rgb*=vColor.rgb;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec4 color=clamp(vec4(retColor.rgb,alpha),0.0,1.0);\n\n#include<fogFragment>\ngl_FragColor=color;\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.TRANSPARENT=!1,i.FOG=!1,i.PREMULTIPLYALPHA=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.mainColor=e.Color3.Black(),r.lineColor=e.Color3.Teal(),r.gridRatio=1,r.gridOffset=e.Vector3.Zero(),r.majorUnitFrequency=10,r.minorUnitVisibility=.33,r.opacity=1,r.preMultiplyAlpha=!1,r._gridControl=new e.Vector4(r.gridRatio,r.majorUnitFrequency,r.minorUnitVisibility,r.opacity),r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.opacity<1},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;if(o.TRANSPARENT!==this.opacity<1&&(o.TRANSPARENT=!o.TRANSPARENT,o.markAsUnprocessed()),o.PREMULTIPLYALPHA!=this.preMultiplyAlpha&&(o.PREMULTIPLYALPHA=!o.PREMULTIPLYALPHA,o.markAsUnprocessed()),e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,!1,this.fogEnabled,o),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var s=[e.VertexBuffer.PositionKind,e.VertexBuffer.NormalKind],f=o.toString();n.setEffect(a.getEngine().createEffect("grid",s,["projection","worldView","mainColor","lineColor","gridControl","gridOffset","vFogInfos","vFogColor","world","view"],[],f,null,this.onCompiled,this.onError),o)}return!!n.effect.isReady()&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene();if(n._materialDefines){var o=n.effect;this._activeEffect=o,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("worldView",i.multiply(r.getViewMatrix())),this._activeEffect.setMatrix("view",r.getViewMatrix()),this._activeEffect.setMatrix("projection",r.getProjectionMatrix()),this._mustRebind(r,o)&&(this._activeEffect.setColor3("mainColor",this.mainColor),this._activeEffect.setColor3("lineColor",this.lineColor),this._activeEffect.setVector3("gridOffset",this.gridOffset),this._gridControl.x=this.gridRatio,this._gridControl.y=Math.round(this.majorUnitFrequency),this._gridControl.z=this.minorUnitVisibility,this._gridControl.w=this.opacity,this._activeEffect.setVector4("gridControl",this._gridControl)),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._afterBind(t,this._activeEffect)}},n.prototype.dispose=function(e){t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.GridMaterial",i},n.prototype.getClassName=function(){return"GridMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serializeAsColor3()],n.prototype,"mainColor",void 0),__decorate([e.serializeAsColor3()],n.prototype,"lineColor",void 0),__decorate([e.serialize()],n.prototype,"gridRatio",void 0),__decorate([e.serializeAsColor3()],n.prototype,"gridOffset",void 0),__decorate([e.serialize()],n.prototype,"majorUnitFrequency",void 0),__decorate([e.serialize()],n.prototype,"minorUnitVisibility",void 0),__decorate([e.serialize()],n.prototype,"opacity",void 0),__decorate([e.serialize()],n.prototype,"preMultiplyAlpha",void 0),n})(e.PushMaterial);e.GridMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.gridVertexShader="precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 projection;\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 worldView;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogVertexDeclaration>\nvoid main(void) {\n#ifdef FOG\nvec4 worldPos=world*vec4(position,1.0);\n#endif\n#include<fogVertex>\nvec4 cameraSpacePosition=worldView*vec4(position,1.0);\ngl_Position=projection*cameraSpacePosition;\n#ifdef TRANSPARENT\nvCameraSpacePosition=cameraSpacePosition;\n#endif\nvPosition=position;\nvNormal=normal;\n}",BABYLON.Effect.ShadersStore.gridPixelShader="#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;\nuniform vec3 mainColor;\nuniform vec3 lineColor;\nuniform vec4 gridControl;\nuniform vec3 gridOffset;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogFragmentDeclaration>\nfloat getVisibility(float position) {\n\nfloat majorGridFrequency=gridControl.y;\nif (floor(position+0.5) == floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{\nreturn 1.0;\n} \nreturn gridControl.z;\n}\nfloat getAnisotropicAttenuation(float differentialLength) {\nconst float maxNumberOfLines=10.0;\nreturn clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);\n}\nfloat isPointOnLine(float position,float differentialLength) {\nfloat fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);\nfloat result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result; \n}\nfloat contributionOnAxis(float position) {\nfloat differentialLength=length(vec2(dFdx(position),dFdy(position)));\ndifferentialLength*=SQRT2; \n\nfloat result=isPointOnLine(position,differentialLength);\n\nfloat visibility=getVisibility(position);\nresult*=visibility;\n\nfloat anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);\nresult*=anisotropicAttenuation;\nreturn result;\n}\nfloat normalImpactOnAxis(float x) {\nfloat normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);\nreturn normalImpact;\n}\nvoid main(void) {\n\nfloat gridRatio=gridControl.x;\nvec3 gridPos=(vPosition+gridOffset)/gridRatio;\n\nfloat x=contributionOnAxis(gridPos.x);\nfloat y=contributionOnAxis(gridPos.y);\nfloat z=contributionOnAxis(gridPos.z);\n\nvec3 normal=normalize(vNormal);\nx*=normalImpactOnAxis(normal.x);\ny*=normalImpactOnAxis(normal.y);\nz*=normalImpactOnAxis(normal.z);\n\nfloat grid=clamp(x+y+z,0.,1.);\n\nvec3 color=mix(mainColor,lineColor,grid);\n#ifdef FOG\n#include<fogFragment>\n#endif\n#ifdef TRANSPARENT\nfloat distanceToFragment=length(vCameraSpacePosition.xyz);\nfloat cameraPassThrough=clamp(distanceToFragment-0.25,0.0,1.0);\nfloat opacity=clamp(grid,0.08,cameraPassThrough*gridControl.w*grid);\ngl_FragColor=vec4(color.rgb,opacity);\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n\ngl_FragColor=vec4(color.rgb,1.0);\n#endif\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.AMBIENT=!1,i.OPACITY=!1,i.OPACITYRGB=!1,i.REFLECTION=!1,i.EMISSIVE=!1,i.SPECULAR=!1,i.BUMP=!1,i.PARALLAX=!1,i.PARALLAXOCCLUSION=!1,i.SPECULAROVERALPHA=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.ALPHAFROMDIFFUSE=!1,i.POINTSIZE=!1,i.FOG=!1,i.SPECULARTERM=!1,i.DIFFUSEFRESNEL=!1,i.OPACITYFRESNEL=!1,i.REFLECTIONFRESNEL=!1,i.REFRACTIONFRESNEL=!1,i.EMISSIVEFRESNEL=!1,i.FRESNEL=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.GLOSSINESS=!1,i.ROUGHNESS=!1,i.EMISSIVEASILLUMINATION=!1,i.LINKEMISSIVEWITHDIFFUSE=!1,i.REFLECTIONFRESNELFROMSPECULAR=!1,i.LIGHTMAP=!1,i.USELIGHTMAPASSHADOWMAP=!1,i.REFLECTIONMAP_3D=!1,i.REFLECTIONMAP_SPHERICAL=!1,i.REFLECTIONMAP_PLANAR=!1,i.REFLECTIONMAP_CUBIC=!1,i.REFLECTIONMAP_PROJECTION=!1,i.REFLECTIONMAP_SKYBOX=!1,i.REFLECTIONMAP_EXPLICIT=!1,i.REFLECTIONMAP_EQUIRECTANGULAR=!1,i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,i.INVERTCUBICMAP=!1,i.LOGARITHMICDEPTH=!1,i.REFRACTION=!1,i.REFRACTIONMAP_3D=!1,i.REFLECTIONOVERALPHA=!1,i.TWOSIDEDLIGHTING=!1,i.SHADOWFLOAT=!1,i.MORPHTARGETS=!1,i.MORPHTARGETS_NORMAL=!1,i.MORPHTARGETS_TANGENT=!1,i.NUM_MORPH_INFLUENCERS=0,i.IMAGEPROCESSING=!1,i.VIGNETTE=!1,i.VIGNETTEBLENDMODEMULTIPLY=!1,i.VIGNETTEBLENDMODEOPAQUE=!1,i.TONEMAPPING=!1,i.CONTRAST=!1,i.COLORCURVES=!1,i.COLORGRADING=!1,i.SAMPLER3DGREENDEPTH=!1,i.SAMPLER3DBGRMAP=!1,i.IMAGEPROCESSINGPOSTPROCESS=!1,i.EXPOSURE=!1,i.rebuild(),i}return __extends(i,e),i.prototype.setReflectionMode=function(e){for(var i=["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"],t=0,n=i;t<n.length;t++){var r=n[t];this[r]=r===e}},i})(e.MaterialDefines);e.StandardMaterialDefines_OldVer=i;var t=(function(t){function n(i,r){var o=t.call(this,i,r)||this;return o.ambientColor=new e.Color3(0,0,0),o.diffuseColor=new e.Color3(1,1,1),o.specularColor=new e.Color3(1,1,1),o.emissiveColor=new e.Color3(0,0,0),o.specularPower=64,o._useAlphaFromDiffuseTexture=!1,o._useEmissiveAsIllumination=!1,o._linkEmissiveWithDiffuse=!1,o._useSpecularOverAlpha=!1,o._useReflectionOverAlpha=!1,o._disableLighting=!1,o._useParallax=!1,o._useParallaxOcclusion=!1,o.parallaxScaleBias=.05,o._roughness=0,o.indexOfRefraction=.98,o.invertRefractionY=!0,o._useLightmapAsShadowmap=!1,o._useReflectionFresnelFromSpecular=!1,o._useGlossinessFromSpecularMapAlpha=!1,o._maxSimultaneousLights=4,o._invertNormalMapX=!1,o._invertNormalMapY=!1,o._twoSidedLighting=!1,o._renderTargets=new e.SmartArray(16),o._worldViewProjectionMatrix=e.Matrix.Zero(),o._globalAmbientColor=new e.Color3(0,0,0),o._attachImageProcessingConfiguration(null),o.getRenderTargetTextures=function(){return o._renderTargets.reset(),n.ReflectionTextureEnabled&&o._reflectionTexture&&o._reflectionTexture.isRenderTarget&&o._renderTargets.push(o._reflectionTexture),n.RefractionTextureEnabled&&o._refractionTexture&&o._refractionTexture.isRenderTarget&&o._renderTargets.push(o._refractionTexture),o._renderTargets},o}return __extends(n,t),Object.defineProperty(n.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!0,configurable:!0}),n.prototype._attachImageProcessingConfiguration=function(e){var i=this;e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((function(e){i._markAllSubMeshesAsImageProcessingDirty()})))},Object.defineProperty(n.prototype,"cameraColorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"cameraColorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"cameraToneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"cameraExposure",{get:function(){return this._imageProcessingConfiguration.exposure},set:function(e){this._imageProcessingConfiguration.exposure=e},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"cameraContrast",{get:function(){return this._imageProcessingConfiguration.contrast},set:function(e){this._imageProcessingConfiguration.contrast=e},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"cameraColorGradingTexture",{get:function(){return this._imageProcessingConfiguration.colorGradingTexture},set:function(e){this._imageProcessingConfiguration.colorGradingTexture=e},enumerable:!0,configurable:!0}),n.prototype.getClassName=function(){return"StandardMaterial_OldVer"},Object.defineProperty(n.prototype,"useLogarithmicDepth",{get:function(){return this._useLogarithmicDepth},set:function(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported,this._markAllSubMeshesAsMiscDirty()},enumerable:!0,configurable:!0}),n.prototype.needAlphaBlending=function(){return this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled},n.prototype.needAlphaTesting=function(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha},n.prototype._shouldUseAlphaFromDiffuseTexture=function(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture},n.prototype.getAlphaTestTexture=function(){return this._diffuseTexture},n.prototype.isReadyForSubMesh=function(t,r,o){if(this.isFrozen&&this._wasPreviouslyReady&&r.effect)return!0;r._materialDefines||(r._materialDefines=new i);var a=this.getScene(),s=r._materialDefines;if(!this.checkReadyOnEveryCall&&r.effect&&s._renderId===a.getRenderId())return!0;var f=a.getEngine();if(s._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,s,!0,this._maxSimultaneousLights,this._disableLighting),s._areTexturesDirty){if(s._needUVs=!1,a.texturesEnabled){if(this._diffuseTexture&&n.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.DIFFUSE=!0}else s.DIFFUSE=!1;if(this._ambientTexture&&n.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.AMBIENT=!0}else s.AMBIENT=!1;if(this._opacityTexture&&n.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.OPACITY=!0,s.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else s.OPACITY=!1;if(this._reflectionTexture&&n.ReflectionTextureEnabled){if(!this._reflectionTexture.isReadyOrNotBlocking())return!1;switch(s._needNormals=!0,s.REFLECTION=!0,s.ROUGHNESS=this._roughness>0,s.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,s.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===e.Texture.INVCUBIC_MODE,s.REFLECTIONMAP_3D=this._reflectionTexture.isCube,this._reflectionTexture.coordinatesMode){case e.Texture.CUBIC_MODE:case e.Texture.INVCUBIC_MODE:s.setReflectionMode("REFLECTIONMAP_CUBIC");break;case e.Texture.EXPLICIT_MODE:s.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case e.Texture.PLANAR_MODE:s.setReflectionMode("REFLECTIONMAP_PLANAR");break;case e.Texture.PROJECTION_MODE:s.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case e.Texture.SKYBOX_MODE:s.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case e.Texture.SPHERICAL_MODE:s.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case e.Texture.EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case e.Texture.FIXED_EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case e.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED")}}else s.REFLECTION=!1;if(this._emissiveTexture&&n.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.EMISSIVE=!0}else s.EMISSIVE=!1;if(this._lightmapTexture&&n.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.LIGHTMAP=!0,s.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap}else s.LIGHTMAP=!1;if(this._specularTexture&&n.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.SPECULAR=!0,s.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else s.SPECULAR=!1;if(a.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&n.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;s._needUVs=!0,s.BUMP=!0,s.PARALLAX=this._useParallax,s.PARALLAXOCCLUSION=this._useParallaxOcclusion}else s.BUMP=!1;if(this._refractionTexture&&n.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.REFRACTION=!0,s.REFRACTIONMAP_3D=this._refractionTexture.isCube}else s.REFRACTION=!1;s.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else s.DIFFUSE=!1,s.AMBIENT=!1,s.OPACITY=!1,s.REFLECTION=!1,s.EMISSIVE=!1,s.LIGHTMAP=!1,s.BUMP=!1,s.REFRACTION=!1;s.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),s.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,s.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,s.SPECULAROVERALPHA=this._useSpecularOverAlpha}if(s._areImageProcessingDirty){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(s)}if(s._areFresnelDirty&&(n.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(s.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,s.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,s.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,s.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,s.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,s.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,s._needNormals=!0,s.FRESNEL=!0):s.FRESNEL=!1),e.MaterialHelper.PrepareDefinesForMisc(t,a,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,s),e.MaterialHelper.PrepareDefinesForAttributes(t,s,!0,!0,!0),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,f,s,o),s.isDirty){s.markAsProcessed(),a.resetCachedMaterial();var l=new e.EffectFallbacks;s.REFLECTION&&l.addFallback(0,"REFLECTION"),s.SPECULAR&&l.addFallback(0,"SPECULAR"),s.BUMP&&l.addFallback(0,"BUMP"),s.PARALLAX&&l.addFallback(1,"PARALLAX"),s.PARALLAXOCCLUSION&&l.addFallback(0,"PARALLAXOCCLUSION"),s.SPECULAROVERALPHA&&l.addFallback(0,"SPECULAROVERALPHA"),s.FOG&&l.addFallback(1,"FOG"),s.POINTSIZE&&l.addFallback(0,"POINTSIZE"),s.LOGARITHMICDEPTH&&l.addFallback(0,"LOGARITHMICDEPTH"),e.MaterialHelper.HandleFallbacksForShadows(s,l,this._maxSimultaneousLights),s.SPECULARTERM&&l.addFallback(0,"SPECULARTERM"),s.DIFFUSEFRESNEL&&l.addFallback(1,"DIFFUSEFRESNEL"),s.OPACITYFRESNEL&&l.addFallback(2,"OPACITYFRESNEL"),s.REFLECTIONFRESNEL&&l.addFallback(3,"REFLECTIONFRESNEL"),s.EMISSIVEFRESNEL&&l.addFallback(4,"EMISSIVEFRESNEL"),s.FRESNEL&&l.addFallback(4,"FRESNEL");var u=[e.VertexBuffer.PositionKind];s.NORMAL&&u.push(e.VertexBuffer.NormalKind),s.UV1&&u.push(e.VertexBuffer.UVKind),s.UV2&&u.push(e.VertexBuffer.UV2Kind),s.VERTEXCOLOR&&u.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(u,t,s,l),e.MaterialHelper.PrepareAttributesForInstances(u,s),e.MaterialHelper.PrepareAttributesForMorphTargets(u,t,s);var c="default",d=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","vClipPlane","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","logarithmicDepthConstant","vTangentSpaceParams"],m=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler"],v=["Material","Scene"];e.ImageProcessingConfiguration.PrepareUniforms(d,s),e.ImageProcessingConfiguration.PrepareSamplers(m,s),e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:d,uniformBuffersNames:v,samplers:m,defines:s,maxSimultaneousLights:this._maxSimultaneousLights}),this.customShaderNameResolve&&(c=this.customShaderNameResolve(c,d,v,m,s));var h=s.toString();r.setEffect(a.getEngine().createEffect(c,{attributes:u,uniformsNames:d,uniformBuffersNames:v,samplers:m,defines:h,fallbacks:l,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:s.NUM_MORPH_INFLUENCERS}},f),s),this.buildUniformLayout()}return!!r.effect.isReady()&&(s._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.buildUniformLayout=function(){this._uniformBuffer.addUniform("diffuseLeftColor",4),this._uniformBuffer.addUniform("diffuseRightColor",4),this._uniformBuffer.addUniform("opacityParts",4),this._uniformBuffer.addUniform("reflectionLeftColor",4),this._uniformBuffer.addUniform("reflectionRightColor",4),this._uniformBuffer.addUniform("refractionLeftColor",4),this._uniformBuffer.addUniform("refractionRightColor",4),this._uniformBuffer.addUniform("emissiveLeftColor",4),this._uniformBuffer.addUniform("emissiveRightColor",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vAmbientInfos",2),this._uniformBuffer.addUniform("vOpacityInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("vEmissiveInfos",2),this._uniformBuffer.addUniform("vLightmapInfos",2),this._uniformBuffer.addUniform("vSpecularInfos",2),this._uniformBuffer.addUniform("vBumpInfos",3),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("ambientMatrix",16),this._uniformBuffer.addUniform("opacityMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("emissiveMatrix",16),this._uniformBuffer.addUniform("lightmapMatrix",16),this._uniformBuffer.addUniform("specularMatrix",16),this._uniformBuffer.addUniform("bumpMatrix",16),this._uniformBuffer.addUniform("vTangentSpaceParams",2),this._uniformBuffer.addUniform("refractionMatrix",16),this._uniformBuffer.addUniform("vRefractionInfos",4),this._uniformBuffer.addUniform("vSpecularColor",4),this._uniformBuffer.addUniform("vEmissiveColor",3),this._uniformBuffer.addUniform("vDiffuseColor",4),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.create()},n.prototype.unbind=function(){this._activeEffect&&(this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._activeEffect.setTexture("reflection2DSampler",null),this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._activeEffect.setTexture("refraction2DSampler",null)),t.prototype.unbind.call(this)},n.prototype.bindForSubMesh=function(i,t,r){var o=this.getScene(),a=r._materialDefines;if(a){var s=r.effect;if(this._activeEffect=s,this.bindOnlyWorldMatrix(i),e.MaterialHelper.BindBonesParameters(t,s),this._mustRebind(o,s,t.visibility)){if(this._uniformBuffer.bindToEffect(s,"Material"),this.bindViewProjection(s),!this._uniformBuffer.useUbo||!this.isFrozen||!this._uniformBuffer.isSync){if(n.FresnelEnabled&&a.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),this._uniformBuffer.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&this._uniformBuffer.updateColor4("opacityParts",new e.Color3(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),this._uniformBuffer.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),this._uniformBuffer.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),this._uniformBuffer.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),
  98835. o.texturesEnabled&&(this._diffuseTexture&&n.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._uniformBuffer.updateMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),this._ambientTexture&&n.AmbientTextureEnabled&&(this._uniformBuffer.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),this._uniformBuffer.updateMatrix("ambientMatrix",this._ambientTexture.getTextureMatrix())),this._opacityTexture&&n.OpacityTextureEnabled&&(this._uniformBuffer.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),this._uniformBuffer.updateMatrix("opacityMatrix",this._opacityTexture.getTextureMatrix())),this._reflectionTexture&&n.ReflectionTextureEnabled&&(this._uniformBuffer.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),this._uniformBuffer.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix())),this._emissiveTexture&&n.EmissiveTextureEnabled&&(this._uniformBuffer.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),this._uniformBuffer.updateMatrix("emissiveMatrix",this._emissiveTexture.getTextureMatrix())),this._lightmapTexture&&n.LightmapTextureEnabled&&(this._uniformBuffer.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),this._uniformBuffer.updateMatrix("lightmapMatrix",this._lightmapTexture.getTextureMatrix())),this._specularTexture&&n.SpecularTextureEnabled&&(this._uniformBuffer.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),this._uniformBuffer.updateMatrix("specularMatrix",this._specularTexture.getTextureMatrix())),this._bumpTexture&&o.getEngine().getCaps().standardDerivatives&&n.BumpTextureEnabled&&(this._uniformBuffer.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),this._uniformBuffer.updateMatrix("bumpMatrix",this._bumpTexture.getTextureMatrix()),o._mirroredCameraPosition?this._uniformBuffer.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):this._uniformBuffer.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&n.RefractionTextureEnabled)){var f=1;this._refractionTexture.isCube||(this._uniformBuffer.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(f=this._refractionTexture.depth)),this._uniformBuffer.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,f,this.invertRefractionY?-1:1)}this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),a.SPECULARTERM&&this._uniformBuffer.updateColor4("vSpecularColor",this.specularColor,this.specularPower),this._uniformBuffer.updateColor3("vEmissiveColor",this.emissiveColor),this._uniformBuffer.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility)}if(o.texturesEnabled&&(this._diffuseTexture&&n.DiffuseTextureEnabled&&s.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&n.AmbientTextureEnabled&&s.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&n.OpacityTextureEnabled&&s.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&n.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?s.setTexture("reflectionCubeSampler",this._reflectionTexture):s.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&n.EmissiveTextureEnabled&&s.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&n.LightmapTextureEnabled&&s.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&n.SpecularTextureEnabled&&s.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&o.getEngine().getCaps().standardDerivatives&&n.BumpTextureEnabled&&s.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&n.RefractionTextureEnabled)){var f=1;this._refractionTexture.isCube?s.setTexture("refractionCubeSampler",this._refractionTexture):s.setTexture("refraction2DSampler",this._refractionTexture)}e.MaterialHelper.BindClipPlane(s,o),o.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),s.setVector3("vEyePosition",o._mirroredCameraPosition?o._mirroredCameraPosition:o.activeCamera.position),s.setColor3("vAmbientColor",this._globalAmbientColor)}!this._mustRebind(o,s)&&this.isFrozen||(o.lightsEnabled&&!this._disableLighting&&e.MaterialHelper.BindLights(o,t,s,a,this._maxSimultaneousLights),(o.fogEnabled&&t.applyFog&&o.fogMode!==e.Scene.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture)&&this.bindView(s),e.MaterialHelper.BindFogParameters(o,t,s),a.NUM_MORPH_INFLUENCERS&&e.MaterialHelper.BindMorphTargetParameters(t,s),e.MaterialHelper.BindLogDepth(a,s,o),this._imageProcessingConfiguration.bind(this._activeEffect)),this._uniformBuffer.update(),this._afterBind(t,this._activeEffect)}},n.prototype.getAnimatables=function(){var e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e},n.prototype.dispose=function(e,i){i&&(this._diffuseTexture&&this._diffuseTexture.dispose(),this._ambientTexture&&this._ambientTexture.dispose(),this._opacityTexture&&this._opacityTexture.dispose(),this._reflectionTexture&&this._reflectionTexture.dispose(),this._emissiveTexture&&this._emissiveTexture.dispose(),this._specularTexture&&this._specularTexture.dispose(),this._bumpTexture&&this._bumpTexture.dispose(),this._lightmapTexture&&this._lightmapTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),t.prototype.dispose.call(this,e,i)},n.prototype.clone=function(i){var t=this,r=e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this);return r.name=i,r.id=i,r},n.prototype.serialize=function(){return e.SerializationHelper.Serialize(this)},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},Object.defineProperty(n,"DiffuseTextureEnabled",{get:function(){return n._DiffuseTextureEnabled},set:function(i){n._DiffuseTextureEnabled!==i&&(n._DiffuseTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"AmbientTextureEnabled",{get:function(){return n._AmbientTextureEnabled},set:function(i){n._AmbientTextureEnabled!==i&&(n._AmbientTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"OpacityTextureEnabled",{get:function(){return n._OpacityTextureEnabled},set:function(i){n._OpacityTextureEnabled!==i&&(n._OpacityTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"ReflectionTextureEnabled",{get:function(){return n._ReflectionTextureEnabled},set:function(i){n._ReflectionTextureEnabled!==i&&(n._ReflectionTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"EmissiveTextureEnabled",{get:function(){return n._EmissiveTextureEnabled},set:function(i){n._EmissiveTextureEnabled!==i&&(n._EmissiveTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"SpecularTextureEnabled",{get:function(){return n._SpecularTextureEnabled},set:function(i){n._SpecularTextureEnabled!==i&&(n._SpecularTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"BumpTextureEnabled",{get:function(){return n._BumpTextureEnabled},set:function(i){n._BumpTextureEnabled!==i&&(n._BumpTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"LightmapTextureEnabled",{get:function(){return n._LightmapTextureEnabled},set:function(i){n._LightmapTextureEnabled!==i&&(n._LightmapTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"RefractionTextureEnabled",{get:function(){return n._RefractionTextureEnabled},set:function(i){n._RefractionTextureEnabled!==i&&(n._RefractionTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"ColorGradingTextureEnabled",{get:function(){return n._ColorGradingTextureEnabled},set:function(i){n._ColorGradingTextureEnabled!==i&&(n._ColorGradingTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"FresnelEnabled",{get:function(){return n._FresnelEnabled},set:function(i){n._FresnelEnabled!==i&&(n._FresnelEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.FresnelDirtyFlag))},enumerable:!0,configurable:!0}),n._DiffuseTextureEnabled=!0,n._AmbientTextureEnabled=!0,n._OpacityTextureEnabled=!0,n._ReflectionTextureEnabled=!0,n._EmissiveTextureEnabled=!0,n._SpecularTextureEnabled=!0,n._BumpTextureEnabled=!0,n._LightmapTextureEnabled=!0,n._RefractionTextureEnabled=!0,n._ColorGradingTextureEnabled=!0,n._FresnelEnabled=!0,__decorate([e.serializeAsTexture("diffuseTexture")],n.prototype,"_diffuseTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture",void 0),__decorate([e.serializeAsTexture("ambientTexture")],n.prototype,"_ambientTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"ambientTexture",void 0),__decorate([e.serializeAsTexture("opacityTexture")],n.prototype,"_opacityTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"opacityTexture",void 0),__decorate([e.serializeAsTexture("reflectionTexture")],n.prototype,"_reflectionTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"reflectionTexture",void 0),__decorate([e.serializeAsTexture("emissiveTexture")],n.prototype,"_emissiveTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"emissiveTexture",void 0),__decorate([e.serializeAsTexture("specularTexture")],n.prototype,"_specularTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"specularTexture",void 0),__decorate([e.serializeAsTexture("bumpTexture")],n.prototype,"_bumpTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"bumpTexture",void 0),__decorate([e.serializeAsTexture("lightmapTexture")],n.prototype,"_lightmapTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"lightmapTexture",void 0),__decorate([e.serializeAsTexture("refractionTexture")],n.prototype,"_refractionTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"refractionTexture",void 0),__decorate([e.serializeAsColor3("ambient")],n.prototype,"ambientColor",void 0),__decorate([e.serializeAsColor3("diffuse")],n.prototype,"diffuseColor",void 0),__decorate([e.serializeAsColor3("specular")],n.prototype,"specularColor",void 0),__decorate([e.serializeAsColor3("emissive")],n.prototype,"emissiveColor",void 0),__decorate([e.serialize()],n.prototype,"specularPower",void 0),__decorate([e.serialize("useAlphaFromDiffuseTexture")],n.prototype,"_useAlphaFromDiffuseTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"useAlphaFromDiffuseTexture",void 0),__decorate([e.serialize("useEmissiveAsIllumination")],n.prototype,"_useEmissiveAsIllumination",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"useEmissiveAsIllumination",void 0),__decorate([e.serialize("linkEmissiveWithDiffuse")],n.prototype,"_linkEmissiveWithDiffuse",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"linkEmissiveWithDiffuse",void 0),__decorate([e.serialize("useSpecularOverAlpha")],n.prototype,"_useSpecularOverAlpha",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"useSpecularOverAlpha",void 0),__decorate([e.serialize("useReflectionOverAlpha")],n.prototype,"_useReflectionOverAlpha",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"useReflectionOverAlpha",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("useParallax")],n.prototype,"_useParallax",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"useParallax",void 0),__decorate([e.serialize("useParallaxOcclusion")],n.prototype,"_useParallaxOcclusion",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"useParallaxOcclusion",void 0),__decorate([e.serialize()],n.prototype,"parallaxScaleBias",void 0),__decorate([e.serialize("roughness")],n.prototype,"_roughness",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"roughness",void 0),__decorate([e.serialize()],n.prototype,"indexOfRefraction",void 0),__decorate([e.serialize()],n.prototype,"invertRefractionY",void 0),__decorate([e.serialize("useLightmapAsShadowmap")],n.prototype,"_useLightmapAsShadowmap",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"useLightmapAsShadowmap",void 0),__decorate([e.serializeAsFresnelParameters("diffuseFresnelParameters")],n.prototype,"_diffuseFresnelParameters",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],n.prototype,"diffuseFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters("opacityFresnelParameters")],n.prototype,"_opacityFresnelParameters",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],n.prototype,"opacityFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters("reflectionFresnelParameters")],n.prototype,"_reflectionFresnelParameters",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],n.prototype,"reflectionFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters("refractionFresnelParameters")],n.prototype,"_refractionFresnelParameters",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],n.prototype,"refractionFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters("emissiveFresnelParameters")],n.prototype,"_emissiveFresnelParameters",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],n.prototype,"emissiveFresnelParameters",void 0),__decorate([e.serialize("useReflectionFresnelFromSpecular")],n.prototype,"_useReflectionFresnelFromSpecular",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],n.prototype,"useReflectionFresnelFromSpecular",void 0),__decorate([e.serialize("useGlossinessFromSpecularMapAlpha")],n.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"useGlossinessFromSpecularMapAlpha",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),__decorate([e.serialize("invertNormalMapX")],n.prototype,"_invertNormalMapX",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"invertNormalMapX",void 0),__decorate([e.serialize("invertNormalMapY")],n.prototype,"_invertNormalMapY",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"invertNormalMapY",void 0),__decorate([e.serialize("twoSidedLighting")],n.prototype,"_twoSidedLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"twoSidedLighting",void 0),__decorate([e.serialize()],n.prototype,"useLogarithmicDepth",null),n})(e.PushMaterial);e.StandardMaterial_OldVer=t;var n=(function(){function e(){}return e})();e.CustomShaderStructure=n;var r=(function(){function e(){}return e})();e.ShaderSpecialParts=r;var o=(function(e){function i(){var i=e.call(this)||this;return i.VertexStore="",i.FragmentStore="#include<__decl__defaultFragment>\n#[Fragment_Begin]\n#extension GL_OES_standard_derivatives : enable\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW_helper;\nvarying vec3 localNormal;\nvarying vec3 localPosition;\nvec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n\n#[Fragment_Definitions]\n\nvoid main(void) {\n\nvNormalW = vNormalW_helper;\n#[Fragment_MainBegin]\n\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#[Fragment_Custom_Diffuse]\n\nfloat alpha=vDiffuseColor.a;\n#[Fragment_Custom_Alpha]\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n// Apply image processing if relevant. As this applies in linear space, \n// We first move from gamma to linear.\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\tcolor.rgb = toLinearSpace(color.rgb);\n#else\n\t#ifdef IMAGEPROCESSING\n\t\tcolor.rgb = toLinearSpace(color.rgb);\n\t\tcolor = applyImageProcessing(color);\n\t#endif\n#endif\n\n#[Fragment_Before_FragColor]\ngl_FragColor=color;\n}",i.VertexStore="#include<__decl__defaultVertex>\n\n#[Vertex_Begin]\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 localPosition;\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW_helper;\nvarying vec3 localNormal;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n\n#[Vertex_Definitions]\n\nvoid main(void) {\n \n #[Vertex_MainBegin]\n \nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\n\nlocalPosition = positionUpdated;\n#[Vertex_Before_PositionUpdated]\n\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\n\n#[Vertex_Before_NormalUpdated]\n\nlocalNormal = normalUpdated;\nvNormalW_helper=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}",i}return __extends(i,e),i})(n);e.ShaderForVer3_0=o;var a=(function(){function e(){}return e.Ver3_0="3.0.0",e})();e.StandardShaderVersions=a;var s=(function(i){function t(e,t){var n=i.call(this,e,t)||this;return n.CustomParts=new r,n.customShaderNameResolve=n.Builder,n.SelectVersion("3.0.0"),n}return __extends(t,i),t.prototype.AttachAfterBind=function(e,i){for(var t in this._newUniformInstances){var n=t.toString().split("-");"vec2"==n[0]?i.setVector2(n[1],this._newUniformInstances[t]):"vec3"==n[0]?i.setVector3(n[1],this._newUniformInstances[t]):"vec4"==n[0]?i.setVector4(n[1],this._newUniformInstances[t]):"mat4"==n[0]?i.setMatrix(n[1],this._newUniformInstances[t]):"float"==n[0]&&i.setFloat(n[1],this._newUniformInstances[t])}for(var t in this._newSamplerInstances){var n=t.toString().split("-")
  98836. ;"sampler2D"==n[0]&&this._newSamplerInstances[t].isReady&&this._newSamplerInstances[t].isReady()&&i.setTexture(n[1],this._newSamplerInstances[t])}},t.prototype.ReviewUniform=function(e,i){if("uniform"==e)for(var t in this._newUniforms)-1==this._customUniform[t].indexOf("sampler")&&i.push(this._newUniforms[t]);if("sampler"==e)for(var t in this._newUniforms)-1!=this._customUniform[t].indexOf("sampler")&&i.push(this._newUniforms[t]);return i},t.prototype.Builder=function(i,n,r,o,a){var s=this;if(this._isCreatedShader)return this._createdShaderName;this._isCreatedShader=!1,t.ShaderIndexer++;var f=f+"custom_"+t.ShaderIndexer;this.ReviewUniform("uniform",n),this.ReviewUniform("sampler",o);var l=this._afterBind;return this._afterBind=function(e,i){s.AttachAfterBind(e,i);try{l(e,i)}catch(i){}},e.Effect.ShadersStore[f+"VertexShader"]=this.ShaderVersion.VertexStore.replace("#[Vertex_Begin]",this.CustomParts.Vertex_Begin?this.CustomParts.Vertex_Begin:"").replace("#[Vertex_Definitions]",(this._customUniform?this._customUniform.join("\n"):"")+(this.CustomParts.Vertex_Definitions?this.CustomParts.Vertex_Definitions:"")).replace("#[Vertex_MainBegin]",this.CustomParts.Vertex_MainBegin?this.CustomParts.Vertex_MainBegin:"").replace("#[Vertex_Before_PositionUpdated]",this.CustomParts.Vertex_Before_PositionUpdated?this.CustomParts.Vertex_Before_PositionUpdated:"").replace("#[Vertex_Before_NormalUpdated]",this.CustomParts.Vertex_Before_NormalUpdated?this.CustomParts.Vertex_Before_NormalUpdated:""),e.Effect.ShadersStore[f+"PixelShader"]=this.ShaderVersion.FragmentStore.replace("#[Fragment_Begin]",this.CustomParts.Fragment_Begin?this.CustomParts.Fragment_Begin:"").replace("#[Fragment_MainBegin]",this.CustomParts.Fragment_MainBegin?this.CustomParts.Fragment_MainBegin:"").replace("#[Fragment_Definitions]",(this._customUniform?this._customUniform.join("\n"):"")+(this.CustomParts.Fragment_Definitions?this.CustomParts.Fragment_Definitions:"")).replace("#[Fragment_Custom_Diffuse]",this.CustomParts.Fragment_Custom_Diffuse?this.CustomParts.Fragment_Custom_Diffuse:"").replace("#[Fragment_Custom_Alpha]",this.CustomParts.Fragment_Custom_Alpha?this.CustomParts.Fragment_Custom_Alpha:"").replace("#[Fragment_Before_FragColor]",this.CustomParts.Fragment_Before_FragColor?this.CustomParts.Fragment_Before_FragColor:""),this._isCreatedShader=!0,this._createdShaderName=f,f},t.prototype.SelectVersion=function(e){switch(e){case"3.0.0":this.ShaderVersion=new o}},t.prototype.AddUniform=function(e,i,t){return this._customUniform||(this._customUniform=new Array,this._newUniforms=new Array,this._newSamplerInstances=new Array,this._newUniformInstances=new Array),t&&(i.indexOf("sampler"),this._newUniformInstances[i+"-"+e]=t),this._customUniform.push("uniform "+i+" "+e+";"),this._newUniforms.push(e),this},t.prototype.Fragment_Begin=function(e){return this.CustomParts.Fragment_Begin=e,this},t.prototype.Fragment_Definitions=function(e){return this.CustomParts.Fragment_Definitions=e,this},t.prototype.Fragment_MainBegin=function(e){return this.CustomParts.Fragment_MainBegin=e,this},t.prototype.Fragment_Custom_Diffuse=function(e){return this.CustomParts.Fragment_Custom_Diffuse=e.replace("result","diffuseColor"),this},t.prototype.Fragment_Custom_Alpha=function(e){return this.CustomParts.Fragment_Custom_Alpha=e.replace("result","alpha"),this},t.prototype.Fragment_Before_FragColor=function(e){return this.CustomParts.Fragment_Before_FragColor=e.replace("result","color"),this},t.prototype.Vertex_Begin=function(e){return this.CustomParts.Vertex_Begin=e,this},t.prototype.Vertex_Definitions=function(e){return this.CustomParts.Vertex_Definitions=e,this},t.prototype.Vertex_MainBegin=function(e){return this.CustomParts.Vertex_MainBegin=e,this},t.prototype.Vertex_Before_PositionUpdated=function(e){return this.CustomParts.Vertex_Before_PositionUpdated=e.replace("result","positionUpdated"),this},t.prototype.Vertex_Before_NormalUpdated=function(e){return this.CustomParts.Vertex_Before_NormalUpdated=e.replace("result","normalUpdated"),this},t.ShaderIndexer=1,t})(t);e.CustomMaterial=s})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.POINTSIZE=!1,i.FOG=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.NDOTL=!0,i.CUSTOMUSERLIGHTING=!0,i.CELLBASIC=!0,i.DEPTHPREPASS=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.diffuseColor=new e.Color3(1,1,1),r._computeHighLevel=!1,r._disableLighting=!1,r._maxSimultaneousLights=4,r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(o._areTexturesDirty&&(o._needUVs=!1,a.texturesEnabled&&this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;o._needUVs=!0,o.DIFFUSE=!0}if(o.CELLBASIC=!this.computeHighLevel,e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,this._maxSimultaneousLights,this._disableLighting),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,r),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,f,this.maxSimultaneousLights),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.NORMAL&&l.push(e.VertexBuffer.NormalKind),o.UV1&&l.push(e.VertexBuffer.UVKind),o.UV2&&l.push(e.VertexBuffer.UV2Kind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","diffuseMatrix"],d=["diffuseSampler"],m=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:m,samplers:d,defines:o,maxSimultaneousLights:this.maxSimultaneousLights}),n.setEffect(a.getEngine().createEffect("cell",{attributes:l,uniformsNames:c,uniformBuffersNames:m,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights-1}},s),o)}return!!n.effect.isReady()&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(r,a)&&(this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._activeEffect.setVector3("vEyePosition",r._mirroredCameraPosition?r._mirroredCameraPosition:r.activeCamera.position)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o,this._maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._afterBind(t,this._activeEffect)}},n.prototype.getAnimatables=function(){var e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||this._diffuseTexture===e},n.prototype.dispose=function(e){this._diffuseTexture&&this._diffuseTexture.dispose(),t.prototype.dispose.call(this,e)},n.prototype.getClassName=function(){return"CellMaterial"},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.CellMaterial",i},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serializeAsTexture("diffuseTexture")],n.prototype,"_diffuseTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture",void 0),__decorate([e.serializeAsColor3("diffuseColor")],n.prototype,"diffuseColor",void 0),__decorate([e.serialize("computeHighLevel")],n.prototype,"_computeHighLevel",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"computeHighLevel",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),n})(e.PushMaterial);e.CellMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.cellVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n",BABYLON.Effect.ShadersStore.cellPixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n\nvec3 computeCustomDiffuseLighting(lightingInfo info,vec3 diffuseBase,float shadow)\n{\ndiffuseBase=info.diffuse*shadow;\n#ifdef CELLBASIC\nfloat level=1.0;\nif (info.ndl<0.5)\nlevel=0.5;\ndiffuseBase.rgb*vec3(level,level,level);\n#else\nfloat ToonThresholds[4];\nToonThresholds[0]=0.95;\nToonThresholds[1]=0.5;\nToonThresholds[2]=0.2;\nToonThresholds[3]=0.03;\nfloat ToonBrightnessLevels[5];\nToonBrightnessLevels[0]=1.0;\nToonBrightnessLevels[1]=0.8;\nToonBrightnessLevels[2]=0.6;\nToonBrightnessLevels[3]=0.35;\nToonBrightnessLevels[4]=0.2;\nif (info.ndl>ToonThresholds[0])\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[0];\n}\nelse if (info.ndl>ToonThresholds[1])\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[1];\n}\nelse if (info.ndl>ToonThresholds[2])\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[2];\n}\nelse if (info.ndl>ToonThresholds[3])\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[3];\n}\nelse\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[4];\n}\n#endif\nreturn max(diffuseBase,vec3(0.2));\n}\nvoid main(void)\n{\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nlightingInfo info;\nvec3 diffuseBase=vec3(0.,0.,0.);\nfloat shadow=1.;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif \n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;;\n\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.ALBEDO=!1,i.AMBIENT=!1,i.AMBIENTINGRAYSCALE=!1,i.OPACITY=!1,i.OPACITYRGB=!1,i.REFLECTION=!1,i.EMISSIVE=!1,i.REFLECTIVITY=!1,i.BUMP=!1,i.PARALLAX=!1,i.PARALLAXOCCLUSION=!1,i.SPECULAROVERALPHA=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.ALPHAFROMALBEDO=!1,i.POINTSIZE=!1,i.FOG=!1,i.SPECULARTERM=!1,i.OPACITYFRESNEL=!1,i.EMISSIVEFRESNEL=!1,i.FRESNEL=!1,i.NORMAL=!1,i.TANGENT=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.MICROSURFACEFROMREFLECTIVITYMAP=!1,i.MICROSURFACEAUTOMATIC=!1,i.EMISSIVEASILLUMINATION=!1,i.LINKEMISSIVEWITHALBEDO=!1,i.LIGHTMAP=!1,i.USELIGHTMAPASSHADOWMAP=!1,i.REFLECTIONMAP_3D=!1,i.REFLECTIONMAP_SPHERICAL=!1,i.REFLECTIONMAP_PLANAR=!1,i.REFLECTIONMAP_CUBIC=!1,i.REFLECTIONMAP_PROJECTION=!1,i.REFLECTIONMAP_SKYBOX=!1,i.REFLECTIONMAP_EXPLICIT=!1,i.REFLECTIONMAP_EQUIRECTANGULAR=!1,i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,i.INVERTCUBICMAP=!1,i.LOGARITHMICDEPTH=!1,i.CAMERATONEMAP=!1,i.CAMERACONTRAST=!1,i.CAMERACOLORGRADING=!1,i.CAMERACOLORCURVES=!1,i.OVERLOADEDVALUES=!1,i.OVERLOADEDSHADOWVALUES=!1,i.USESPHERICALFROMREFLECTIONMAP=!1,i.REFRACTION=!1,i.REFRACTIONMAP_3D=!1,i.LINKREFRACTIONTOTRANSPARENCY=!1,i.REFRACTIONMAPINLINEARSPACE=!1,i.LODBASEDMICROSFURACE=!1,i.USEPHYSICALLIGHTFALLOFF=!1,i.RADIANCEOVERALPHA=!1,i.USEPMREMREFLECTION=!1,i.USEPMREMREFRACTION=!1,i.TWOSIDEDLIGHTING=!1,i.SHADOWFLOAT=!1,i.METALLICWORKFLOW=!1,i.METALLICMAP=!1,i.ROUGHNESSSTOREINMETALMAPALPHA=!1,i.ROUGHNESSSTOREINMETALMAPGREEN=!1,i.METALLNESSSTOREINMETALMAPBLUE=!1,i.AOSTOREINMETALMAPRED=!1,i.MICROSURFACEMAP=!1,i.MORPHTARGETS=!1,i.MORPHTARGETS_NORMAL=!1,i.MORPHTARGETS_TANGENT=!1,i.NUM_MORPH_INFLUENCERS=0,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(n,r){var o=t.call(this,n,r)||this;return o.directIntensity=1,o.emissiveIntensity=1,o.environmentIntensity=1,o.specularIntensity=1,o._lightingInfos=new e.Vector4(o.directIntensity,o.emissiveIntensity,o.environmentIntensity,o.specularIntensity),o.disableBumpMap=!1,o.overloadedShadowIntensity=1,o.overloadedShadeIntensity=1,o._overloadedShadowInfos=new e.Vector4(o.overloadedShadowIntensity,o.overloadedShadeIntensity,0,0),o.cameraExposure=1,o.cameraContrast=1,o.cameraColorGradingTexture=null,o.cameraColorCurves=null,o._cameraInfos=new e.Vector4(1,1,0,0),o._microsurfaceTextureLods=new e.Vector2(0,0),o.overloadedAmbient=e.Color3.White(),o.overloadedAmbientIntensity=0,o.overloadedAlbedo=e.Color3.White(),o.overloadedAlbedoIntensity=0,o.overloadedReflectivity=new e.Color3(0,0,0),o.overloadedReflectivityIntensity=0,o.overloadedEmissive=e.Color3.White(),o.overloadedEmissiveIntensity=0,o._overloadedIntensity=new e.Vector4(o.overloadedAmbientIntensity,o.overloadedAlbedoIntensity,o.overloadedReflectivityIntensity,o.overloadedEmissiveIntensity),o.overloadedReflection=e.Color3.White(),o.overloadedReflectionIntensity=0,o.overloadedMicroSurface=0,o.overloadedMicroSurfaceIntensity=0,o._overloadedMicroSurface=new e.Vector3(o.overloadedMicroSurface,o.overloadedMicroSurfaceIntensity,o.overloadedReflectionIntensity),o.ambientTextureStrength=1,o.ambientColor=new e.Color3(0,0,0),o.albedoColor=new e.Color3(1,1,1),o.reflectivityColor=new e.Color3(1,1,1),o.reflectionColor=new e.Color3(0,0,0),o.emissiveColor=new e.Color3(0,0,0),o.microSurface=.9,o.indexOfRefraction=.66,o.invertRefractionY=!1,o.linkRefractionWithTransparency=!1,o.linkEmissiveWithAlbedo=!1,o.useLightmapAsShadowmap=!1,o.useEmissiveAsIllumination=!1,o.useAlphaFromAlbedoTexture=!1,o.useSpecularOverAlpha=!0,o.useMicroSurfaceFromReflectivityMapAlpha=!1,o.useRoughnessFromMetallicTextureAlpha=!0,o.useRoughnessFromMetallicTextureGreen=!1,o.useMetallnessFromMetallicTextureBlue=!1,o.useAmbientOcclusionFromMetallicTextureRed=!1,o.useAmbientInGrayScale=!1,o.useAutoMicroSurfaceFromReflectivityMap=!1,o.useScalarInLinearSpace=!1,o.usePhysicalLightFalloff=!0,o.useRadianceOverAlpha=!0,o.useParallax=!1,o.useParallaxOcclusion=!1,o.parallaxScaleBias=.05,o.disableLighting=!1,o.maxSimultaneousLights=4,o.invertNormalMapX=!1,o.invertNormalMapY=!1,o.twoSidedLighting=!1,o._renderTargets=new e.SmartArray(16),o._globalAmbientColor=new e.Color3(0,0,0),o._tempColor=new e.Color3,o._defines=new i,o._cachedDefines=new i,o._myScene=null,o._cachedDefines.BonesPerMesh=-1,o.getRenderTargetTextures=function(){return o._renderTargets.reset(),e.StandardMaterial.ReflectionTextureEnabled&&o.reflectionTexture&&o.reflectionTexture.isRenderTarget&&o._renderTargets.push(o.reflectionTexture),e.StandardMaterial.RefractionTextureEnabled&&o.refractionTexture&&o.refractionTexture.isRenderTarget&&o._renderTargets.push(o.refractionTexture),o._renderTargets},o}return __extends(n,t),n.prototype.getClassName=function(){return"LegacyPBRMaterial"},Object.defineProperty(n.prototype,"useLogarithmicDepth",{get:function(){return this._useLogarithmicDepth},set:function(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported},enumerable:!0,configurable:!0}),n.prototype.needAlphaBlending=function(){return!this.linkRefractionWithTransparency&&(this.alpha<1||null!=this.opacityTexture||this._shouldUseAlphaFromAlbedoTexture()||this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled)},n.prototype.needAlphaTesting=function(){return!this.linkRefractionWithTransparency&&(null!=this.albedoTexture&&this.albedoTexture.hasAlpha)},n.prototype._shouldUseAlphaFromAlbedoTexture=function(){return null!=this.albedoTexture&&this.albedoTexture.hasAlpha&&this.useAlphaFromAlbedoTexture},n.prototype.getAlphaTestTexture=function(){return this.albedoTexture},n.prototype._checkCache=function(e,i,t){return!i||(this._defines.INSTANCES,!1)},n.prototype.convertColorToLinearSpaceToRef=function(e,i){n.convertColorToLinearSpaceToRef(e,i,this.useScalarInLinearSpace)},n.convertColorToLinearSpaceToRef=function(e,i,t){t?(i.r=e.r,i.g=e.g,i.b=e.b):e.toLinearSpaceToRef(i)},n.BindLights=function(i,t,r,o,a,s,f){for(var l=0,u=0,c=t._lightSources;u<c.length;u++){var d=c[u],m=d._uniformBuffer.useUbo;if(d._uniformBuffer.bindToEffect(r,"Light"+l),e.MaterialHelper.BindLightProperties(d,r,l),this.convertColorToLinearSpaceToRef(d.diffuse,n._scaledAlbedo,a),n._scaledAlbedo.scaleToRef(d.intensity,n._scaledAlbedo),d._uniformBuffer.updateColor4(m?"vLightDiffuse":"vLightDiffuse"+l,n._scaledAlbedo,f?d.radius:d.range),o.SPECULARTERM&&(this.convertColorToLinearSpaceToRef(d.specular,n._scaledReflectivity,a),n._scaledReflectivity.scaleToRef(d.intensity,n._scaledReflectivity),d._uniformBuffer.updateColor3(m?"vLightSpecular":"vLightSpecular"+l,n._scaledReflectivity)),i.shadowsEnabled&&e.MaterialHelper.BindLightShadow(d,i,t,l+"",r),d._uniformBuffer.update(),++l===s)break}},n.prototype.isReady=function(i,t){var n=this;if(this.isFrozen&&this._wasPreviouslyReady)return!0;var r=this.getScene(),o=r.getEngine(),a=!1;if(this._defines.reset(),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.PrepareDefinesForLights(r,i,this._defines,!0,this.maxSimultaneousLights),!this.checkReadyOnEveryCall&&this._renderId===r.getRenderId()&&this._checkCache(r,i,t))return!0;if(r.texturesEnabled){if(r.getEngine().getCaps().textureLOD&&(this._defines.LODBASEDMICROSFURACE=!0),this.albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled){if(!this.albedoTexture.isReady())return!1;a=!0,this._defines.ALBEDO=!0}if(this.ambientTexture&&e.StandardMaterial.AmbientTextureEnabled){if(!this.ambientTexture.isReady())return!1;a=!0,this._defines.AMBIENT=!0,this._defines.AMBIENTINGRAYSCALE=this.useAmbientInGrayScale}if(this.opacityTexture&&e.StandardMaterial.OpacityTextureEnabled){if(!this.opacityTexture.isReady())return!1;a=!0,this._defines.OPACITY=!0,this.opacityTexture.getAlphaFromRGB&&(this._defines.OPACITYRGB=!0)}if(this.reflectionTexture&&e.StandardMaterial.ReflectionTextureEnabled){if(!this.reflectionTexture.isReady())return!1;switch(this._defines.REFLECTION=!0,this.reflectionTexture.coordinatesMode===e.Texture.INVCUBIC_MODE&&(this._defines.INVERTCUBICMAP=!0),this._defines.REFLECTIONMAP_3D=this.reflectionTexture.isCube,this.reflectionTexture.coordinatesMode){case e.Texture.CUBIC_MODE:case e.Texture.INVCUBIC_MODE:this._defines.REFLECTIONMAP_CUBIC=!0;break;case e.Texture.EXPLICIT_MODE:this._defines.REFLECTIONMAP_EXPLICIT=!0;break;case e.Texture.PLANAR_MODE:this._defines.REFLECTIONMAP_PLANAR=!0;break;case e.Texture.PROJECTION_MODE:this._defines.REFLECTIONMAP_PROJECTION=!0;break;case e.Texture.SKYBOX_MODE:this._defines.REFLECTIONMAP_SKYBOX=!0;break;case e.Texture.SPHERICAL_MODE:this._defines.REFLECTIONMAP_SPHERICAL=!0;break;case e.Texture.EQUIRECTANGULAR_MODE:this._defines.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case e.Texture.FIXED_EQUIRECTANGULAR_MODE:this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case e.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:this._defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0}this.reflectionTexture instanceof e.HDRCubeTexture&&this.reflectionTexture&&(this._defines.USESPHERICALFROMREFLECTIONMAP=!0,this.reflectionTexture.isPMREM&&(this._defines.USEPMREMREFLECTION=!0))}if(this.lightmapTexture&&e.StandardMaterial.LightmapTextureEnabled){if(!this.lightmapTexture.isReady())return!1;a=!0,this._defines.LIGHTMAP=!0,this._defines.USELIGHTMAPASSHADOWMAP=this.useLightmapAsShadowmap}if(this.emissiveTexture&&e.StandardMaterial.EmissiveTextureEnabled){if(!this.emissiveTexture.isReady())return!1;a=!0,this._defines.EMISSIVE=!0}if(e.StandardMaterial.SpecularTextureEnabled){if(this.metallicTexture){if(!this.metallicTexture.isReady())return!1;a=!0,this._defines.METALLICWORKFLOW=!0,this._defines.METALLICMAP=!0,this._defines.ROUGHNESSSTOREINMETALMAPALPHA=this.useRoughnessFromMetallicTextureAlpha,this._defines.ROUGHNESSSTOREINMETALMAPGREEN=!this.useRoughnessFromMetallicTextureAlpha&&this.useRoughnessFromMetallicTextureGreen,this._defines.METALLNESSSTOREINMETALMAPBLUE=this.useMetallnessFromMetallicTextureBlue,this._defines.AOSTOREINMETALMAPRED=this.useAmbientOcclusionFromMetallicTextureRed}else if(this.reflectivityTexture){if(!this.reflectivityTexture.isReady())return!1;a=!0,this._defines.REFLECTIVITY=!0,this._defines.MICROSURFACEFROMREFLECTIVITYMAP=this.useMicroSurfaceFromReflectivityMapAlpha,this._defines.MICROSURFACEAUTOMATIC=this.useAutoMicroSurfaceFromReflectivityMap}if(this.microSurfaceTexture){if(!this.microSurfaceTexture.isReady())return!1;a=!0,this._defines.MICROSURFACEMAP=!0}}if(r.getEngine().getCaps().standardDerivatives&&this.bumpTexture&&e.StandardMaterial.BumpTextureEnabled&&!this.disableBumpMap){if(!this.bumpTexture.isReady())return!1;a=!0,this._defines.BUMP=!0,this.useParallax&&this.albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._defines.PARALLAX=!0,this.useParallaxOcclusion&&(this._defines.PARALLAXOCCLUSION=!0))}if(this.refractionTexture&&e.StandardMaterial.RefractionTextureEnabled){if(!this.refractionTexture.isReady())return!1;a=!0,this._defines.REFRACTION=!0,this._defines.REFRACTIONMAP_3D=this.refractionTexture.isCube,this.linkRefractionWithTransparency&&(this._defines.LINKREFRACTIONTOTRANSPARENCY=!0),this.refractionTexture instanceof e.HDRCubeTexture&&(this._defines.REFRACTIONMAPINLINEARSPACE=!0,this.refractionTexture.isPMREM&&(this._defines.USEPMREMREFRACTION=!0))}if(this.cameraColorGradingTexture&&e.StandardMaterial.ColorGradingTextureEnabled){if(!this.cameraColorGradingTexture.isReady())return!1;this._defines.CAMERACOLORGRADING=!0}!this.backFaceCulling&&this.twoSidedLighting&&(this._defines.TWOSIDEDLIGHTING=!0)}if(r.clipPlane&&(this._defines.CLIPPLANE=!0),o.getAlphaTesting()&&(this._defines.ALPHATEST=!0),this._shouldUseAlphaFromAlbedoTexture()&&(this._defines.ALPHAFROMALBEDO=!0),this.useEmissiveAsIllumination&&(this._defines.EMISSIVEASILLUMINATION=!0),this.linkEmissiveWithAlbedo&&(this._defines.LINKEMISSIVEWITHALBEDO=!0),this.useLogarithmicDepth&&(this._defines.LOGARITHMICDEPTH=!0),1!=this.cameraContrast&&(this._defines.CAMERACONTRAST=!0),1!=this.cameraExposure&&(this._defines.CAMERATONEMAP=!0),this.cameraColorCurves&&(this._defines.CAMERACOLORCURVES=!0),1==this.overloadedShadeIntensity&&1==this.overloadedShadowIntensity||(this._defines.OVERLOADEDSHADOWVALUES=!0),(this.overloadedMicroSurfaceIntensity>0||this.overloadedEmissiveIntensity>0||this.overloadedReflectivityIntensity>0||this.overloadedAlbedoIntensity>0||this.overloadedAmbientIntensity>0||this.overloadedReflectionIntensity>0)&&(this._defines.OVERLOADEDVALUES=!0),(this.pointsCloud||r.forcePointsCloud)&&(this._defines.POINTSIZE=!0),r.fogEnabled&&i&&i.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this.fogEnabled&&(this._defines.FOG=!0),e.StandardMaterial.FresnelEnabled&&(this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled||this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled)&&(this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&(this._defines.OPACITYFRESNEL=!0),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(this._defines.EMISSIVEFRESNEL=!0),this._defines.FRESNEL=!0),this._defines.SPECULARTERM&&this.useSpecularOverAlpha&&(this._defines.SPECULAROVERALPHA=!0),this.usePhysicalLightFalloff&&(this._defines.USEPHYSICALLIGHTFALLOFF=!0),this.useRadianceOverAlpha&&(this._defines.RADIANCEOVERALPHA=!0),(void 0!==this.metallic&&null!==this.metallic||void 0!==this.roughness&&null!==this.roughness)&&(this._defines.METALLICWORKFLOW=!0),i&&(r.getEngine().getCaps().standardDerivatives||i.isVerticesDataPresent(e.VertexBuffer.NormalKind)||(i.createNormals(!0),e.Tools.Warn("PBRMaterial: Normals have been created for the mesh: "+i.name)),i.isVerticesDataPresent(e.VertexBuffer.NormalKind)&&(this._defines.NORMAL=!0,i.isVerticesDataPresent(e.VertexBuffer.TangentKind)&&(this._defines.TANGENT=!0)),a&&(i.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(this._defines.UV1=!0),i.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&(this._defines.UV2=!0)),i.useVertexColors&&i.isVerticesDataPresent(e.VertexBuffer.ColorKind)&&(this._defines.VERTEXCOLOR=!0,i.hasVertexAlpha&&(this._defines.VERTEXALPHA=!0)),i.useBones&&i.computeBonesUsingShaders&&(this._defines.NUM_BONE_INFLUENCERS=i.numBoneInfluencers,this._defines.BonesPerMesh=i.skeleton.bones.length+1),t&&(this._defines.INSTANCES=!0),i.morphTargetManager)){var s=i.morphTargetManager;this._defines.MORPHTARGETS_TANGENT=s.supportsTangents&&this._defines.TANGENT,this._defines.MORPHTARGETS_NORMAL=s.supportsNormals&&this._defines.NORMAL,this._defines.MORPHTARGETS=s.numInfluencers>0,this._defines.NUM_MORPH_INFLUENCERS=s.numInfluencers}if(!this._defines.isEqual(this._cachedDefines)){this._defines.cloneTo(this._cachedDefines),r.resetCachedMaterial();var f=new e.EffectFallbacks;this._defines.REFLECTION&&f.addFallback(0,"REFLECTION"),this._defines.REFRACTION&&f.addFallback(0,"REFRACTION"),this._defines.REFLECTIVITY&&f.addFallback(0,"REFLECTIVITY"),this._defines.BUMP&&f.addFallback(0,"BUMP"),this._defines.PARALLAX&&f.addFallback(1,"PARALLAX"),this._defines.PARALLAXOCCLUSION&&f.addFallback(0,"PARALLAXOCCLUSION"),this._defines.SPECULAROVERALPHA&&f.addFallback(0,"SPECULAROVERALPHA"),this._defines.FOG&&f.addFallback(1,"FOG"),this._defines.POINTSIZE&&f.addFallback(0,"POINTSIZE"),this._defines.LOGARITHMICDEPTH&&f.addFallback(0,"LOGARITHMICDEPTH"),e.MaterialHelper.HandleFallbacksForShadows(this._defines,f,this.maxSimultaneousLights),this._defines.SPECULARTERM&&f.addFallback(0,"SPECULARTERM"),this._defines.OPACITYFRESNEL&&f.addFallback(1,"OPACITYFRESNEL"),this._defines.EMISSIVEFRESNEL&&f.addFallback(2,"EMISSIVEFRESNEL"),this._defines.FRESNEL&&f.addFallback(3,"FRESNEL"),this._defines.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,i);var l=[e.VertexBuffer.PositionKind];this._defines.NORMAL&&l.push(e.VertexBuffer.NormalKind),this._defines.TANGENT&&l.push(e.VertexBuffer.TangentKind),this._defines.UV1&&l.push(e.VertexBuffer.UVKind),this._defines.UV2&&l.push(e.VertexBuffer.UV2Kind),this._defines.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,i,this._defines,f),e.MaterialHelper.PrepareAttributesForInstances(l,this._defines),e.MaterialHelper.PrepareAttributesForMorphTargets(l,i,this._defines);var u=this._defines.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vEmissiveColor","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vReflectivityInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","vClipPlane","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","refractionMatrix","opacityParts","emissiveLeftColor","emissiveRightColor","vLightingIntensity","vOverloadedShadowIntensity","vOverloadedIntensity","vOverloadedAlbedo","vOverloadedReflection","vOverloadedReflectivity","vOverloadedEmissive","vOverloadedMicroSurface","logarithmicDepthConstant","vSphericalX","vSphericalY","vSphericalZ","vSphericalXX","vSphericalYY","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vMicrosurfaceTextureLods","vCameraInfos","vTangentSpaceParams"],d=["albedoSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","reflectivitySampler","microSurfaceSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler"],m=["Material","Scene"];this._defines.CAMERACOLORCURVES&&e.ColorCurves.PrepareUniforms(c),
  98837. this._defines.CAMERACOLORGRADING&&(c.push("vCameraColorGradingInfos","vCameraColorGradingScaleOffset"),d.push("cameraColorGrading2DSampler")),e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:m,samplers:d,defines:this._defines,maxSimultaneousLights:this.maxSimultaneousLights});var v=function(e){n.onCompiled&&n.onCompiled(e),n.bindSceneUniformBuffer(e,r.getSceneUniformBuffer())};this._effect=r.getEngine().createEffect("legacyPbr",{attributes:l,uniformsNames:c,uniformBuffersNames:m,samplers:d,defines:u,fallbacks:f,onCompiled:v,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:this._defines.NUM_MORPH_INFLUENCERS}},o),this.buildUniformLayout()}return!!this._effect.isReady()&&(this._renderId=r.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.buildUniformLayout=function(){this._uniformBuffer.addUniform("vAlbedoInfos",2),this._uniformBuffer.addUniform("vAmbientInfos",3),this._uniformBuffer.addUniform("vOpacityInfos",2),this._uniformBuffer.addUniform("vEmissiveInfos",2),this._uniformBuffer.addUniform("vLightmapInfos",2),this._uniformBuffer.addUniform("vReflectivityInfos",3),this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos",2),this._uniformBuffer.addUniform("vRefractionInfos",4),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("vBumpInfos",3),this._uniformBuffer.addUniform("albedoMatrix",16),this._uniformBuffer.addUniform("ambientMatrix",16),this._uniformBuffer.addUniform("opacityMatrix",16),this._uniformBuffer.addUniform("emissiveMatrix",16),this._uniformBuffer.addUniform("lightmapMatrix",16),this._uniformBuffer.addUniform("reflectivityMatrix",16),this._uniformBuffer.addUniform("microSurfaceSamplerMatrix",16),this._uniformBuffer.addUniform("bumpMatrix",16),this._uniformBuffer.addUniform("vTangentSpaceParams",2),this._uniformBuffer.addUniform("refractionMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionColor",3),this._uniformBuffer.addUniform("vAlbedoColor",4),this._uniformBuffer.addUniform("vLightingIntensity",4),this._uniformBuffer.addUniform("vMicrosurfaceTextureLods",2),this._uniformBuffer.addUniform("vReflectivityColor",4),this._uniformBuffer.addUniform("vEmissiveColor",3),this._uniformBuffer.addUniform("opacityParts",4),this._uniformBuffer.addUniform("emissiveLeftColor",4),this._uniformBuffer.addUniform("emissiveRightColor",4),this._uniformBuffer.addUniform("vOverloadedIntensity",4),this._uniformBuffer.addUniform("vOverloadedAmbient",3),this._uniformBuffer.addUniform("vOverloadedAlbedo",3),this._uniformBuffer.addUniform("vOverloadedReflectivity",3),this._uniformBuffer.addUniform("vOverloadedEmissive",3),this._uniformBuffer.addUniform("vOverloadedReflection",3),this._uniformBuffer.addUniform("vOverloadedMicroSurface",3),this._uniformBuffer.addUniform("vOverloadedShadowIntensity",4),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.create()},n.prototype.unbind=function(){this.reflectionTexture&&this.reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflection2DSampler",null),this.refractionTexture&&this.refractionTexture.isRenderTarget&&this._uniformBuffer.setTexture("refraction2DSampler",null),t.prototype.unbind.call(this)},n.prototype.bindOnlyWorldMatrix=function(e){this._effect.setMatrix("world",e)},n.prototype.bind=function(i,t){this._myScene=this.getScene();var r=this._effect;if(this.bindOnlyWorldMatrix(i),e.MaterialHelper.BindBonesParameters(t,this._effect),this._myScene.getCachedMaterial()!==this){if(this._uniformBuffer.bindToEffect(r,"Material"),this.bindViewProjection(r),!this._uniformBuffer.useUbo||!this.isFrozen||!this._uniformBuffer.isSync){if(e.StandardMaterial.FresnelEnabled&&(this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&this._uniformBuffer.updateColor4("opacityParts",new e.Color3(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),this._uniformBuffer.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),this._myScene.texturesEnabled){if(this.albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vAlbedoInfos",this.albedoTexture.coordinatesIndex,this.albedoTexture.level),this._uniformBuffer.updateMatrix("albedoMatrix",this.albedoTexture.getTextureMatrix())),this.ambientTexture&&e.StandardMaterial.AmbientTextureEnabled&&(this._uniformBuffer.updateFloat3("vAmbientInfos",this.ambientTexture.coordinatesIndex,this.ambientTexture.level,this.ambientTextureStrength),this._uniformBuffer.updateMatrix("ambientMatrix",this.ambientTexture.getTextureMatrix())),this.opacityTexture&&e.StandardMaterial.OpacityTextureEnabled&&(this._uniformBuffer.updateFloat2("vOpacityInfos",this.opacityTexture.coordinatesIndex,this.opacityTexture.level),this._uniformBuffer.updateMatrix("opacityMatrix",this.opacityTexture.getTextureMatrix())),this.reflectionTexture&&e.StandardMaterial.ReflectionTextureEnabled&&(this._microsurfaceTextureLods.x=Math.round(Math.log(this.reflectionTexture.getSize().width)*Math.LOG2E),this._uniformBuffer.updateMatrix("reflectionMatrix",this.reflectionTexture.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",this.reflectionTexture.level,0),this._defines.USESPHERICALFROMREFLECTIONMAP)){var o=this.reflectionTexture.sphericalPolynomial;this._effect.setFloat3("vSphericalX",o.x.x,o.x.y,o.x.z),this._effect.setFloat3("vSphericalY",o.y.x,o.y.y,o.y.z),this._effect.setFloat3("vSphericalZ",o.z.x,o.z.y,o.z.z),this._effect.setFloat3("vSphericalXX_ZZ",o.xx.x-o.zz.x,o.xx.y-o.zz.y,o.xx.z-o.zz.z),this._effect.setFloat3("vSphericalYY_ZZ",o.yy.x-o.zz.x,o.yy.y-o.zz.y,o.yy.z-o.zz.z),this._effect.setFloat3("vSphericalZZ",o.zz.x,o.zz.y,o.zz.z),this._effect.setFloat3("vSphericalXY",o.xy.x,o.xy.y,o.xy.z),this._effect.setFloat3("vSphericalYZ",o.yz.x,o.yz.y,o.yz.z),this._effect.setFloat3("vSphericalZX",o.zx.x,o.zx.y,o.zx.z)}if(this.emissiveTexture&&e.StandardMaterial.EmissiveTextureEnabled&&(this._uniformBuffer.updateFloat2("vEmissiveInfos",this.emissiveTexture.coordinatesIndex,this.emissiveTexture.level),this._uniformBuffer.updateMatrix("emissiveMatrix",this.emissiveTexture.getTextureMatrix())),this.lightmapTexture&&e.StandardMaterial.LightmapTextureEnabled&&(this._uniformBuffer.updateFloat2("vLightmapInfos",this.lightmapTexture.coordinatesIndex,this.lightmapTexture.level),this._uniformBuffer.updateMatrix("lightmapMatrix",this.lightmapTexture.getTextureMatrix())),e.StandardMaterial.SpecularTextureEnabled&&(this.metallicTexture?(this._uniformBuffer.updateFloat3("vReflectivityInfos",this.metallicTexture.coordinatesIndex,this.metallicTexture.level,this.ambientTextureStrength),this._uniformBuffer.updateMatrix("reflectivityMatrix",this.metallicTexture.getTextureMatrix())):this.reflectivityTexture&&(this._uniformBuffer.updateFloat3("vReflectivityInfos",this.reflectivityTexture.coordinatesIndex,this.reflectivityTexture.level,1),this._uniformBuffer.updateMatrix("reflectivityMatrix",this.reflectivityTexture.getTextureMatrix())),this.microSurfaceTexture&&(this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos",this.microSurfaceTexture.coordinatesIndex,this.microSurfaceTexture.level),this._uniformBuffer.updateMatrix("microSurfaceSamplerMatrix",this.microSurfaceTexture.getTextureMatrix()))),this.bumpTexture&&this._myScene.getEngine().getCaps().standardDerivatives&&e.StandardMaterial.BumpTextureEnabled&&!this.disableBumpMap&&(this._uniformBuffer.updateFloat3("vBumpInfos",this.bumpTexture.coordinatesIndex,1/this.bumpTexture.level,this.parallaxScaleBias),this._uniformBuffer.updateMatrix("bumpMatrix",this.bumpTexture.getTextureMatrix()),this._myScene._mirroredCameraPosition?this._uniformBuffer.updateFloat2("vTangentSpaceParams",this.invertNormalMapX?1:-1,this.invertNormalMapY?1:-1):this._uniformBuffer.updateFloat2("vTangentSpaceParams",this.invertNormalMapX?-1:1,this.invertNormalMapY?-1:1)),this.refractionTexture&&e.StandardMaterial.RefractionTextureEnabled){this._microsurfaceTextureLods.y=Math.round(Math.log(this.refractionTexture.getSize().width)*Math.LOG2E);var a=1;this.refractionTexture.isCube||(this._uniformBuffer.updateMatrix("refractionMatrix",this.refractionTexture.getReflectionTextureMatrix()),this.refractionTexture.depth&&(a=this.refractionTexture.depth)),this._uniformBuffer.updateFloat4("vRefractionInfos",this.refractionTexture.level,this.indexOfRefraction,a,this.invertRefractionY?-1:1)}(this.reflectionTexture||this.refractionTexture)&&this._uniformBuffer.updateFloat2("vMicrosurfaceTextureLods",this._microsurfaceTextureLods.x,this._microsurfaceTextureLods.y)}this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),this._defines.METALLICWORKFLOW?(n._scaledReflectivity.r=void 0===this.metallic||null===this.metallic?1:this.metallic,n._scaledReflectivity.g=void 0===this.roughness||null===this.roughness?1:this.roughness,this._uniformBuffer.updateColor4("vReflectivityColor",n._scaledReflectivity,0)):(this.convertColorToLinearSpaceToRef(this.reflectivityColor,n._scaledReflectivity),this._uniformBuffer.updateColor4("vReflectivityColor",n._scaledReflectivity,this.microSurface)),this.convertColorToLinearSpaceToRef(this.emissiveColor,n._scaledEmissive),this._uniformBuffer.updateColor3("vEmissiveColor",n._scaledEmissive),this.convertColorToLinearSpaceToRef(this.reflectionColor,n._scaledReflection),this._uniformBuffer.updateColor3("vReflectionColor",n._scaledReflection),this.convertColorToLinearSpaceToRef(this.albedoColor,n._scaledAlbedo),this._uniformBuffer.updateColor4("vAlbedoColor",n._scaledAlbedo,this.alpha*t.visibility),this._lightingInfos.x=this.directIntensity,this._lightingInfos.y=this.emissiveIntensity,this._lightingInfos.z=this.environmentIntensity,this._lightingInfos.w=this.specularIntensity,this._uniformBuffer.updateVector4("vLightingIntensity",this._lightingInfos),this._overloadedShadowInfos.x=this.overloadedShadowIntensity,this._overloadedShadowInfos.y=this.overloadedShadeIntensity,this._uniformBuffer.updateVector4("vOverloadedShadowIntensity",this._overloadedShadowInfos),this._overloadedIntensity.x=this.overloadedAmbientIntensity,this._overloadedIntensity.y=this.overloadedAlbedoIntensity,this._overloadedIntensity.z=this.overloadedReflectivityIntensity,this._overloadedIntensity.w=this.overloadedEmissiveIntensity,this._uniformBuffer.updateVector4("vOverloadedIntensity",this._overloadedIntensity),this._uniformBuffer.updateColor3("vOverloadedAmbient",this.overloadedAmbient),this.convertColorToLinearSpaceToRef(this.overloadedAlbedo,this._tempColor),this._uniformBuffer.updateColor3("vOverloadedAlbedo",this._tempColor),this.convertColorToLinearSpaceToRef(this.overloadedReflectivity,this._tempColor),this._uniformBuffer.updateColor3("vOverloadedReflectivity",this._tempColor),this.convertColorToLinearSpaceToRef(this.overloadedEmissive,this._tempColor),this._uniformBuffer.updateColor3("vOverloadedEmissive",this._tempColor),this.convertColorToLinearSpaceToRef(this.overloadedReflection,this._tempColor),this._uniformBuffer.updateColor3("vOverloadedReflection",this._tempColor),this._overloadedMicroSurface.x=this.overloadedMicroSurface,this._overloadedMicroSurface.y=this.overloadedMicroSurfaceIntensity,this._overloadedMicroSurface.z=this.overloadedReflectionIntensity,this._uniformBuffer.updateVector3("vOverloadedMicroSurface",this._overloadedMicroSurface)}if(this._myScene.texturesEnabled&&(this.albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("albedoSampler",this.albedoTexture),this.ambientTexture&&e.StandardMaterial.AmbientTextureEnabled&&this._uniformBuffer.setTexture("ambientSampler",this.ambientTexture),this.opacityTexture&&e.StandardMaterial.OpacityTextureEnabled&&this._uniformBuffer.setTexture("opacitySampler",this.opacityTexture),this.reflectionTexture&&e.StandardMaterial.ReflectionTextureEnabled&&(this.reflectionTexture.isCube?this._uniformBuffer.setTexture("reflectionCubeSampler",this.reflectionTexture):this._uniformBuffer.setTexture("reflection2DSampler",this.reflectionTexture)),this.emissiveTexture&&e.StandardMaterial.EmissiveTextureEnabled&&this._uniformBuffer.setTexture("emissiveSampler",this.emissiveTexture),this.lightmapTexture&&e.StandardMaterial.LightmapTextureEnabled&&this._uniformBuffer.setTexture("lightmapSampler",this.lightmapTexture),e.StandardMaterial.SpecularTextureEnabled&&(this.metallicTexture?this._uniformBuffer.setTexture("reflectivitySampler",this.metallicTexture):this.reflectivityTexture&&this._uniformBuffer.setTexture("reflectivitySampler",this.reflectivityTexture),this.microSurfaceTexture&&this._uniformBuffer.setTexture("microSurfaceSampler",this.microSurfaceTexture)),this.bumpTexture&&this._myScene.getEngine().getCaps().standardDerivatives&&e.StandardMaterial.BumpTextureEnabled&&!this.disableBumpMap&&this._uniformBuffer.setTexture("bumpSampler",this.bumpTexture),this.refractionTexture&&e.StandardMaterial.RefractionTextureEnabled&&(this.refractionTexture.isCube?this._uniformBuffer.setTexture("refractionCubeSampler",this.refractionTexture):this._uniformBuffer.setTexture("refraction2DSampler",this.refractionTexture)),this.cameraColorGradingTexture&&e.StandardMaterial.ColorGradingTextureEnabled)){this._effect.setTexture("cameraColorGrading2DSampler",this.cameraColorGradingTexture);var s=this.cameraColorGradingTexture.level,f=this.cameraColorGradingTexture.getSize().height,l=f-1,u=1/f;this._effect.setFloat4("vCameraColorGradingInfos",s,f,l,u);var c=u/f,d=u,m=l*c,v=l/f,h=.5*c,p=.5*d;this._effect.setFloat4("vCameraColorGradingScaleOffset",m,v,h,p)}e.MaterialHelper.BindClipPlane(this._effect,this._myScene),this._myScene.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),r.setVector3("vEyePosition",this._myScene._mirroredCameraPosition?this._myScene._mirroredCameraPosition:this._myScene.activeCamera.position),r.setColor3("vAmbientColor",this._globalAmbientColor)}this._myScene.getCachedMaterial()===this&&this.isFrozen||(this._myScene.lightsEnabled&&!this.disableLighting&&n.BindLights(this._myScene,t,this._effect,this._defines,this.useScalarInLinearSpace,this.maxSimultaneousLights,this.usePhysicalLightFalloff),(this._myScene.fogEnabled&&t.applyFog&&this._myScene.fogMode!==e.Scene.FOGMODE_NONE||this.reflectionTexture)&&this.bindView(r),e.MaterialHelper.BindFogParameters(this._myScene,t,this._effect),this._defines.NUM_MORPH_INFLUENCERS&&e.MaterialHelper.BindMorphTargetParameters(t,this._effect),this._cameraInfos.x=this.cameraExposure,this._cameraInfos.y=this.cameraContrast,r.setVector4("vCameraInfos",this._cameraInfos),this.cameraColorCurves&&e.ColorCurves.Bind(this.cameraColorCurves,this._effect),e.MaterialHelper.BindLogDepth(this._defines,this._effect,this._myScene)),this._uniformBuffer.update(),this._afterBind(t),this._myScene=null},n.prototype.getAnimatables=function(){var e=[];return this.albedoTexture&&this.albedoTexture.animations&&this.albedoTexture.animations.length>0&&e.push(this.albedoTexture),this.ambientTexture&&this.ambientTexture.animations&&this.ambientTexture.animations.length>0&&e.push(this.ambientTexture),this.opacityTexture&&this.opacityTexture.animations&&this.opacityTexture.animations.length>0&&e.push(this.opacityTexture),this.reflectionTexture&&this.reflectionTexture.animations&&this.reflectionTexture.animations.length>0&&e.push(this.reflectionTexture),this.emissiveTexture&&this.emissiveTexture.animations&&this.emissiveTexture.animations.length>0&&e.push(this.emissiveTexture),this.metallicTexture&&this.metallicTexture.animations&&this.metallicTexture.animations.length>0?e.push(this.metallicTexture):this.reflectivityTexture&&this.reflectivityTexture.animations&&this.reflectivityTexture.animations.length>0&&e.push(this.reflectivityTexture),this.bumpTexture&&this.bumpTexture.animations&&this.bumpTexture.animations.length>0&&e.push(this.bumpTexture),this.lightmapTexture&&this.lightmapTexture.animations&&this.lightmapTexture.animations.length>0&&e.push(this.lightmapTexture),this.refractionTexture&&this.refractionTexture.animations&&this.refractionTexture.animations.length>0&&e.push(this.refractionTexture),this.cameraColorGradingTexture&&this.cameraColorGradingTexture.animations&&this.cameraColorGradingTexture.animations.length>0&&e.push(this.cameraColorGradingTexture),e},n.prototype.dispose=function(e,i){i&&(this.albedoTexture&&this.albedoTexture.dispose(),this.ambientTexture&&this.ambientTexture.dispose(),this.opacityTexture&&this.opacityTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose(),this.emissiveTexture&&this.emissiveTexture.dispose(),this.metallicTexture&&this.metallicTexture.dispose(),this.reflectivityTexture&&this.reflectivityTexture.dispose(),this.bumpTexture&&this.bumpTexture.dispose(),this.lightmapTexture&&this.lightmapTexture.dispose(),this.refractionTexture&&this.refractionTexture.dispose(),this.cameraColorGradingTexture&&this.cameraColorGradingTexture.dispose()),this._renderTargets.dispose(),t.prototype.dispose.call(this,e,i)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.LegacyPBRMaterial",i},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},n._scaledAlbedo=new e.Color3,n._scaledReflectivity=new e.Color3,n._scaledEmissive=new e.Color3,n._scaledReflection=new e.Color3,__decorate([e.serialize()],n.prototype,"directIntensity",void 0),__decorate([e.serialize()],n.prototype,"emissiveIntensity",void 0),__decorate([e.serialize()],n.prototype,"environmentIntensity",void 0),__decorate([e.serialize()],n.prototype,"specularIntensity",void 0),__decorate([e.serialize()],n.prototype,"disableBumpMap",void 0),__decorate([e.serialize()],n.prototype,"overloadedShadowIntensity",void 0),__decorate([e.serialize()],n.prototype,"overloadedShadeIntensity",void 0),__decorate([e.serialize()],n.prototype,"cameraExposure",void 0),__decorate([e.serialize()],n.prototype,"cameraContrast",void 0),__decorate([e.serializeAsTexture()],n.prototype,"cameraColorGradingTexture",void 0),__decorate([e.serializeAsColorCurves()],n.prototype,"cameraColorCurves",void 0),__decorate([e.serializeAsColor3()],n.prototype,"overloadedAmbient",void 0),__decorate([e.serialize()],n.prototype,"overloadedAmbientIntensity",void 0),__decorate([e.serializeAsColor3()],n.prototype,"overloadedAlbedo",void 0),__decorate([e.serialize()],n.prototype,"overloadedAlbedoIntensity",void 0),__decorate([e.serializeAsColor3()],n.prototype,"overloadedReflectivity",void 0),__decorate([e.serialize()],n.prototype,"overloadedReflectivityIntensity",void 0),__decorate([e.serializeAsColor3()],n.prototype,"overloadedEmissive",void 0),__decorate([e.serialize()],n.prototype,"overloadedEmissiveIntensity",void 0),__decorate([e.serializeAsColor3()],n.prototype,"overloadedReflection",void 0),__decorate([e.serialize()],n.prototype,"overloadedReflectionIntensity",void 0),__decorate([e.serialize()],n.prototype,"overloadedMicroSurface",void 0),__decorate([e.serialize()],n.prototype,"overloadedMicroSurfaceIntensity",void 0),__decorate([e.serializeAsTexture()],n.prototype,"albedoTexture",void 0),__decorate([e.serializeAsTexture()],n.prototype,"ambientTexture",void 0),__decorate([e.serialize()],n.prototype,"ambientTextureStrength",void 0),__decorate([e.serializeAsTexture()],n.prototype,"opacityTexture",void 0),__decorate([e.serializeAsTexture()],n.prototype,"reflectionTexture",void 0),__decorate([e.serializeAsTexture()],n.prototype,"emissiveTexture",void 0),__decorate([e.serializeAsTexture()],n.prototype,"reflectivityTexture",void 0),__decorate([e.serializeAsTexture()],n.prototype,"metallicTexture",void 0),__decorate([e.serialize()],n.prototype,"metallic",void 0),__decorate([e.serialize()],n.prototype,"roughness",void 0),__decorate([e.serializeAsTexture()],n.prototype,"microSurfaceTexture",void 0),__decorate([e.serializeAsTexture()],n.prototype,"bumpTexture",void 0),__decorate([e.serializeAsTexture()],n.prototype,"lightmapTexture",void 0),__decorate([e.serializeAsTexture()],n.prototype,"refractionTexture",void 0),__decorate([e.serializeAsColor3("ambient")],n.prototype,"ambientColor",void 0),__decorate([e.serializeAsColor3("albedo")],n.prototype,"albedoColor",void 0),__decorate([e.serializeAsColor3("reflectivity")],n.prototype,"reflectivityColor",void 0),__decorate([e.serializeAsColor3("reflection")],n.prototype,"reflectionColor",void 0),__decorate([e.serializeAsColor3("emissive")],n.prototype,"emissiveColor",void 0),__decorate([e.serialize()],n.prototype,"microSurface",void 0),__decorate([e.serialize()],n.prototype,"indexOfRefraction",void 0),__decorate([e.serialize()],n.prototype,"invertRefractionY",void 0),__decorate([e.serializeAsFresnelParameters()],n.prototype,"opacityFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters()],n.prototype,"emissiveFresnelParameters",void 0),__decorate([e.serialize()],n.prototype,"linkRefractionWithTransparency",void 0),__decorate([e.serialize()],n.prototype,"linkEmissiveWithAlbedo",void 0),__decorate([e.serialize()],n.prototype,"useLightmapAsShadowmap",void 0),__decorate([e.serialize()],n.prototype,"useEmissiveAsIllumination",void 0),__decorate([e.serialize()],n.prototype,"useAlphaFromAlbedoTexture",void 0),__decorate([e.serialize()],n.prototype,"useSpecularOverAlpha",void 0),__decorate([e.serialize()],n.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),__decorate([e.serialize()],n.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),__decorate([e.serialize()],n.prototype,"useRoughnessFromMetallicTextureGreen",void 0),__decorate([e.serialize()],n.prototype,"useMetallnessFromMetallicTextureBlue",void 0),__decorate([e.serialize()],n.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),__decorate([e.serialize()],n.prototype,"useAmbientInGrayScale",void 0),__decorate([e.serialize()],n.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),__decorate([e.serialize()],n.prototype,"useScalarInLinearSpace",void 0),__decorate([e.serialize()],n.prototype,"usePhysicalLightFalloff",void 0),__decorate([e.serialize()],n.prototype,"useRadianceOverAlpha",void 0),__decorate([e.serialize()],n.prototype,"useParallax",void 0),__decorate([e.serialize()],n.prototype,"useParallaxOcclusion",void 0),__decorate([e.serialize()],n.prototype,"parallaxScaleBias",void 0),__decorate([e.serialize()],n.prototype,"disableLighting",void 0),__decorate([e.serialize()],n.prototype,"maxSimultaneousLights",void 0),__decorate([e.serialize()],n.prototype,"invertNormalMapX",void 0),__decorate([e.serialize()],n.prototype,"invertNormalMapY",void 0),__decorate([e.serialize()],n.prototype,"twoSidedLighting",void 0),__decorate([e.serialize()],n.prototype,"useLogarithmicDepth",null),n})(e.Material);e.LegacyPBRMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.legacyPbrVertexShader="precision highp float;\n#include<__decl__legacyPbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#ifdef BUMP\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\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\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#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \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#ifdef MICROSURFACEMAP\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#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\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}",
  98838. BABYLON.Effect.ShadersStore.legacyPbrPixelShader="#if defined(BUMP)|| !defined(NORMAL)\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__legacyPbrFragment>\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\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#ifdef CAMERACOLORGRADING\n#include<legacyColorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<legacyColorCurvesDefinition>\n#endif\n\n#include<shadowsFragmentFunctions>\n#include<legacyPbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<legacyColorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<legacyColorCurves>\n#endif\n#include<legacyPbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV+uvOffset);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\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#ifdef OVERLOADEDVALUES\nambientOcclusionColor.rgb=mix(ambientOcclusionColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a*vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#else\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#endif\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef METALLICMAP\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.rgb;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo.rgb=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#else\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface=microSurfaceTexel.r;\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<legacyPbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\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 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\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#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=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=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=lightDiffuseContribution*surfaceAlbedoContribution;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=(lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=(shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution;\n#endif\n#else\nvec3 finalDiffuse=lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor;\n#endif\n#endif\n#endif\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution+=vAmbientColor;\nshadowedOnlyLightDiffuseContribution*=surfaceAlbedo.rgb;\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution,0.0);\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\nfinalDiffuse=(finalDiffuse*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance)*ambientOcclusionColor;\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\nvec4 finalColor=vec4(finalDiffuse+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#ifdef EMISSIVEASILLUMINATION\nfinalColor.rgb+=(surfaceEmissiveColor*vLightingIntensity.y);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}",BABYLON.Effect.IncludesShadersStore.legacyPbrFragmentDeclaration="uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\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#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\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;\n#ifdef REFRACTIONMAP_3D\n#else\nuniform mat4 refractionMatrix;\n#endif\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#endif",BABYLON.Effect.IncludesShadersStore.legacyPbrFunctions="\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\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/(kPi*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 specularColor,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); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \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 diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\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{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif",BABYLON.Effect.IncludesShadersStore.legacyPbrLightFunctions="\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.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\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>=lightAngle)\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 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=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*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 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=max(0.00000000001,dot(vNormal,directionToLightCenterW));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*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 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=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}",BABYLON.Effect.IncludesShadersStore.legacyPbrLightFunctionsCall="#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\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,roughness,NdotV,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,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,specularEnvironmentR90,NdotL);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nnotShadowLevel=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nnotShadowLevel=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,0.0);\n#endif\n#else\n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nnotShadowLevel=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,0.0);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nnotShadowLevel=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,0.0);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\nlightDiffuseContribution+=lightmapColor*notShadowLevel;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nlightSpecularContribution+=info.specular*notShadowLevel*lightmapColor;\n#endif\n#endif\n#else\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif\n#endif",
  98839. BABYLON.Effect.IncludesShadersStore.legacyPbrUboDeclaration="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 vec2 vMicrosurfaceTextureLods;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform vec4 opacityParts;\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\nuniform vec4 vOverloadedShadowIntensity;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};",BABYLON.Effect.IncludesShadersStore.legacyPbrVertexDeclaration="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#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \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",BABYLON.Effect.IncludesShadersStore.legacyColorCurves="const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}",BABYLON.Effect.IncludesShadersStore.legacyColorCurvesDefinition="uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;",BABYLON.Effect.IncludesShadersStore.legacyColorGrading="vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}",BABYLON.Effect.IncludesShadersStore.legacyColorGradingDefinition="uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;",(function(e,i){e&&e.BABYLON||( true?module.exports=i():"function"==typeof define&&define.amd?define([],i):"object"==typeof exports?exports.BJSMaterials=i():e.BABYLON=i())})(this,(function(){return BABYLON}));
  98840. /***/ }),
  98841. /* 22 */
  98842. /***/ (function(module, exports, __webpack_require__) {
  98843. "use strict";
  98844. Object.defineProperty(exports, "__esModule", { value: true });
  98845. var defaultViewer_1 = __webpack_require__(23);
  98846. var mappers_1 = __webpack_require__(4);
  98847. function InitTags(selector) {
  98848. if (selector === void 0) { selector = 'babylon'; }
  98849. var elements = document.querySelectorAll(selector);
  98850. for (var i = 0; i < elements.length; ++i) {
  98851. var element = elements.item(i);
  98852. var configMapper = mappers_1.mapperManager.getMapper('dom');
  98853. var config = configMapper.map(element);
  98854. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  98855. }
  98856. }
  98857. exports.InitTags = InitTags;
  98858. /***/ }),
  98859. /* 23 */
  98860. /***/ (function(module, exports, __webpack_require__) {
  98861. "use strict";
  98862. var __extends = (this && this.__extends) || (function () {
  98863. var extendStatics = Object.setPrototypeOf ||
  98864. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  98865. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  98866. return function (d, b) {
  98867. extendStatics(d, b);
  98868. function __() { this.constructor = d; }
  98869. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  98870. };
  98871. })();
  98872. Object.defineProperty(exports, "__esModule", { value: true });
  98873. var viewer_1 = __webpack_require__(2);
  98874. var babylonjs_1 = __webpack_require__(0);
  98875. var BABYLON = __webpack_require__(0);
  98876. window['BABYLON'] = BABYLON;
  98877. var DefaultViewer = (function (_super) {
  98878. __extends(DefaultViewer, _super);
  98879. function DefaultViewer() {
  98880. return _super !== null && _super.apply(this, arguments) || this;
  98881. }
  98882. DefaultViewer.prototype.initScene = function () {
  98883. var _this = this;
  98884. return _super.prototype.initScene.call(this).then(function () {
  98885. _this.extendClassWithConfig(_this.scene, _this.configuration.scene);
  98886. return _this.scene;
  98887. });
  98888. };
  98889. DefaultViewer.prototype.onTemplatesLoaded = function () {
  98890. this.showLoadingScreen();
  98891. var viewerElement = this.templateManager.getTemplate('viewer');
  98892. var navbar = this.templateManager.getTemplate('navBar');
  98893. var nextHeight = '0px';
  98894. viewerElement.parent.addEventListener('pointerover', function () {
  98895. var currentHeight = navbar.parent.clientHeight + 'px';
  98896. navbar.parent.style.bottom = nextHeight;
  98897. nextHeight = '-' + currentHeight;
  98898. console.log(nextHeight, currentHeight);
  98899. });
  98900. viewerElement.parent.addEventListener('pointerout', function () {
  98901. navbar.parent.style.bottom = nextHeight;
  98902. nextHeight = '0px';
  98903. });
  98904. this.registerFullscreenMode();
  98905. return _super.prototype.onTemplatesLoaded.call(this);
  98906. };
  98907. DefaultViewer.prototype.registerFullscreenMode = function () {
  98908. var isFullscreen = false;
  98909. var navbar = this.templateManager.getTemplate('navBar');
  98910. var viewerElement = this.templateManager.getTemplate('viewer').parent;
  98911. navbar.onEventTriggered.add(function (data) {
  98912. switch (data.event.type) {
  98913. case 'pointerdown':
  98914. var event_1 = data.event;
  98915. if (event_1.button === 0) {
  98916. if (data.selector === '#fullscreen-button') {
  98917. if (!isFullscreen) {
  98918. var requestFullScreen = viewerElement.requestFullscreen || viewerElement.webkitRequestFullscreen;
  98919. requestFullScreen.call(viewerElement);
  98920. }
  98921. else {
  98922. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen;
  98923. exitFullscreen.call(document);
  98924. }
  98925. isFullscreen = !isFullscreen;
  98926. }
  98927. }
  98928. break;
  98929. }
  98930. });
  98931. };
  98932. DefaultViewer.prototype.prepareContainerElement = function () {
  98933. this.containerElement.style.position = 'relative';
  98934. this.containerElement.style.display = 'flex';
  98935. };
  98936. DefaultViewer.prototype.loadModel = function (model) {
  98937. if (model === void 0) { model = this.configuration.model; }
  98938. this.showLoadingScreen();
  98939. return _super.prototype.loadModel.call(this, model, true);
  98940. };
  98941. DefaultViewer.prototype.onModelLoaded = function (meshes) {
  98942. this.setModelMetaData();
  98943. this.hideLoadingScreen();
  98944. this.scene.createDefaultCameraOrLight(true, true, true);
  98945. this.camera = this.scene.activeCamera;
  98946. meshes[0].rotation.y += Math.PI;
  98947. this.setupCamera(meshes);
  98948. this.setupLights(meshes);
  98949. return this.initEnvironment();
  98950. };
  98951. DefaultViewer.prototype.setModelMetaData = function () {
  98952. var navbar = this.templateManager.getTemplate('navBar');
  98953. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  98954. if (metadataContainer && typeof this.configuration.model === 'object') {
  98955. if (this.configuration.model.title) {
  98956. var element = metadataContainer.querySelector('span.model-title');
  98957. if (element) {
  98958. element.innerHTML = this.configuration.model.title;
  98959. }
  98960. }
  98961. if (this.configuration.model.subtitle) {
  98962. var element = metadataContainer.querySelector('span.model-subtitle');
  98963. if (element) {
  98964. element.innerHTML = this.configuration.model.subtitle;
  98965. }
  98966. }
  98967. if (this.configuration.model.thumbnail) {
  98968. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + this.configuration.model.thumbnail + "')";
  98969. }
  98970. }
  98971. };
  98972. DefaultViewer.prototype.initEnvironment = function () {
  98973. if (this.configuration.skybox) {
  98974. var texture = void 0;
  98975. if (this.configuration.skybox.cubeTexture) {
  98976. if (typeof this.configuration.skybox.cubeTexture.url === 'string') {
  98977. texture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(this.configuration.skybox.cubeTexture.url, this.scene);
  98978. }
  98979. else {
  98980. texture = babylonjs_1.CubeTexture.CreateFromImages(this.configuration.skybox.cubeTexture.url, this.scene, this.configuration.skybox.cubeTexture.noMipMap);
  98981. }
  98982. }
  98983. if (texture) {
  98984. this.extendClassWithConfig(texture, this.configuration.skybox.cubeTexture);
  98985. var scale = this.configuration.skybox.scale || (this.scene.activeCamera.maxZ - this.scene.activeCamera.minZ) / 2;
  98986. var box = this.scene.createDefaultSkybox(texture, this.configuration.skybox.pbr, scale, this.configuration.skybox.blur);
  98987. if (this.configuration.skybox.material && this.configuration.skybox.material.imageProcessingConfiguration) {
  98988. box.material.imageProcessingConfiguration = new babylonjs_1.ImageProcessingConfiguration();
  98989. }
  98990. this.extendClassWithConfig(box, this.configuration.skybox);
  98991. }
  98992. }
  98993. if (this.configuration.ground) {
  98994. var groundConfig = (typeof this.configuration.ground === 'boolean') ? {} : this.configuration.ground;
  98995. var ground = babylonjs_1.Mesh.CreateGround('ground', groundConfig.size || 1000, groundConfig.size || 1000, 8, this.scene);
  98996. if (this.configuration.ground === true || groundConfig.shadowOnly) {
  98997. ground.material = new babylonjs_1.ShadowOnlyMaterial('groundmat', this.scene);
  98998. }
  98999. else {
  99000. ground.material = new babylonjs_1.StandardMaterial('groundmat', this.scene);
  99001. }
  99002. if (this.configuration.ground === true) {
  99003. ground.receiveShadows = true;
  99004. ground.material.alpha = 0.4;
  99005. }
  99006. this.extendClassWithConfig(ground, groundConfig);
  99007. }
  99008. return Promise.resolve(this.scene);
  99009. };
  99010. DefaultViewer.prototype.showLoadingScreen = function () {
  99011. var _this = this;
  99012. return this.templateManager.getTemplate('loadingScreen').show((function (template) {
  99013. var canvasRect = _this.containerElement.getBoundingClientRect();
  99014. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  99015. template.parent.style.display = 'flex';
  99016. template.parent.style.width = canvasRect.width + "px";
  99017. template.parent.style.height = canvasRect.height + "px";
  99018. template.parent.style.opacity = "1";
  99019. template.parent.style.backgroundColor = "black";
  99020. return Promise.resolve(template);
  99021. }));
  99022. };
  99023. DefaultViewer.prototype.hideLoadingScreen = function () {
  99024. return this.templateManager.getTemplate('loadingScreen').hide((function (template) {
  99025. template.parent.style.opacity = "0";
  99026. var onTransitionEnd = function () {
  99027. template.parent.removeEventListener("transitionend", onTransitionEnd);
  99028. template.parent.style.display = 'none';
  99029. };
  99030. template.parent.addEventListener("transitionend", onTransitionEnd);
  99031. return Promise.resolve(template);
  99032. }));
  99033. };
  99034. DefaultViewer.prototype.setupLights = function (focusMeshes) {
  99035. var _this = this;
  99036. if (focusMeshes === void 0) { focusMeshes = []; }
  99037. var sceneConfig = this.configuration.scene || { defaultLight: true };
  99038. if (!sceneConfig.defaultLight && (this.configuration.lights && this.configuration.lights.length)) {
  99039. this.scene.lights.forEach(function (l) {
  99040. l.dispose();
  99041. });
  99042. this.configuration.lights.forEach(function (lightConfig, idx) {
  99043. lightConfig.name = lightConfig.name || 'light-' + idx;
  99044. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  99045. var light = constructor();
  99046. if (light.isEnabled() !== !lightConfig.disabled) {
  99047. light.setEnabled(!lightConfig.disabled);
  99048. }
  99049. _this.extendClassWithConfig(light, lightConfig);
  99050. if (light instanceof babylonjs_1.ShadowLight) {
  99051. if (lightConfig.shadowEnabled) {
  99052. var shadowGenerator = new BABYLON.ShadowGenerator(512, light);
  99053. _this.extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  99054. for (var index = 0; index < focusMeshes.length; index++) {
  99055. shadowGenerator.getShadowMap().renderList.push(focusMeshes[index]);
  99056. }
  99057. }
  99058. }
  99059. });
  99060. }
  99061. };
  99062. DefaultViewer.prototype.setupCamera = function (focusMeshes) {
  99063. var _this = this;
  99064. if (focusMeshes === void 0) { focusMeshes = []; }
  99065. var sceneConfig = this.configuration.scene || { autoRotate: false, defaultCamera: true };
  99066. if (sceneConfig.defaultCamera) {
  99067. return;
  99068. }
  99069. var cameraConfig = this.configuration.camera || {};
  99070. if (cameraConfig.position) {
  99071. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  99072. }
  99073. if (cameraConfig.rotation) {
  99074. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  99075. }
  99076. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  99077. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  99078. if (cameraConfig.behaviors) {
  99079. cameraConfig.behaviors.forEach(function (behaviorConfig) {
  99080. _this.setCameraBehavior(behaviorConfig, focusMeshes);
  99081. });
  99082. }
  99083. ;
  99084. if (sceneConfig.autoRotate) {
  99085. this.camera.useAutoRotationBehavior = true;
  99086. }
  99087. };
  99088. DefaultViewer.prototype.setCameraBehavior = function (behaviorConfig, payload) {
  99089. var behavior;
  99090. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  99091. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  99092. switch (type) {
  99093. case 0:
  99094. behavior = new babylonjs_1.AutoRotationBehavior();
  99095. break;
  99096. case 1:
  99097. behavior = new babylonjs_1.BouncingBehavior();
  99098. break;
  99099. case 2:
  99100. behavior = new babylonjs_1.FramingBehavior();
  99101. break;
  99102. default:
  99103. behavior = null;
  99104. break;
  99105. }
  99106. if (behavior) {
  99107. if (typeof behaviorConfig === "object") {
  99108. this.extendClassWithConfig(behavior, behaviorConfig);
  99109. }
  99110. this.camera.addBehavior(behavior);
  99111. }
  99112. switch (type) {
  99113. case 0:
  99114. break;
  99115. case 1:
  99116. break;
  99117. case 2:
  99118. if (config.zoomOnBoundingInfo) {
  99119. var meshes = payload;
  99120. var bounding = meshes[0].getHierarchyBoundingVectors();
  99121. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  99122. }
  99123. break;
  99124. }
  99125. };
  99126. DefaultViewer.prototype.extendClassWithConfig = function (object, config) {
  99127. var _this = this;
  99128. Object.keys(config).forEach(function (key) {
  99129. if (key in object && typeof object[key] !== 'function') {
  99130. if (typeof object[key] === 'function')
  99131. return;
  99132. if (typeof object[key] === 'object') {
  99133. _this.extendClassWithConfig(object[key], config[key]);
  99134. }
  99135. else {
  99136. object[key] = config[key];
  99137. }
  99138. }
  99139. });
  99140. };
  99141. return DefaultViewer;
  99142. }(viewer_1.AbstractViewer));
  99143. exports.DefaultViewer = DefaultViewer;
  99144. /***/ }),
  99145. /* 24 */
  99146. /***/ (function(module, exports, __webpack_require__) {
  99147. /* WEBPACK VAR INJECTION */(function(process, global) {var require;/*!
  99148. * @overview es6-promise - a tiny implementation of Promises/A+.
  99149. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  99150. * @license Licensed under MIT license
  99151. * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
  99152. * @version 4.1.1
  99153. */
  99154. (function (global, factory) {
  99155. true ? module.exports = factory() :
  99156. typeof define === 'function' && define.amd ? define(factory) :
  99157. (global.ES6Promise = factory());
  99158. }(this, (function () { 'use strict';
  99159. function objectOrFunction(x) {
  99160. var type = typeof x;
  99161. return x !== null && (type === 'object' || type === 'function');
  99162. }
  99163. function isFunction(x) {
  99164. return typeof x === 'function';
  99165. }
  99166. var _isArray = undefined;
  99167. if (Array.isArray) {
  99168. _isArray = Array.isArray;
  99169. } else {
  99170. _isArray = function (x) {
  99171. return Object.prototype.toString.call(x) === '[object Array]';
  99172. };
  99173. }
  99174. var isArray = _isArray;
  99175. var len = 0;
  99176. var vertxNext = undefined;
  99177. var customSchedulerFn = undefined;
  99178. var asap = function asap(callback, arg) {
  99179. queue[len] = callback;
  99180. queue[len + 1] = arg;
  99181. len += 2;
  99182. if (len === 2) {
  99183. // If len is 2, that means that we need to schedule an async flush.
  99184. // If additional callbacks are queued before the queue is flushed, they
  99185. // will be processed by this flush that we are scheduling.
  99186. if (customSchedulerFn) {
  99187. customSchedulerFn(flush);
  99188. } else {
  99189. scheduleFlush();
  99190. }
  99191. }
  99192. };
  99193. function setScheduler(scheduleFn) {
  99194. customSchedulerFn = scheduleFn;
  99195. }
  99196. function setAsap(asapFn) {
  99197. asap = asapFn;
  99198. }
  99199. var browserWindow = typeof window !== 'undefined' ? window : undefined;
  99200. var browserGlobal = browserWindow || {};
  99201. var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
  99202. var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';
  99203. // test for web worker but not in IE10
  99204. var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
  99205. // node
  99206. function useNextTick() {
  99207. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  99208. // see https://github.com/cujojs/when/issues/410 for details
  99209. return function () {
  99210. return process.nextTick(flush);
  99211. };
  99212. }
  99213. // vertx
  99214. function useVertxTimer() {
  99215. if (typeof vertxNext !== 'undefined') {
  99216. return function () {
  99217. vertxNext(flush);
  99218. };
  99219. }
  99220. return useSetTimeout();
  99221. }
  99222. function useMutationObserver() {
  99223. var iterations = 0;
  99224. var observer = new BrowserMutationObserver(flush);
  99225. var node = document.createTextNode('');
  99226. observer.observe(node, { characterData: true });
  99227. return function () {
  99228. node.data = iterations = ++iterations % 2;
  99229. };
  99230. }
  99231. // web worker
  99232. function useMessageChannel() {
  99233. var channel = new MessageChannel();
  99234. channel.port1.onmessage = flush;
  99235. return function () {
  99236. return channel.port2.postMessage(0);
  99237. };
  99238. }
  99239. function useSetTimeout() {
  99240. // Store setTimeout reference so es6-promise will be unaffected by
  99241. // other code modifying setTimeout (like sinon.useFakeTimers())
  99242. var globalSetTimeout = setTimeout;
  99243. return function () {
  99244. return globalSetTimeout(flush, 1);
  99245. };
  99246. }
  99247. var queue = new Array(1000);
  99248. function flush() {
  99249. for (var i = 0; i < len; i += 2) {
  99250. var callback = queue[i];
  99251. var arg = queue[i + 1];
  99252. callback(arg);
  99253. queue[i] = undefined;
  99254. queue[i + 1] = undefined;
  99255. }
  99256. len = 0;
  99257. }
  99258. function attemptVertx() {
  99259. try {
  99260. var r = require;
  99261. var vertx = __webpack_require__(26);
  99262. vertxNext = vertx.runOnLoop || vertx.runOnContext;
  99263. return useVertxTimer();
  99264. } catch (e) {
  99265. return useSetTimeout();
  99266. }
  99267. }
  99268. var scheduleFlush = undefined;
  99269. // Decide what async method to use to triggering processing of queued callbacks:
  99270. if (isNode) {
  99271. scheduleFlush = useNextTick();
  99272. } else if (BrowserMutationObserver) {
  99273. scheduleFlush = useMutationObserver();
  99274. } else if (isWorker) {
  99275. scheduleFlush = useMessageChannel();
  99276. } else if (browserWindow === undefined && "function" === 'function') {
  99277. scheduleFlush = attemptVertx();
  99278. } else {
  99279. scheduleFlush = useSetTimeout();
  99280. }
  99281. function then(onFulfillment, onRejection) {
  99282. var _arguments = arguments;
  99283. var parent = this;
  99284. var child = new this.constructor(noop);
  99285. if (child[PROMISE_ID] === undefined) {
  99286. makePromise(child);
  99287. }
  99288. var _state = parent._state;
  99289. if (_state) {
  99290. (function () {
  99291. var callback = _arguments[_state - 1];
  99292. asap(function () {
  99293. return invokeCallback(_state, child, callback, parent._result);
  99294. });
  99295. })();
  99296. } else {
  99297. subscribe(parent, child, onFulfillment, onRejection);
  99298. }
  99299. return child;
  99300. }
  99301. /**
  99302. `Promise.resolve` returns a promise that will become resolved with the
  99303. passed `value`. It is shorthand for the following:
  99304. ```javascript
  99305. let promise = new Promise(function(resolve, reject){
  99306. resolve(1);
  99307. });
  99308. promise.then(function(value){
  99309. // value === 1
  99310. });
  99311. ```
  99312. Instead of writing the above, your code now simply becomes the following:
  99313. ```javascript
  99314. let promise = Promise.resolve(1);
  99315. promise.then(function(value){
  99316. // value === 1
  99317. });
  99318. ```
  99319. @method resolve
  99320. @static
  99321. @param {Any} value value that the returned promise will be resolved with
  99322. Useful for tooling.
  99323. @return {Promise} a promise that will become fulfilled with the given
  99324. `value`
  99325. */
  99326. function resolve$1(object) {
  99327. /*jshint validthis:true */
  99328. var Constructor = this;
  99329. if (object && typeof object === 'object' && object.constructor === Constructor) {
  99330. return object;
  99331. }
  99332. var promise = new Constructor(noop);
  99333. resolve(promise, object);
  99334. return promise;
  99335. }
  99336. var PROMISE_ID = Math.random().toString(36).substring(16);
  99337. function noop() {}
  99338. var PENDING = void 0;
  99339. var FULFILLED = 1;
  99340. var REJECTED = 2;
  99341. var GET_THEN_ERROR = new ErrorObject();
  99342. function selfFulfillment() {
  99343. return new TypeError("You cannot resolve a promise with itself");
  99344. }
  99345. function cannotReturnOwn() {
  99346. return new TypeError('A promises callback cannot return that same promise.');
  99347. }
  99348. function getThen(promise) {
  99349. try {
  99350. return promise.then;
  99351. } catch (error) {
  99352. GET_THEN_ERROR.error = error;
  99353. return GET_THEN_ERROR;
  99354. }
  99355. }
  99356. function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
  99357. try {
  99358. then$$1.call(value, fulfillmentHandler, rejectionHandler);
  99359. } catch (e) {
  99360. return e;
  99361. }
  99362. }
  99363. function handleForeignThenable(promise, thenable, then$$1) {
  99364. asap(function (promise) {
  99365. var sealed = false;
  99366. var error = tryThen(then$$1, thenable, function (value) {
  99367. if (sealed) {
  99368. return;
  99369. }
  99370. sealed = true;
  99371. if (thenable !== value) {
  99372. resolve(promise, value);
  99373. } else {
  99374. fulfill(promise, value);
  99375. }
  99376. }, function (reason) {
  99377. if (sealed) {
  99378. return;
  99379. }
  99380. sealed = true;
  99381. reject(promise, reason);
  99382. }, 'Settle: ' + (promise._label || ' unknown promise'));
  99383. if (!sealed && error) {
  99384. sealed = true;
  99385. reject(promise, error);
  99386. }
  99387. }, promise);
  99388. }
  99389. function handleOwnThenable(promise, thenable) {
  99390. if (thenable._state === FULFILLED) {
  99391. fulfill(promise, thenable._result);
  99392. } else if (thenable._state === REJECTED) {
  99393. reject(promise, thenable._result);
  99394. } else {
  99395. subscribe(thenable, undefined, function (value) {
  99396. return resolve(promise, value);
  99397. }, function (reason) {
  99398. return reject(promise, reason);
  99399. });
  99400. }
  99401. }
  99402. function handleMaybeThenable(promise, maybeThenable, then$$1) {
  99403. if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
  99404. handleOwnThenable(promise, maybeThenable);
  99405. } else {
  99406. if (then$$1 === GET_THEN_ERROR) {
  99407. reject(promise, GET_THEN_ERROR.error);
  99408. GET_THEN_ERROR.error = null;
  99409. } else if (then$$1 === undefined) {
  99410. fulfill(promise, maybeThenable);
  99411. } else if (isFunction(then$$1)) {
  99412. handleForeignThenable(promise, maybeThenable, then$$1);
  99413. } else {
  99414. fulfill(promise, maybeThenable);
  99415. }
  99416. }
  99417. }
  99418. function resolve(promise, value) {
  99419. if (promise === value) {
  99420. reject(promise, selfFulfillment());
  99421. } else if (objectOrFunction(value)) {
  99422. handleMaybeThenable(promise, value, getThen(value));
  99423. } else {
  99424. fulfill(promise, value);
  99425. }
  99426. }
  99427. function publishRejection(promise) {
  99428. if (promise._onerror) {
  99429. promise._onerror(promise._result);
  99430. }
  99431. publish(promise);
  99432. }
  99433. function fulfill(promise, value) {
  99434. if (promise._state !== PENDING) {
  99435. return;
  99436. }
  99437. promise._result = value;
  99438. promise._state = FULFILLED;
  99439. if (promise._subscribers.length !== 0) {
  99440. asap(publish, promise);
  99441. }
  99442. }
  99443. function reject(promise, reason) {
  99444. if (promise._state !== PENDING) {
  99445. return;
  99446. }
  99447. promise._state = REJECTED;
  99448. promise._result = reason;
  99449. asap(publishRejection, promise);
  99450. }
  99451. function subscribe(parent, child, onFulfillment, onRejection) {
  99452. var _subscribers = parent._subscribers;
  99453. var length = _subscribers.length;
  99454. parent._onerror = null;
  99455. _subscribers[length] = child;
  99456. _subscribers[length + FULFILLED] = onFulfillment;
  99457. _subscribers[length + REJECTED] = onRejection;
  99458. if (length === 0 && parent._state) {
  99459. asap(publish, parent);
  99460. }
  99461. }
  99462. function publish(promise) {
  99463. var subscribers = promise._subscribers;
  99464. var settled = promise._state;
  99465. if (subscribers.length === 0) {
  99466. return;
  99467. }
  99468. var child = undefined,
  99469. callback = undefined,
  99470. detail = promise._result;
  99471. for (var i = 0; i < subscribers.length; i += 3) {
  99472. child = subscribers[i];
  99473. callback = subscribers[i + settled];
  99474. if (child) {
  99475. invokeCallback(settled, child, callback, detail);
  99476. } else {
  99477. callback(detail);
  99478. }
  99479. }
  99480. promise._subscribers.length = 0;
  99481. }
  99482. function ErrorObject() {
  99483. this.error = null;
  99484. }
  99485. var TRY_CATCH_ERROR = new ErrorObject();
  99486. function tryCatch(callback, detail) {
  99487. try {
  99488. return callback(detail);
  99489. } catch (e) {
  99490. TRY_CATCH_ERROR.error = e;
  99491. return TRY_CATCH_ERROR;
  99492. }
  99493. }
  99494. function invokeCallback(settled, promise, callback, detail) {
  99495. var hasCallback = isFunction(callback),
  99496. value = undefined,
  99497. error = undefined,
  99498. succeeded = undefined,
  99499. failed = undefined;
  99500. if (hasCallback) {
  99501. value = tryCatch(callback, detail);
  99502. if (value === TRY_CATCH_ERROR) {
  99503. failed = true;
  99504. error = value.error;
  99505. value.error = null;
  99506. } else {
  99507. succeeded = true;
  99508. }
  99509. if (promise === value) {
  99510. reject(promise, cannotReturnOwn());
  99511. return;
  99512. }
  99513. } else {
  99514. value = detail;
  99515. succeeded = true;
  99516. }
  99517. if (promise._state !== PENDING) {
  99518. // noop
  99519. } else if (hasCallback && succeeded) {
  99520. resolve(promise, value);
  99521. } else if (failed) {
  99522. reject(promise, error);
  99523. } else if (settled === FULFILLED) {
  99524. fulfill(promise, value);
  99525. } else if (settled === REJECTED) {
  99526. reject(promise, value);
  99527. }
  99528. }
  99529. function initializePromise(promise, resolver) {
  99530. try {
  99531. resolver(function resolvePromise(value) {
  99532. resolve(promise, value);
  99533. }, function rejectPromise(reason) {
  99534. reject(promise, reason);
  99535. });
  99536. } catch (e) {
  99537. reject(promise, e);
  99538. }
  99539. }
  99540. var id = 0;
  99541. function nextId() {
  99542. return id++;
  99543. }
  99544. function makePromise(promise) {
  99545. promise[PROMISE_ID] = id++;
  99546. promise._state = undefined;
  99547. promise._result = undefined;
  99548. promise._subscribers = [];
  99549. }
  99550. function Enumerator$1(Constructor, input) {
  99551. this._instanceConstructor = Constructor;
  99552. this.promise = new Constructor(noop);
  99553. if (!this.promise[PROMISE_ID]) {
  99554. makePromise(this.promise);
  99555. }
  99556. if (isArray(input)) {
  99557. this.length = input.length;
  99558. this._remaining = input.length;
  99559. this._result = new Array(this.length);
  99560. if (this.length === 0) {
  99561. fulfill(this.promise, this._result);
  99562. } else {
  99563. this.length = this.length || 0;
  99564. this._enumerate(input);
  99565. if (this._remaining === 0) {
  99566. fulfill(this.promise, this._result);
  99567. }
  99568. }
  99569. } else {
  99570. reject(this.promise, validationError());
  99571. }
  99572. }
  99573. function validationError() {
  99574. return new Error('Array Methods must be provided an Array');
  99575. }
  99576. Enumerator$1.prototype._enumerate = function (input) {
  99577. for (var i = 0; this._state === PENDING && i < input.length; i++) {
  99578. this._eachEntry(input[i], i);
  99579. }
  99580. };
  99581. Enumerator$1.prototype._eachEntry = function (entry, i) {
  99582. var c = this._instanceConstructor;
  99583. var resolve$$1 = c.resolve;
  99584. if (resolve$$1 === resolve$1) {
  99585. var _then = getThen(entry);
  99586. if (_then === then && entry._state !== PENDING) {
  99587. this._settledAt(entry._state, i, entry._result);
  99588. } else if (typeof _then !== 'function') {
  99589. this._remaining--;
  99590. this._result[i] = entry;
  99591. } else if (c === Promise$2) {
  99592. var promise = new c(noop);
  99593. handleMaybeThenable(promise, entry, _then);
  99594. this._willSettleAt(promise, i);
  99595. } else {
  99596. this._willSettleAt(new c(function (resolve$$1) {
  99597. return resolve$$1(entry);
  99598. }), i);
  99599. }
  99600. } else {
  99601. this._willSettleAt(resolve$$1(entry), i);
  99602. }
  99603. };
  99604. Enumerator$1.prototype._settledAt = function (state, i, value) {
  99605. var promise = this.promise;
  99606. if (promise._state === PENDING) {
  99607. this._remaining--;
  99608. if (state === REJECTED) {
  99609. reject(promise, value);
  99610. } else {
  99611. this._result[i] = value;
  99612. }
  99613. }
  99614. if (this._remaining === 0) {
  99615. fulfill(promise, this._result);
  99616. }
  99617. };
  99618. Enumerator$1.prototype._willSettleAt = function (promise, i) {
  99619. var enumerator = this;
  99620. subscribe(promise, undefined, function (value) {
  99621. return enumerator._settledAt(FULFILLED, i, value);
  99622. }, function (reason) {
  99623. return enumerator._settledAt(REJECTED, i, reason);
  99624. });
  99625. };
  99626. /**
  99627. `Promise.all` accepts an array of promises, and returns a new promise which
  99628. is fulfilled with an array of fulfillment values for the passed promises, or
  99629. rejected with the reason of the first passed promise to be rejected. It casts all
  99630. elements of the passed iterable to promises as it runs this algorithm.
  99631. Example:
  99632. ```javascript
  99633. let promise1 = resolve(1);
  99634. let promise2 = resolve(2);
  99635. let promise3 = resolve(3);
  99636. let promises = [ promise1, promise2, promise3 ];
  99637. Promise.all(promises).then(function(array){
  99638. // The array here would be [ 1, 2, 3 ];
  99639. });
  99640. ```
  99641. If any of the `promises` given to `all` are rejected, the first promise
  99642. that is rejected will be given as an argument to the returned promises's
  99643. rejection handler. For example:
  99644. Example:
  99645. ```javascript
  99646. let promise1 = resolve(1);
  99647. let promise2 = reject(new Error("2"));
  99648. let promise3 = reject(new Error("3"));
  99649. let promises = [ promise1, promise2, promise3 ];
  99650. Promise.all(promises).then(function(array){
  99651. // Code here never runs because there are rejected promises!
  99652. }, function(error) {
  99653. // error.message === "2"
  99654. });
  99655. ```
  99656. @method all
  99657. @static
  99658. @param {Array} entries array of promises
  99659. @param {String} label optional string for labeling the promise.
  99660. Useful for tooling.
  99661. @return {Promise} promise that is fulfilled when all `promises` have been
  99662. fulfilled, or rejected if any of them become rejected.
  99663. @static
  99664. */
  99665. function all$1(entries) {
  99666. return new Enumerator$1(this, entries).promise;
  99667. }
  99668. /**
  99669. `Promise.race` returns a new promise which is settled in the same way as the
  99670. first passed promise to settle.
  99671. Example:
  99672. ```javascript
  99673. let promise1 = new Promise(function(resolve, reject){
  99674. setTimeout(function(){
  99675. resolve('promise 1');
  99676. }, 200);
  99677. });
  99678. let promise2 = new Promise(function(resolve, reject){
  99679. setTimeout(function(){
  99680. resolve('promise 2');
  99681. }, 100);
  99682. });
  99683. Promise.race([promise1, promise2]).then(function(result){
  99684. // result === 'promise 2' because it was resolved before promise1
  99685. // was resolved.
  99686. });
  99687. ```
  99688. `Promise.race` is deterministic in that only the state of the first
  99689. settled promise matters. For example, even if other promises given to the
  99690. `promises` array argument are resolved, but the first settled promise has
  99691. become rejected before the other promises became fulfilled, the returned
  99692. promise will become rejected:
  99693. ```javascript
  99694. let promise1 = new Promise(function(resolve, reject){
  99695. setTimeout(function(){
  99696. resolve('promise 1');
  99697. }, 200);
  99698. });
  99699. let promise2 = new Promise(function(resolve, reject){
  99700. setTimeout(function(){
  99701. reject(new Error('promise 2'));
  99702. }, 100);
  99703. });
  99704. Promise.race([promise1, promise2]).then(function(result){
  99705. // Code here never runs
  99706. }, function(reason){
  99707. // reason.message === 'promise 2' because promise 2 became rejected before
  99708. // promise 1 became fulfilled
  99709. });
  99710. ```
  99711. An example real-world use case is implementing timeouts:
  99712. ```javascript
  99713. Promise.race([ajax('foo.json'), timeout(5000)])
  99714. ```
  99715. @method race
  99716. @static
  99717. @param {Array} promises array of promises to observe
  99718. Useful for tooling.
  99719. @return {Promise} a promise which settles in the same way as the first passed
  99720. promise to settle.
  99721. */
  99722. function race$1(entries) {
  99723. /*jshint validthis:true */
  99724. var Constructor = this;
  99725. if (!isArray(entries)) {
  99726. return new Constructor(function (_, reject) {
  99727. return reject(new TypeError('You must pass an array to race.'));
  99728. });
  99729. } else {
  99730. return new Constructor(function (resolve, reject) {
  99731. var length = entries.length;
  99732. for (var i = 0; i < length; i++) {
  99733. Constructor.resolve(entries[i]).then(resolve, reject);
  99734. }
  99735. });
  99736. }
  99737. }
  99738. /**
  99739. `Promise.reject` returns a promise rejected with the passed `reason`.
  99740. It is shorthand for the following:
  99741. ```javascript
  99742. let promise = new Promise(function(resolve, reject){
  99743. reject(new Error('WHOOPS'));
  99744. });
  99745. promise.then(function(value){
  99746. // Code here doesn't run because the promise is rejected!
  99747. }, function(reason){
  99748. // reason.message === 'WHOOPS'
  99749. });
  99750. ```
  99751. Instead of writing the above, your code now simply becomes the following:
  99752. ```javascript
  99753. let promise = Promise.reject(new Error('WHOOPS'));
  99754. promise.then(function(value){
  99755. // Code here doesn't run because the promise is rejected!
  99756. }, function(reason){
  99757. // reason.message === 'WHOOPS'
  99758. });
  99759. ```
  99760. @method reject
  99761. @static
  99762. @param {Any} reason value that the returned promise will be rejected with.
  99763. Useful for tooling.
  99764. @return {Promise} a promise rejected with the given `reason`.
  99765. */
  99766. function reject$1(reason) {
  99767. /*jshint validthis:true */
  99768. var Constructor = this;
  99769. var promise = new Constructor(noop);
  99770. reject(promise, reason);
  99771. return promise;
  99772. }
  99773. function needsResolver() {
  99774. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  99775. }
  99776. function needsNew() {
  99777. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  99778. }
  99779. /**
  99780. Promise objects represent the eventual result of an asynchronous operation. The
  99781. primary way of interacting with a promise is through its `then` method, which
  99782. registers callbacks to receive either a promise's eventual value or the reason
  99783. why the promise cannot be fulfilled.
  99784. Terminology
  99785. -----------
  99786. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  99787. - `thenable` is an object or function that defines a `then` method.
  99788. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  99789. - `exception` is a value that is thrown using the throw statement.
  99790. - `reason` is a value that indicates why a promise was rejected.
  99791. - `settled` the final resting state of a promise, fulfilled or rejected.
  99792. A promise can be in one of three states: pending, fulfilled, or rejected.
  99793. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  99794. state. Promises that are rejected have a rejection reason and are in the
  99795. rejected state. A fulfillment value is never a thenable.
  99796. Promises can also be said to *resolve* a value. If this value is also a
  99797. promise, then the original promise's settled state will match the value's
  99798. settled state. So a promise that *resolves* a promise that rejects will
  99799. itself reject, and a promise that *resolves* a promise that fulfills will
  99800. itself fulfill.
  99801. Basic Usage:
  99802. ------------
  99803. ```js
  99804. let promise = new Promise(function(resolve, reject) {
  99805. // on success
  99806. resolve(value);
  99807. // on failure
  99808. reject(reason);
  99809. });
  99810. promise.then(function(value) {
  99811. // on fulfillment
  99812. }, function(reason) {
  99813. // on rejection
  99814. });
  99815. ```
  99816. Advanced Usage:
  99817. ---------------
  99818. Promises shine when abstracting away asynchronous interactions such as
  99819. `XMLHttpRequest`s.
  99820. ```js
  99821. function getJSON(url) {
  99822. return new Promise(function(resolve, reject){
  99823. let xhr = new XMLHttpRequest();
  99824. xhr.open('GET', url);
  99825. xhr.onreadystatechange = handler;
  99826. xhr.responseType = 'json';
  99827. xhr.setRequestHeader('Accept', 'application/json');
  99828. xhr.send();
  99829. function handler() {
  99830. if (this.readyState === this.DONE) {
  99831. if (this.status === 200) {
  99832. resolve(this.response);
  99833. } else {
  99834. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  99835. }
  99836. }
  99837. };
  99838. });
  99839. }
  99840. getJSON('/posts.json').then(function(json) {
  99841. // on fulfillment
  99842. }, function(reason) {
  99843. // on rejection
  99844. });
  99845. ```
  99846. Unlike callbacks, promises are great composable primitives.
  99847. ```js
  99848. Promise.all([
  99849. getJSON('/posts'),
  99850. getJSON('/comments')
  99851. ]).then(function(values){
  99852. values[0] // => postsJSON
  99853. values[1] // => commentsJSON
  99854. return values;
  99855. });
  99856. ```
  99857. @class Promise
  99858. @param {function} resolver
  99859. Useful for tooling.
  99860. @constructor
  99861. */
  99862. function Promise$2(resolver) {
  99863. this[PROMISE_ID] = nextId();
  99864. this._result = this._state = undefined;
  99865. this._subscribers = [];
  99866. if (noop !== resolver) {
  99867. typeof resolver !== 'function' && needsResolver();
  99868. this instanceof Promise$2 ? initializePromise(this, resolver) : needsNew();
  99869. }
  99870. }
  99871. Promise$2.all = all$1;
  99872. Promise$2.race = race$1;
  99873. Promise$2.resolve = resolve$1;
  99874. Promise$2.reject = reject$1;
  99875. Promise$2._setScheduler = setScheduler;
  99876. Promise$2._setAsap = setAsap;
  99877. Promise$2._asap = asap;
  99878. Promise$2.prototype = {
  99879. constructor: Promise$2,
  99880. /**
  99881. The primary way of interacting with a promise is through its `then` method,
  99882. which registers callbacks to receive either a promise's eventual value or the
  99883. reason why the promise cannot be fulfilled.
  99884. ```js
  99885. findUser().then(function(user){
  99886. // user is available
  99887. }, function(reason){
  99888. // user is unavailable, and you are given the reason why
  99889. });
  99890. ```
  99891. Chaining
  99892. --------
  99893. The return value of `then` is itself a promise. This second, 'downstream'
  99894. promise is resolved with the return value of the first promise's fulfillment
  99895. or rejection handler, or rejected if the handler throws an exception.
  99896. ```js
  99897. findUser().then(function (user) {
  99898. return user.name;
  99899. }, function (reason) {
  99900. return 'default name';
  99901. }).then(function (userName) {
  99902. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  99903. // will be `'default name'`
  99904. });
  99905. findUser().then(function (user) {
  99906. throw new Error('Found user, but still unhappy');
  99907. }, function (reason) {
  99908. throw new Error('`findUser` rejected and we're unhappy');
  99909. }).then(function (value) {
  99910. // never reached
  99911. }, function (reason) {
  99912. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  99913. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  99914. });
  99915. ```
  99916. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  99917. ```js
  99918. findUser().then(function (user) {
  99919. throw new PedagogicalException('Upstream error');
  99920. }).then(function (value) {
  99921. // never reached
  99922. }).then(function (value) {
  99923. // never reached
  99924. }, function (reason) {
  99925. // The `PedgagocialException` is propagated all the way down to here
  99926. });
  99927. ```
  99928. Assimilation
  99929. ------------
  99930. Sometimes the value you want to propagate to a downstream promise can only be
  99931. retrieved asynchronously. This can be achieved by returning a promise in the
  99932. fulfillment or rejection handler. The downstream promise will then be pending
  99933. until the returned promise is settled. This is called *assimilation*.
  99934. ```js
  99935. findUser().then(function (user) {
  99936. return findCommentsByAuthor(user);
  99937. }).then(function (comments) {
  99938. // The user's comments are now available
  99939. });
  99940. ```
  99941. If the assimliated promise rejects, then the downstream promise will also reject.
  99942. ```js
  99943. findUser().then(function (user) {
  99944. return findCommentsByAuthor(user);
  99945. }).then(function (comments) {
  99946. // If `findCommentsByAuthor` fulfills, we'll have the value here
  99947. }, function (reason) {
  99948. // If `findCommentsByAuthor` rejects, we'll have the reason here
  99949. });
  99950. ```
  99951. Simple Example
  99952. --------------
  99953. Synchronous Example
  99954. ```javascript
  99955. let result;
  99956. try {
  99957. result = findResult();
  99958. // success
  99959. } catch(reason) {
  99960. // failure
  99961. }
  99962. ```
  99963. Errback Example
  99964. ```js
  99965. findResult(function(result, err){
  99966. if (err) {
  99967. // failure
  99968. } else {
  99969. // success
  99970. }
  99971. });
  99972. ```
  99973. Promise Example;
  99974. ```javascript
  99975. findResult().then(function(result){
  99976. // success
  99977. }, function(reason){
  99978. // failure
  99979. });
  99980. ```
  99981. Advanced Example
  99982. --------------
  99983. Synchronous Example
  99984. ```javascript
  99985. let author, books;
  99986. try {
  99987. author = findAuthor();
  99988. books = findBooksByAuthor(author);
  99989. // success
  99990. } catch(reason) {
  99991. // failure
  99992. }
  99993. ```
  99994. Errback Example
  99995. ```js
  99996. function foundBooks(books) {
  99997. }
  99998. function failure(reason) {
  99999. }
  100000. findAuthor(function(author, err){
  100001. if (err) {
  100002. failure(err);
  100003. // failure
  100004. } else {
  100005. try {
  100006. findBoooksByAuthor(author, function(books, err) {
  100007. if (err) {
  100008. failure(err);
  100009. } else {
  100010. try {
  100011. foundBooks(books);
  100012. } catch(reason) {
  100013. failure(reason);
  100014. }
  100015. }
  100016. });
  100017. } catch(error) {
  100018. failure(err);
  100019. }
  100020. // success
  100021. }
  100022. });
  100023. ```
  100024. Promise Example;
  100025. ```javascript
  100026. findAuthor().
  100027. then(findBooksByAuthor).
  100028. then(function(books){
  100029. // found books
  100030. }).catch(function(reason){
  100031. // something went wrong
  100032. });
  100033. ```
  100034. @method then
  100035. @param {Function} onFulfilled
  100036. @param {Function} onRejected
  100037. Useful for tooling.
  100038. @return {Promise}
  100039. */
  100040. then: then,
  100041. /**
  100042. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  100043. as the catch block of a try/catch statement.
  100044. ```js
  100045. function findAuthor(){
  100046. throw new Error('couldn't find that author');
  100047. }
  100048. // synchronous
  100049. try {
  100050. findAuthor();
  100051. } catch(reason) {
  100052. // something went wrong
  100053. }
  100054. // async with promises
  100055. findAuthor().catch(function(reason){
  100056. // something went wrong
  100057. });
  100058. ```
  100059. @method catch
  100060. @param {Function} onRejection
  100061. Useful for tooling.
  100062. @return {Promise}
  100063. */
  100064. 'catch': function _catch(onRejection) {
  100065. return this.then(null, onRejection);
  100066. }
  100067. };
  100068. /*global self*/
  100069. function polyfill$1() {
  100070. var local = undefined;
  100071. if (typeof global !== 'undefined') {
  100072. local = global;
  100073. } else if (typeof self !== 'undefined') {
  100074. local = self;
  100075. } else {
  100076. try {
  100077. local = Function('return this')();
  100078. } catch (e) {
  100079. throw new Error('polyfill failed because global object is unavailable in this environment');
  100080. }
  100081. }
  100082. var P = local.Promise;
  100083. if (P) {
  100084. var promiseToString = null;
  100085. try {
  100086. promiseToString = Object.prototype.toString.call(P.resolve());
  100087. } catch (e) {
  100088. // silently ignored
  100089. }
  100090. if (promiseToString === '[object Promise]' && !P.cast) {
  100091. return;
  100092. }
  100093. }
  100094. local.Promise = Promise$2;
  100095. }
  100096. // Strange compat..
  100097. Promise$2.polyfill = polyfill$1;
  100098. Promise$2.Promise = Promise$2;
  100099. return Promise$2;
  100100. })));
  100101. //# sourceMappingURL=es6-promise.map
  100102. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(25), __webpack_require__(1)))
  100103. /***/ }),
  100104. /* 25 */
  100105. /***/ (function(module, exports) {
  100106. // shim for using process in browser
  100107. var process = module.exports = {};
  100108. // cached from whatever global is present so that test runners that stub it
  100109. // don't break things. But we need to wrap it in a try catch in case it is
  100110. // wrapped in strict mode code which doesn't define any globals. It's inside a
  100111. // function because try/catches deoptimize in certain engines.
  100112. var cachedSetTimeout;
  100113. var cachedClearTimeout;
  100114. function defaultSetTimout() {
  100115. throw new Error('setTimeout has not been defined');
  100116. }
  100117. function defaultClearTimeout () {
  100118. throw new Error('clearTimeout has not been defined');
  100119. }
  100120. (function () {
  100121. try {
  100122. if (typeof setTimeout === 'function') {
  100123. cachedSetTimeout = setTimeout;
  100124. } else {
  100125. cachedSetTimeout = defaultSetTimout;
  100126. }
  100127. } catch (e) {
  100128. cachedSetTimeout = defaultSetTimout;
  100129. }
  100130. try {
  100131. if (typeof clearTimeout === 'function') {
  100132. cachedClearTimeout = clearTimeout;
  100133. } else {
  100134. cachedClearTimeout = defaultClearTimeout;
  100135. }
  100136. } catch (e) {
  100137. cachedClearTimeout = defaultClearTimeout;
  100138. }
  100139. } ())
  100140. function runTimeout(fun) {
  100141. if (cachedSetTimeout === setTimeout) {
  100142. //normal enviroments in sane situations
  100143. return setTimeout(fun, 0);
  100144. }
  100145. // if setTimeout wasn't available but was latter defined
  100146. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  100147. cachedSetTimeout = setTimeout;
  100148. return setTimeout(fun, 0);
  100149. }
  100150. try {
  100151. // when when somebody has screwed with setTimeout but no I.E. maddness
  100152. return cachedSetTimeout(fun, 0);
  100153. } catch(e){
  100154. try {
  100155. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  100156. return cachedSetTimeout.call(null, fun, 0);
  100157. } catch(e){
  100158. // 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
  100159. return cachedSetTimeout.call(this, fun, 0);
  100160. }
  100161. }
  100162. }
  100163. function runClearTimeout(marker) {
  100164. if (cachedClearTimeout === clearTimeout) {
  100165. //normal enviroments in sane situations
  100166. return clearTimeout(marker);
  100167. }
  100168. // if clearTimeout wasn't available but was latter defined
  100169. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  100170. cachedClearTimeout = clearTimeout;
  100171. return clearTimeout(marker);
  100172. }
  100173. try {
  100174. // when when somebody has screwed with setTimeout but no I.E. maddness
  100175. return cachedClearTimeout(marker);
  100176. } catch (e){
  100177. try {
  100178. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  100179. return cachedClearTimeout.call(null, marker);
  100180. } catch (e){
  100181. // 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.
  100182. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  100183. return cachedClearTimeout.call(this, marker);
  100184. }
  100185. }
  100186. }
  100187. var queue = [];
  100188. var draining = false;
  100189. var currentQueue;
  100190. var queueIndex = -1;
  100191. function cleanUpNextTick() {
  100192. if (!draining || !currentQueue) {
  100193. return;
  100194. }
  100195. draining = false;
  100196. if (currentQueue.length) {
  100197. queue = currentQueue.concat(queue);
  100198. } else {
  100199. queueIndex = -1;
  100200. }
  100201. if (queue.length) {
  100202. drainQueue();
  100203. }
  100204. }
  100205. function drainQueue() {
  100206. if (draining) {
  100207. return;
  100208. }
  100209. var timeout = runTimeout(cleanUpNextTick);
  100210. draining = true;
  100211. var len = queue.length;
  100212. while(len) {
  100213. currentQueue = queue;
  100214. queue = [];
  100215. while (++queueIndex < len) {
  100216. if (currentQueue) {
  100217. currentQueue[queueIndex].run();
  100218. }
  100219. }
  100220. queueIndex = -1;
  100221. len = queue.length;
  100222. }
  100223. currentQueue = null;
  100224. draining = false;
  100225. runClearTimeout(timeout);
  100226. }
  100227. process.nextTick = function (fun) {
  100228. var args = new Array(arguments.length - 1);
  100229. if (arguments.length > 1) {
  100230. for (var i = 1; i < arguments.length; i++) {
  100231. args[i - 1] = arguments[i];
  100232. }
  100233. }
  100234. queue.push(new Item(fun, args));
  100235. if (queue.length === 1 && !draining) {
  100236. runTimeout(drainQueue);
  100237. }
  100238. };
  100239. // v8 likes predictible objects
  100240. function Item(fun, array) {
  100241. this.fun = fun;
  100242. this.array = array;
  100243. }
  100244. Item.prototype.run = function () {
  100245. this.fun.apply(null, this.array);
  100246. };
  100247. process.title = 'browser';
  100248. process.browser = true;
  100249. process.env = {};
  100250. process.argv = [];
  100251. process.version = ''; // empty string to avoid regexp issues
  100252. process.versions = {};
  100253. function noop() {}
  100254. process.on = noop;
  100255. process.addListener = noop;
  100256. process.once = noop;
  100257. process.off = noop;
  100258. process.removeListener = noop;
  100259. process.removeAllListeners = noop;
  100260. process.emit = noop;
  100261. process.prependListener = noop;
  100262. process.prependOnceListener = noop;
  100263. process.listeners = function (name) { return [] }
  100264. process.binding = function (name) {
  100265. throw new Error('process.binding is not supported');
  100266. };
  100267. process.cwd = function () { return '/' };
  100268. process.chdir = function (dir) {
  100269. throw new Error('process.chdir is not supported');
  100270. };
  100271. process.umask = function() { return 0; };
  100272. /***/ }),
  100273. /* 26 */
  100274. /***/ (function(module, exports) {
  100275. /* (ignored) */
  100276. /***/ })
  100277. /******/ ]);
  100278. });
  100279. //# sourceMappingURL=viewer.js.map