babylon.1.14-beta-debug.js 1019 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var Color3 = (function () {
  4. function Color3(r, g, b) {
  5. if (typeof r === "undefined") { r = 0; }
  6. if (typeof g === "undefined") { g = 0; }
  7. if (typeof b === "undefined") { b = 0; }
  8. this.r = r;
  9. this.g = g;
  10. this.b = b;
  11. }
  12. Color3.prototype.toString = function () {
  13. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  14. };
  15. Color3.prototype.toArray = function (array, index) {
  16. if (index === undefined) {
  17. index = 0;
  18. }
  19. array[index] = this.r;
  20. array[index + 1] = this.g;
  21. array[index + 2] = this.b;
  22. };
  23. Color3.prototype.toColor4 = function (alpha) {
  24. if (typeof alpha === "undefined") { alpha = 1; }
  25. return new Color4(this.r, this.g, this.b, alpha);
  26. };
  27. Color3.prototype.asArray = function () {
  28. var result = [];
  29. this.toArray(result, 0);
  30. return result;
  31. };
  32. Color3.prototype.toLuminance = function () {
  33. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  34. };
  35. Color3.prototype.multiply = function (otherColor) {
  36. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  37. };
  38. Color3.prototype.multiplyToRef = function (otherColor, result) {
  39. result.r = this.r * otherColor.r;
  40. result.g = this.g * otherColor.g;
  41. result.b = this.b * otherColor.b;
  42. };
  43. Color3.prototype.equals = function (otherColor) {
  44. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  45. };
  46. Color3.prototype.scale = function (scale) {
  47. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  48. };
  49. Color3.prototype.scaleToRef = function (scale, result) {
  50. result.r = this.r * scale;
  51. result.g = this.g * scale;
  52. result.b = this.b * scale;
  53. };
  54. Color3.prototype.add = function (otherColor) {
  55. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  56. };
  57. Color3.prototype.addToRef = function (otherColor, result) {
  58. result.r = this.r + otherColor.r;
  59. result.g = this.g + otherColor.g;
  60. result.b = this.b + otherColor.b;
  61. };
  62. Color3.prototype.subtract = function (otherColor) {
  63. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  64. };
  65. Color3.prototype.subtractToRef = function (otherColor, result) {
  66. result.r = this.r - otherColor.r;
  67. result.g = this.g - otherColor.g;
  68. result.b = this.b - otherColor.b;
  69. };
  70. Color3.prototype.clone = function () {
  71. return new Color3(this.r, this.g, this.b);
  72. };
  73. Color3.prototype.copyFrom = function (source) {
  74. this.r = source.r;
  75. this.g = source.g;
  76. this.b = source.b;
  77. };
  78. Color3.prototype.copyFromFloats = function (r, g, b) {
  79. this.r = r;
  80. this.g = g;
  81. this.b = b;
  82. };
  83. Color3.FromArray = function (array) {
  84. return new Color3(array[0], array[1], array[2]);
  85. };
  86. Color3.FromInts = function (r, g, b) {
  87. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  88. };
  89. Color3.Lerp = function (start, end, amount) {
  90. var r = start.r + ((end.r - start.r) * amount);
  91. var g = start.g + ((end.g - start.g) * amount);
  92. var b = start.b + ((end.b - start.b) * amount);
  93. return new Color3(r, g, b);
  94. };
  95. Color3.Red = function () {
  96. return new Color3(1, 0, 0);
  97. };
  98. Color3.Green = function () {
  99. return new Color3(0, 1, 0);
  100. };
  101. Color3.Blue = function () {
  102. return new Color3(0, 0, 1);
  103. };
  104. Color3.Black = function () {
  105. return new Color3(0, 0, 0);
  106. };
  107. Color3.White = function () {
  108. return new Color3(1, 1, 1);
  109. };
  110. Color3.Purple = function () {
  111. return new Color3(0.5, 0, 0.5);
  112. };
  113. Color3.Magenta = function () {
  114. return new Color3(1, 0, 1);
  115. };
  116. Color3.Yellow = function () {
  117. return new Color3(1, 1, 0);
  118. };
  119. Color3.Gray = function () {
  120. return new Color3(0.5, 0.5, 0.5);
  121. };
  122. return Color3;
  123. })();
  124. BABYLON.Color3 = Color3;
  125. var Color4 = (function () {
  126. function Color4(r, g, b, a) {
  127. this.r = r;
  128. this.g = g;
  129. this.b = b;
  130. this.a = a;
  131. }
  132. Color4.prototype.addInPlace = function (right) {
  133. this.r += right.r;
  134. this.g += right.g;
  135. this.b += right.b;
  136. this.a += right.a;
  137. };
  138. Color4.prototype.asArray = function () {
  139. var result = [];
  140. this.toArray(result, 0);
  141. return result;
  142. };
  143. Color4.prototype.toArray = function (array, index) {
  144. if (index === undefined) {
  145. index = 0;
  146. }
  147. array[index] = this.r;
  148. array[index + 1] = this.g;
  149. array[index + 2] = this.b;
  150. array[index + 3] = this.a;
  151. };
  152. Color4.prototype.add = function (right) {
  153. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  154. };
  155. Color4.prototype.subtract = function (right) {
  156. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  157. };
  158. Color4.prototype.subtractToRef = function (right, result) {
  159. result.r = this.r - right.r;
  160. result.g = this.g - right.g;
  161. result.b = this.b - right.b;
  162. result.a = this.a - right.a;
  163. };
  164. Color4.prototype.scale = function (scale) {
  165. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  166. };
  167. Color4.prototype.scaleToRef = function (scale, result) {
  168. result.r = this.r * scale;
  169. result.g = this.g * scale;
  170. result.b = this.b * scale;
  171. result.a = this.a * scale;
  172. };
  173. Color4.prototype.toString = function () {
  174. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  175. };
  176. Color4.prototype.clone = function () {
  177. return new Color4(this.r, this.g, this.b, this.a);
  178. };
  179. Color4.Lerp = function (left, right, amount) {
  180. var result = new Color4(0, 0, 0, 0);
  181. BABYLON.Color4.LerpToRef(left, right, amount, result);
  182. return result;
  183. };
  184. Color4.LerpToRef = function (left, right, amount, result) {
  185. result.r = left.r + (right.r - left.r) * amount;
  186. result.g = left.g + (right.g - left.g) * amount;
  187. result.b = left.b + (right.b - left.b) * amount;
  188. result.a = left.a + (right.a - left.a) * amount;
  189. };
  190. Color4.FromArray = function (array, offset) {
  191. if (typeof offset === "undefined") { offset = 0; }
  192. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  193. };
  194. Color4.FromInts = function (r, g, b, a) {
  195. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  196. };
  197. return Color4;
  198. })();
  199. BABYLON.Color4 = Color4;
  200. var Vector2 = (function () {
  201. function Vector2(x, y) {
  202. this.x = x;
  203. this.y = y;
  204. }
  205. Vector2.prototype.toString = function () {
  206. return "{X: " + this.x + " Y:" + this.y + "}";
  207. };
  208. Vector2.prototype.toArray = function (array, index) {
  209. if (index === undefined) {
  210. index = 0;
  211. }
  212. array[index] = this.x;
  213. array[index + 1] = this.y;
  214. };
  215. Vector2.prototype.asArray = function () {
  216. var result = [];
  217. this.toArray(result, 0);
  218. return result;
  219. };
  220. Vector2.prototype.copyFrom = function (source) {
  221. this.x = source.x;
  222. this.y = source.y;
  223. };
  224. Vector2.prototype.copyFromFloats = function (x, y) {
  225. this.x = x;
  226. this.y = y;
  227. };
  228. Vector2.prototype.add = function (otherVector) {
  229. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  230. };
  231. Vector2.prototype.addVector3 = function (otherVector) {
  232. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  233. };
  234. Vector2.prototype.subtract = function (otherVector) {
  235. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  236. };
  237. Vector2.prototype.multiplyInPlace = function (otherVector) {
  238. this.x *= otherVector.x;
  239. this.y *= otherVector.y;
  240. };
  241. Vector2.prototype.multiply = function (otherVector) {
  242. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  243. };
  244. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  245. result.x = this.x * otherVector.x;
  246. result.y = this.y * otherVector.y;
  247. };
  248. Vector2.prototype.multiplyByFloats = function (x, y) {
  249. return new Vector2(this.x * x, this.y * y);
  250. };
  251. Vector2.prototype.divide = function (otherVector) {
  252. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  253. };
  254. Vector2.prototype.divideToRef = function (otherVector, result) {
  255. result.x = this.x / otherVector.x;
  256. result.y = this.y / otherVector.y;
  257. };
  258. Vector2.prototype.negate = function () {
  259. return new Vector2(-this.x, -this.y);
  260. };
  261. Vector2.prototype.scaleInPlace = function (scale) {
  262. this.x *= scale;
  263. this.y *= scale;
  264. };
  265. Vector2.prototype.scale = function (scale) {
  266. return new Vector2(this.x * scale, this.y * scale);
  267. };
  268. Vector2.prototype.equals = function (otherVector) {
  269. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  270. };
  271. Vector2.prototype.length = function () {
  272. return Math.sqrt(this.x * this.x + this.y * this.y);
  273. };
  274. Vector2.prototype.lengthSquared = function () {
  275. return (this.x * this.x + this.y * this.y);
  276. };
  277. Vector2.prototype.normalize = function () {
  278. var len = this.length();
  279. if (len === 0)
  280. return;
  281. var num = 1.0 / len;
  282. this.x *= num;
  283. this.y *= num;
  284. };
  285. Vector2.prototype.clone = function () {
  286. return new Vector2(this.x, this.y);
  287. };
  288. Vector2.Zero = function () {
  289. return new Vector2(0, 0);
  290. };
  291. Vector2.FromArray = function (array, offset) {
  292. if (!offset) {
  293. offset = 0;
  294. }
  295. return new Vector2(array[offset], array[offset + 1]);
  296. };
  297. Vector2.FromArrayToRef = function (array, offset, result) {
  298. result.x = array[offset];
  299. result.y = array[offset + 1];
  300. };
  301. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  302. var squared = amount * amount;
  303. var cubed = amount * squared;
  304. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  305. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  306. return new Vector2(x, y);
  307. };
  308. Vector2.Clamp = function (value, min, max) {
  309. var x = value.x;
  310. x = (x > max.x) ? max.x : x;
  311. x = (x < min.x) ? min.x : x;
  312. var y = value.y;
  313. y = (y > max.y) ? max.y : y;
  314. y = (y < min.y) ? min.y : y;
  315. return new Vector2(x, y);
  316. };
  317. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  318. var squared = amount * amount;
  319. var cubed = amount * squared;
  320. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  321. var part2 = (-2.0 * cubed) + (3.0 * squared);
  322. var part3 = (cubed - (2.0 * squared)) + amount;
  323. var part4 = cubed - squared;
  324. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  325. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  326. return new Vector2(x, y);
  327. };
  328. Vector2.Lerp = function (start, end, amount) {
  329. var x = start.x + ((end.x - start.x) * amount);
  330. var y = start.y + ((end.y - start.y) * amount);
  331. return new Vector2(x, y);
  332. };
  333. Vector2.Dot = function (left, right) {
  334. return left.x * right.x + left.y * right.y;
  335. };
  336. Vector2.Normalize = function (vector) {
  337. var newVector = vector.clone();
  338. newVector.normalize();
  339. return newVector;
  340. };
  341. Vector2.Minimize = function (left, right) {
  342. var x = (left.x < right.x) ? left.x : right.x;
  343. var y = (left.y < right.y) ? left.y : right.y;
  344. return new Vector2(x, y);
  345. };
  346. Vector2.Maximize = function (left, right) {
  347. var x = (left.x > right.x) ? left.x : right.x;
  348. var y = (left.y > right.y) ? left.y : right.y;
  349. return new Vector2(x, y);
  350. };
  351. Vector2.Transform = function (vector, transformation) {
  352. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  353. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  354. return new Vector2(x, y);
  355. };
  356. Vector2.Distance = function (value1, value2) {
  357. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  358. };
  359. Vector2.DistanceSquared = function (value1, value2) {
  360. var x = value1.x - value2.x;
  361. var y = value1.y - value2.y;
  362. return (x * x) + (y * y);
  363. };
  364. return Vector2;
  365. })();
  366. BABYLON.Vector2 = Vector2;
  367. var Vector3 = (function () {
  368. function Vector3(x, y, z) {
  369. this.x = x;
  370. this.y = y;
  371. this.z = z;
  372. }
  373. Vector3.prototype.toString = function () {
  374. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  375. };
  376. Vector3.prototype.asArray = function () {
  377. var result = [];
  378. this.toArray(result, 0);
  379. return result;
  380. };
  381. Vector3.prototype.toArray = function (array, index) {
  382. if (index === undefined) {
  383. index = 0;
  384. }
  385. array[index] = this.x;
  386. array[index + 1] = this.y;
  387. array[index + 2] = this.z;
  388. };
  389. Vector3.prototype.addInPlace = function (otherVector) {
  390. this.x += otherVector.x;
  391. this.y += otherVector.y;
  392. this.z += otherVector.z;
  393. };
  394. Vector3.prototype.add = function (otherVector) {
  395. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  396. };
  397. Vector3.prototype.addToRef = function (otherVector, result) {
  398. result.x = this.x + otherVector.x;
  399. result.y = this.y + otherVector.y;
  400. result.z = this.z + otherVector.z;
  401. };
  402. Vector3.prototype.subtractInPlace = function (otherVector) {
  403. this.x -= otherVector.x;
  404. this.y -= otherVector.y;
  405. this.z -= otherVector.z;
  406. };
  407. Vector3.prototype.subtract = function (otherVector) {
  408. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  409. };
  410. Vector3.prototype.subtractToRef = function (otherVector, result) {
  411. result.x = this.x - otherVector.x;
  412. result.y = this.y - otherVector.y;
  413. result.z = this.z - otherVector.z;
  414. };
  415. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  416. return new Vector3(this.x - x, this.y - y, this.z - z);
  417. };
  418. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  419. result.x = this.x - x;
  420. result.y = this.y - y;
  421. result.z = this.z - z;
  422. };
  423. Vector3.prototype.negate = function () {
  424. return new Vector3(-this.x, -this.y, -this.z);
  425. };
  426. Vector3.prototype.scaleInPlace = function (scale) {
  427. this.x *= scale;
  428. this.y *= scale;
  429. this.z *= scale;
  430. };
  431. Vector3.prototype.scale = function (scale) {
  432. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  433. };
  434. Vector3.prototype.scaleToRef = function (scale, result) {
  435. result.x = this.x * scale;
  436. result.y = this.y * scale;
  437. result.z = this.z * scale;
  438. };
  439. Vector3.prototype.equals = function (otherVector) {
  440. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  441. };
  442. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  443. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  444. };
  445. Vector3.prototype.equalsToFloats = function (x, y, z) {
  446. return this.x === x && this.y === y && this.z === z;
  447. };
  448. Vector3.prototype.multiplyInPlace = function (otherVector) {
  449. this.x *= otherVector.x;
  450. this.y *= otherVector.y;
  451. this.z *= otherVector.z;
  452. };
  453. Vector3.prototype.multiply = function (otherVector) {
  454. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  455. };
  456. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  457. result.x = this.x * otherVector.x;
  458. result.y = this.y * otherVector.y;
  459. result.z = this.z * otherVector.z;
  460. };
  461. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  462. return new Vector3(this.x * x, this.y * y, this.z * z);
  463. };
  464. Vector3.prototype.divide = function (otherVector) {
  465. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  466. };
  467. Vector3.prototype.divideToRef = function (otherVector, result) {
  468. result.x = this.x / otherVector.x;
  469. result.y = this.y / otherVector.y;
  470. result.z = this.z / otherVector.z;
  471. };
  472. Vector3.prototype.MinimizeInPlace = function (other) {
  473. if (other.x < this.x)
  474. this.x = other.x;
  475. if (other.y < this.y)
  476. this.y = other.y;
  477. if (other.z < this.z)
  478. this.z = other.z;
  479. };
  480. Vector3.prototype.MaximizeInPlace = function (other) {
  481. if (other.x > this.x)
  482. this.x = other.x;
  483. if (other.y > this.y)
  484. this.y = other.y;
  485. if (other.z > this.z)
  486. this.z = other.z;
  487. };
  488. Vector3.prototype.length = function () {
  489. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  490. };
  491. Vector3.prototype.lengthSquared = function () {
  492. return (this.x * this.x + this.y * this.y + this.z * this.z);
  493. };
  494. Vector3.prototype.normalize = function () {
  495. var len = this.length();
  496. if (len === 0)
  497. return;
  498. var num = 1.0 / len;
  499. this.x *= num;
  500. this.y *= num;
  501. this.z *= num;
  502. };
  503. Vector3.prototype.clone = function () {
  504. return new Vector3(this.x, this.y, this.z);
  505. };
  506. Vector3.prototype.copyFrom = function (source) {
  507. this.x = source.x;
  508. this.y = source.y;
  509. this.z = source.z;
  510. };
  511. Vector3.prototype.copyFromFloats = function (x, y, z) {
  512. this.x = x;
  513. this.y = y;
  514. this.z = z;
  515. };
  516. Vector3.FromArray = function (array, offset) {
  517. if (!offset) {
  518. offset = 0;
  519. }
  520. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  521. };
  522. Vector3.FromArrayToRef = function (array, offset, result) {
  523. result.x = array[offset];
  524. result.y = array[offset + 1];
  525. result.z = array[offset + 2];
  526. };
  527. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  528. result.x = array[offset];
  529. result.y = array[offset + 1];
  530. result.z = array[offset + 2];
  531. };
  532. Vector3.FromFloatsToRef = function (x, y, z, result) {
  533. result.x = x;
  534. result.y = y;
  535. result.z = z;
  536. };
  537. Vector3.Zero = function () {
  538. return new Vector3(0, 0, 0);
  539. };
  540. Vector3.Up = function () {
  541. return new Vector3(0, 1.0, 0);
  542. };
  543. Vector3.TransformCoordinates = function (vector, transformation) {
  544. var result = Vector3.Zero();
  545. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  546. return result;
  547. };
  548. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  549. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  550. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  551. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  552. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  553. result.x = x / w;
  554. result.y = y / w;
  555. result.z = z / w;
  556. };
  557. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  558. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  559. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  560. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  561. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  562. result.x = rx / rw;
  563. result.y = ry / rw;
  564. result.z = rz / rw;
  565. };
  566. Vector3.TransformNormal = function (vector, transformation) {
  567. var result = Vector3.Zero();
  568. Vector3.TransformNormalToRef(vector, transformation, result);
  569. return result;
  570. };
  571. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  572. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  573. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  574. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  575. };
  576. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  577. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  578. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  579. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  580. };
  581. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  582. var squared = amount * amount;
  583. var cubed = amount * squared;
  584. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  585. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  586. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  587. return new Vector3(x, y, z);
  588. };
  589. Vector3.Clamp = function (value, min, max) {
  590. var x = value.x;
  591. x = (x > max.x) ? max.x : x;
  592. x = (x < min.x) ? min.x : x;
  593. var y = value.y;
  594. y = (y > max.y) ? max.y : y;
  595. y = (y < min.y) ? min.y : y;
  596. var z = value.z;
  597. z = (z > max.z) ? max.z : z;
  598. z = (z < min.z) ? min.z : z;
  599. return new Vector3(x, y, z);
  600. };
  601. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  602. var squared = amount * amount;
  603. var cubed = amount * squared;
  604. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  605. var part2 = (-2.0 * cubed) + (3.0 * squared);
  606. var part3 = (cubed - (2.0 * squared)) + amount;
  607. var part4 = cubed - squared;
  608. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  609. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  610. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  611. return new Vector3(x, y, z);
  612. };
  613. Vector3.Lerp = function (start, end, amount) {
  614. var x = start.x + ((end.x - start.x) * amount);
  615. var y = start.y + ((end.y - start.y) * amount);
  616. var z = start.z + ((end.z - start.z) * amount);
  617. return new Vector3(x, y, z);
  618. };
  619. Vector3.Dot = function (left, right) {
  620. return (left.x * right.x + left.y * right.y + left.z * right.z);
  621. };
  622. Vector3.Cross = function (left, right) {
  623. var result = Vector3.Zero();
  624. Vector3.CrossToRef(left, right, result);
  625. return result;
  626. };
  627. Vector3.CrossToRef = function (left, right, result) {
  628. result.x = left.y * right.z - left.z * right.y;
  629. result.y = left.z * right.x - left.x * right.z;
  630. result.z = left.x * right.y - left.y * right.x;
  631. };
  632. Vector3.Normalize = function (vector) {
  633. var result = Vector3.Zero();
  634. Vector3.NormalizeToRef(vector, result);
  635. return result;
  636. };
  637. Vector3.NormalizeToRef = function (vector, result) {
  638. result.copyFrom(vector);
  639. result.normalize();
  640. };
  641. Vector3.Project = function (vector, world, transform, viewport) {
  642. var cw = viewport.width;
  643. var ch = viewport.height;
  644. var cx = viewport.x;
  645. var cy = viewport.y;
  646. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  647. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  648. return Vector3.TransformCoordinates(vector, finalMatrix);
  649. };
  650. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  651. var matrix = world.multiply(view).multiply(projection);
  652. matrix.invert();
  653. source.x = source.x / viewportWidth * 2 - 1;
  654. source.y = -(source.y / viewportHeight * 2 - 1);
  655. var vector = BABYLON.Vector3.TransformCoordinates(source, matrix);
  656. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  657. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  658. vector = vector.scale(1.0 / num);
  659. }
  660. return vector;
  661. };
  662. Vector3.Minimize = function (left, right) {
  663. var min = left.clone();
  664. min.MinimizeInPlace(right);
  665. return min;
  666. };
  667. Vector3.Maximize = function (left, right) {
  668. var max = left.clone();
  669. max.MaximizeInPlace(right);
  670. return max;
  671. };
  672. Vector3.Distance = function (value1, value2) {
  673. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  674. };
  675. Vector3.DistanceSquared = function (value1, value2) {
  676. var x = value1.x - value2.x;
  677. var y = value1.y - value2.y;
  678. var z = value1.z - value2.z;
  679. return (x * x) + (y * y) + (z * z);
  680. };
  681. Vector3.Center = function (value1, value2) {
  682. var center = value1.add(value2);
  683. center.scaleInPlace(0.5);
  684. return center;
  685. };
  686. return Vector3;
  687. })();
  688. BABYLON.Vector3 = Vector3;
  689. var Quaternion = (function () {
  690. function Quaternion(x, y, z, w) {
  691. if (typeof x === "undefined") { x = 0; }
  692. if (typeof y === "undefined") { y = 0; }
  693. if (typeof z === "undefined") { z = 0; }
  694. if (typeof w === "undefined") { w = 1; }
  695. this.x = x;
  696. this.y = y;
  697. this.z = z;
  698. this.w = w;
  699. }
  700. Quaternion.prototype.toString = function () {
  701. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  702. };
  703. Quaternion.prototype.asArray = function () {
  704. return [this.x, this.y, this.z, this.w];
  705. };
  706. Quaternion.prototype.equals = function (otherQuaternion) {
  707. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  708. };
  709. Quaternion.prototype.clone = function () {
  710. return new Quaternion(this.x, this.y, this.z, this.w);
  711. };
  712. Quaternion.prototype.copyFrom = function (other) {
  713. this.x = other.x;
  714. this.y = other.y;
  715. this.z = other.z;
  716. this.w = other.w;
  717. };
  718. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  719. this.x = x;
  720. this.y = y;
  721. this.z = z;
  722. this.w = w;
  723. };
  724. Quaternion.prototype.add = function (other) {
  725. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  726. };
  727. Quaternion.prototype.subtract = function (other) {
  728. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  729. };
  730. Quaternion.prototype.scale = function (value) {
  731. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  732. };
  733. Quaternion.prototype.multiply = function (q1) {
  734. var result = new Quaternion(0, 0, 0, 1.0);
  735. this.multiplyToRef(q1, result);
  736. return result;
  737. };
  738. Quaternion.prototype.multiplyToRef = function (q1, result) {
  739. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  740. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  741. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  742. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  743. };
  744. Quaternion.prototype.length = function () {
  745. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  746. };
  747. Quaternion.prototype.normalize = function () {
  748. var length = 1.0 / this.length();
  749. this.x *= length;
  750. this.y *= length;
  751. this.z *= length;
  752. this.w *= length;
  753. };
  754. Quaternion.prototype.toEulerAngles = function () {
  755. var result = Vector3.Zero();
  756. this.toEulerAnglesToRef(result);
  757. return result;
  758. };
  759. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  760. var qx = this.x;
  761. var qy = this.y;
  762. var qz = this.z;
  763. var qw = this.w;
  764. var sqx = qx * qx;
  765. var sqy = qy * qy;
  766. var sqz = qz * qz;
  767. var yaw = Math.atan2(2.0 * (qy * qw - qx * qz), 1.0 - 2.0 * (sqy + sqz));
  768. var pitch = Math.asin(2.0 * (qx * qy + qz * qw));
  769. var roll = Math.atan2(2.0 * (qx * qw - qy * qz), 1.0 - 2.0 * (sqx + sqz));
  770. var gimbaLockTest = qx * qy + qz * qw;
  771. if (gimbaLockTest > 0.499) {
  772. yaw = 2.0 * Math.atan2(qx, qw);
  773. roll = 0;
  774. } else if (gimbaLockTest < -0.499) {
  775. yaw = -2.0 * Math.atan2(qx, qw);
  776. roll = 0;
  777. }
  778. result.x = pitch;
  779. result.y = yaw;
  780. result.z = roll;
  781. };
  782. Quaternion.prototype.toRotationMatrix = function (result) {
  783. var xx = this.x * this.x;
  784. var yy = this.y * this.y;
  785. var zz = this.z * this.z;
  786. var xy = this.x * this.y;
  787. var zw = this.z * this.w;
  788. var zx = this.z * this.x;
  789. var yw = this.y * this.w;
  790. var yz = this.y * this.z;
  791. var xw = this.x * this.w;
  792. result.m[0] = 1.0 - (2.0 * (yy + zz));
  793. result.m[1] = 2.0 * (xy + zw);
  794. result.m[2] = 2.0 * (zx - yw);
  795. result.m[3] = 0;
  796. result.m[4] = 2.0 * (xy - zw);
  797. result.m[5] = 1.0 - (2.0 * (zz + xx));
  798. result.m[6] = 2.0 * (yz + xw);
  799. result.m[7] = 0;
  800. result.m[8] = 2.0 * (zx + yw);
  801. result.m[9] = 2.0 * (yz - xw);
  802. result.m[10] = 1.0 - (2.0 * (yy + xx));
  803. result.m[11] = 0;
  804. result.m[12] = 0;
  805. result.m[13] = 0;
  806. result.m[14] = 0;
  807. result.m[15] = 1.0;
  808. };
  809. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  810. var data = matrix.m;
  811. var m11 = data[0], m12 = data[4], m13 = data[8];
  812. var m21 = data[1], m22 = data[5], m23 = data[9];
  813. var m31 = data[2], m32 = data[6], m33 = data[10];
  814. var trace = m11 + m22 + m33;
  815. var s;
  816. if (trace > 0) {
  817. s = 0.5 / Math.sqrt(trace + 1.0);
  818. this.w = 0.25 / s;
  819. this.x = (m32 - m23) * s;
  820. this.y = (m13 - m31) * s;
  821. this.z = (m21 - m12) * s;
  822. return;
  823. }
  824. if (m11 > m22 && m11 > m33) {
  825. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  826. this.w = (m32 - m23) / s;
  827. this.x = 0.25 * s;
  828. this.y = (m12 + m21) / s;
  829. this.z = (m13 + m31) / s;
  830. return;
  831. }
  832. if (m22 > m33) {
  833. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  834. this.w = (m13 - m31) / s;
  835. this.x = (m12 + m21) / s;
  836. this.y = 0.25 * s;
  837. this.z = (m23 + m32) / s;
  838. return;
  839. }
  840. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  841. this.w = (m21 - m12) / s;
  842. this.x = (m13 + m31) / s;
  843. this.y = (m23 + m32) / s;
  844. this.z = 0.25 * s;
  845. };
  846. Quaternion.Inverse = function (q) {
  847. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  848. };
  849. Quaternion.RotationAxis = function (axis, angle) {
  850. var result = new Quaternion();
  851. var sin = Math.sin(angle / 2);
  852. result.w = Math.cos(angle / 2);
  853. result.x = axis.x * sin;
  854. result.y = axis.y * sin;
  855. result.z = axis.z * sin;
  856. return result;
  857. };
  858. Quaternion.FromArray = function (array, offset) {
  859. if (!offset) {
  860. offset = 0;
  861. }
  862. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  863. };
  864. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  865. var result = new Quaternion();
  866. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  867. return result;
  868. };
  869. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  870. var halfRoll = roll * 0.5;
  871. var halfPitch = pitch * 0.5;
  872. var halfYaw = yaw * 0.5;
  873. var sinRoll = Math.sin(halfRoll);
  874. var cosRoll = Math.cos(halfRoll);
  875. var sinPitch = Math.sin(halfPitch);
  876. var cosPitch = Math.cos(halfPitch);
  877. var sinYaw = Math.sin(halfYaw);
  878. var cosYaw = Math.cos(halfYaw);
  879. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  880. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  881. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  882. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  883. };
  884. Quaternion.Slerp = function (left, right, amount) {
  885. var num2;
  886. var num3;
  887. var num = amount;
  888. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  889. var flag = false;
  890. if (num4 < 0) {
  891. flag = true;
  892. num4 = -num4;
  893. }
  894. if (num4 > 0.999999) {
  895. num3 = 1 - num;
  896. num2 = flag ? -num : num;
  897. } else {
  898. var num5 = Math.acos(num4);
  899. var num6 = (1.0 / Math.sin(num5));
  900. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  901. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  902. }
  903. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  904. };
  905. return Quaternion;
  906. })();
  907. BABYLON.Quaternion = Quaternion;
  908. var Matrix = (function () {
  909. function Matrix() {
  910. this.m = new Float32Array(16);
  911. }
  912. Matrix.prototype.isIdentity = function () {
  913. if (this.m[0] != 1.0 || this.m[5] != 1.0 || this.m[10] != 1.0 || this.m[15] != 1.0)
  914. return false;
  915. if (this.m[1] != 0.0 || this.m[2] != 0.0 || this.m[3] != 0.0 || this.m[4] != 0.0 || this.m[6] != 0.0 || this.m[7] != 0.0 || this.m[8] != 0.0 || this.m[9] != 0.0 || this.m[11] != 0.0 || this.m[12] != 0.0 || this.m[13] != 0.0 || this.m[14] != 0.0)
  916. return false;
  917. return true;
  918. };
  919. Matrix.prototype.determinant = function () {
  920. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  921. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  922. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  923. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  924. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  925. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  926. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  927. };
  928. Matrix.prototype.toArray = function () {
  929. return this.m;
  930. };
  931. Matrix.prototype.asArray = function () {
  932. return this.toArray();
  933. };
  934. Matrix.prototype.invert = function () {
  935. this.invertToRef(this);
  936. };
  937. Matrix.prototype.invertToRef = function (other) {
  938. var l1 = this.m[0];
  939. var l2 = this.m[1];
  940. var l3 = this.m[2];
  941. var l4 = this.m[3];
  942. var l5 = this.m[4];
  943. var l6 = this.m[5];
  944. var l7 = this.m[6];
  945. var l8 = this.m[7];
  946. var l9 = this.m[8];
  947. var l10 = this.m[9];
  948. var l11 = this.m[10];
  949. var l12 = this.m[11];
  950. var l13 = this.m[12];
  951. var l14 = this.m[13];
  952. var l15 = this.m[14];
  953. var l16 = this.m[15];
  954. var l17 = (l11 * l16) - (l12 * l15);
  955. var l18 = (l10 * l16) - (l12 * l14);
  956. var l19 = (l10 * l15) - (l11 * l14);
  957. var l20 = (l9 * l16) - (l12 * l13);
  958. var l21 = (l9 * l15) - (l11 * l13);
  959. var l22 = (l9 * l14) - (l10 * l13);
  960. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  961. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  962. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  963. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  964. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  965. var l28 = (l7 * l16) - (l8 * l15);
  966. var l29 = (l6 * l16) - (l8 * l14);
  967. var l30 = (l6 * l15) - (l7 * l14);
  968. var l31 = (l5 * l16) - (l8 * l13);
  969. var l32 = (l5 * l15) - (l7 * l13);
  970. var l33 = (l5 * l14) - (l6 * l13);
  971. var l34 = (l7 * l12) - (l8 * l11);
  972. var l35 = (l6 * l12) - (l8 * l10);
  973. var l36 = (l6 * l11) - (l7 * l10);
  974. var l37 = (l5 * l12) - (l8 * l9);
  975. var l38 = (l5 * l11) - (l7 * l9);
  976. var l39 = (l5 * l10) - (l6 * l9);
  977. other.m[0] = l23 * l27;
  978. other.m[4] = l24 * l27;
  979. other.m[8] = l25 * l27;
  980. other.m[12] = l26 * l27;
  981. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  982. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  983. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  984. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  985. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  986. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  987. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  988. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  989. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  990. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  991. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  992. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  993. };
  994. Matrix.prototype.setTranslation = function (vector3) {
  995. this.m[12] = vector3.x;
  996. this.m[13] = vector3.y;
  997. this.m[14] = vector3.z;
  998. };
  999. Matrix.prototype.multiply = function (other) {
  1000. var result = new Matrix();
  1001. this.multiplyToRef(other, result);
  1002. return result;
  1003. };
  1004. Matrix.prototype.copyFrom = function (other) {
  1005. for (var index = 0; index < 16; index++) {
  1006. this.m[index] = other.m[index];
  1007. }
  1008. };
  1009. Matrix.prototype.copyToArray = function (array, offset) {
  1010. if (typeof offset === "undefined") { offset = 0; }
  1011. for (var index = 0; index < 16; index++) {
  1012. array[offset + index] = this.m[index];
  1013. }
  1014. };
  1015. Matrix.prototype.multiplyToRef = function (other, result) {
  1016. this.multiplyToArray(other, result.m, 0);
  1017. };
  1018. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1019. var tm0 = this.m[0];
  1020. var tm1 = this.m[1];
  1021. var tm2 = this.m[2];
  1022. var tm3 = this.m[3];
  1023. var tm4 = this.m[4];
  1024. var tm5 = this.m[5];
  1025. var tm6 = this.m[6];
  1026. var tm7 = this.m[7];
  1027. var tm8 = this.m[8];
  1028. var tm9 = this.m[9];
  1029. var tm10 = this.m[10];
  1030. var tm11 = this.m[11];
  1031. var tm12 = this.m[12];
  1032. var tm13 = this.m[13];
  1033. var tm14 = this.m[14];
  1034. var tm15 = this.m[15];
  1035. var om0 = other.m[0];
  1036. var om1 = other.m[1];
  1037. var om2 = other.m[2];
  1038. var om3 = other.m[3];
  1039. var om4 = other.m[4];
  1040. var om5 = other.m[5];
  1041. var om6 = other.m[6];
  1042. var om7 = other.m[7];
  1043. var om8 = other.m[8];
  1044. var om9 = other.m[9];
  1045. var om10 = other.m[10];
  1046. var om11 = other.m[11];
  1047. var om12 = other.m[12];
  1048. var om13 = other.m[13];
  1049. var om14 = other.m[14];
  1050. var om15 = other.m[15];
  1051. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1052. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1053. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1054. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1055. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1056. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1057. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1058. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1059. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1060. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1061. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1062. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1063. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1064. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1065. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1066. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1067. };
  1068. Matrix.prototype.equals = function (value) {
  1069. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1070. };
  1071. Matrix.prototype.clone = function () {
  1072. 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]);
  1073. };
  1074. Matrix.FromArray = function (array, offset) {
  1075. var result = new Matrix();
  1076. if (!offset) {
  1077. offset = 0;
  1078. }
  1079. Matrix.FromArrayToRef(array, offset, result);
  1080. return result;
  1081. };
  1082. Matrix.FromArrayToRef = function (array, offset, result) {
  1083. for (var index = 0; index < 16; index++) {
  1084. result.m[index] = array[index + offset];
  1085. }
  1086. };
  1087. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1088. result.m[0] = initialM11;
  1089. result.m[1] = initialM12;
  1090. result.m[2] = initialM13;
  1091. result.m[3] = initialM14;
  1092. result.m[4] = initialM21;
  1093. result.m[5] = initialM22;
  1094. result.m[6] = initialM23;
  1095. result.m[7] = initialM24;
  1096. result.m[8] = initialM31;
  1097. result.m[9] = initialM32;
  1098. result.m[10] = initialM33;
  1099. result.m[11] = initialM34;
  1100. result.m[12] = initialM41;
  1101. result.m[13] = initialM42;
  1102. result.m[14] = initialM43;
  1103. result.m[15] = initialM44;
  1104. };
  1105. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1106. var result = new Matrix();
  1107. result.m[0] = initialM11;
  1108. result.m[1] = initialM12;
  1109. result.m[2] = initialM13;
  1110. result.m[3] = initialM14;
  1111. result.m[4] = initialM21;
  1112. result.m[5] = initialM22;
  1113. result.m[6] = initialM23;
  1114. result.m[7] = initialM24;
  1115. result.m[8] = initialM31;
  1116. result.m[9] = initialM32;
  1117. result.m[10] = initialM33;
  1118. result.m[11] = initialM34;
  1119. result.m[12] = initialM41;
  1120. result.m[13] = initialM42;
  1121. result.m[14] = initialM43;
  1122. result.m[15] = initialM44;
  1123. return result;
  1124. };
  1125. Matrix.Identity = function () {
  1126. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1127. };
  1128. Matrix.IdentityToRef = function (result) {
  1129. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1130. };
  1131. Matrix.Zero = function () {
  1132. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1133. };
  1134. Matrix.RotationX = function (angle) {
  1135. var result = new Matrix();
  1136. Matrix.RotationXToRef(angle, result);
  1137. return result;
  1138. };
  1139. Matrix.RotationXToRef = function (angle, result) {
  1140. var s = Math.sin(angle);
  1141. var c = Math.cos(angle);
  1142. result.m[0] = 1.0;
  1143. result.m[15] = 1.0;
  1144. result.m[5] = c;
  1145. result.m[10] = c;
  1146. result.m[9] = -s;
  1147. result.m[6] = s;
  1148. result.m[1] = 0;
  1149. result.m[2] = 0;
  1150. result.m[3] = 0;
  1151. result.m[4] = 0;
  1152. result.m[7] = 0;
  1153. result.m[8] = 0;
  1154. result.m[11] = 0;
  1155. result.m[12] = 0;
  1156. result.m[13] = 0;
  1157. result.m[14] = 0;
  1158. };
  1159. Matrix.RotationY = function (angle) {
  1160. var result = new Matrix();
  1161. Matrix.RotationYToRef(angle, result);
  1162. return result;
  1163. };
  1164. Matrix.RotationYToRef = function (angle, result) {
  1165. var s = Math.sin(angle);
  1166. var c = Math.cos(angle);
  1167. result.m[5] = 1.0;
  1168. result.m[15] = 1.0;
  1169. result.m[0] = c;
  1170. result.m[2] = -s;
  1171. result.m[8] = s;
  1172. result.m[10] = c;
  1173. result.m[1] = 0;
  1174. result.m[3] = 0;
  1175. result.m[4] = 0;
  1176. result.m[6] = 0;
  1177. result.m[7] = 0;
  1178. result.m[9] = 0;
  1179. result.m[11] = 0;
  1180. result.m[12] = 0;
  1181. result.m[13] = 0;
  1182. result.m[14] = 0;
  1183. };
  1184. Matrix.RotationZ = function (angle) {
  1185. var result = new Matrix();
  1186. Matrix.RotationZToRef(angle, result);
  1187. return result;
  1188. };
  1189. Matrix.RotationZToRef = function (angle, result) {
  1190. var s = Math.sin(angle);
  1191. var c = Math.cos(angle);
  1192. result.m[10] = 1.0;
  1193. result.m[15] = 1.0;
  1194. result.m[0] = c;
  1195. result.m[1] = s;
  1196. result.m[4] = -s;
  1197. result.m[5] = c;
  1198. result.m[2] = 0;
  1199. result.m[3] = 0;
  1200. result.m[6] = 0;
  1201. result.m[7] = 0;
  1202. result.m[8] = 0;
  1203. result.m[9] = 0;
  1204. result.m[11] = 0;
  1205. result.m[12] = 0;
  1206. result.m[13] = 0;
  1207. result.m[14] = 0;
  1208. };
  1209. Matrix.RotationAxis = function (axis, angle) {
  1210. var s = Math.sin(-angle);
  1211. var c = Math.cos(-angle);
  1212. var c1 = 1 - c;
  1213. axis.normalize();
  1214. var result = Matrix.Zero();
  1215. result.m[0] = (axis.x * axis.x) * c1 + c;
  1216. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1217. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1218. result.m[3] = 0.0;
  1219. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1220. result.m[5] = (axis.y * axis.y) * c1 + c;
  1221. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1222. result.m[7] = 0.0;
  1223. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1224. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1225. result.m[10] = (axis.z * axis.z) * c1 + c;
  1226. result.m[11] = 0.0;
  1227. result.m[15] = 1.0;
  1228. return result;
  1229. };
  1230. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1231. var result = new Matrix();
  1232. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1233. return result;
  1234. };
  1235. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1236. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1237. this._tempQuaternion.toRotationMatrix(result);
  1238. };
  1239. Matrix.Scaling = function (x, y, z) {
  1240. var result = Matrix.Zero();
  1241. Matrix.ScalingToRef(x, y, z, result);
  1242. return result;
  1243. };
  1244. Matrix.ScalingToRef = function (x, y, z, result) {
  1245. result.m[0] = x;
  1246. result.m[1] = 0;
  1247. result.m[2] = 0;
  1248. result.m[3] = 0;
  1249. result.m[4] = 0;
  1250. result.m[5] = y;
  1251. result.m[6] = 0;
  1252. result.m[7] = 0;
  1253. result.m[8] = 0;
  1254. result.m[9] = 0;
  1255. result.m[10] = z;
  1256. result.m[11] = 0;
  1257. result.m[12] = 0;
  1258. result.m[13] = 0;
  1259. result.m[14] = 0;
  1260. result.m[15] = 1.0;
  1261. };
  1262. Matrix.Translation = function (x, y, z) {
  1263. var result = Matrix.Identity();
  1264. Matrix.TranslationToRef(x, y, z, result);
  1265. return result;
  1266. };
  1267. Matrix.TranslationToRef = function (x, y, z, result) {
  1268. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1269. };
  1270. Matrix.LookAtLH = function (eye, target, up) {
  1271. var result = Matrix.Zero();
  1272. Matrix.LookAtLHToRef(eye, target, up, result);
  1273. return result;
  1274. };
  1275. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1276. target.subtractToRef(eye, this._zAxis);
  1277. this._zAxis.normalize();
  1278. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1279. this._xAxis.normalize();
  1280. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1281. this._yAxis.normalize();
  1282. var ex = -Vector3.Dot(this._xAxis, eye);
  1283. var ey = -Vector3.Dot(this._yAxis, eye);
  1284. var ez = -Vector3.Dot(this._zAxis, eye);
  1285. 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);
  1286. };
  1287. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1288. var hw = 2.0 / width;
  1289. var hh = 2.0 / height;
  1290. var id = 1.0 / (zfar - znear);
  1291. var nid = znear / (znear - zfar);
  1292. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1293. };
  1294. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1295. var matrix = Matrix.Zero();
  1296. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1297. return matrix;
  1298. };
  1299. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1300. result.m[0] = 2.0 / (right - left);
  1301. result.m[1] = result.m[2] = result.m[3] = 0;
  1302. result.m[5] = 2.0 / (top - bottom);
  1303. result.m[4] = result.m[6] = result.m[7] = 0;
  1304. result.m[10] = -1.0 / (znear - zfar);
  1305. result.m[8] = result.m[9] = result.m[11] = 0;
  1306. result.m[12] = (left + right) / (left - right);
  1307. result.m[13] = (top + bottom) / (bottom - top);
  1308. result.m[14] = znear / (znear - zfar);
  1309. result.m[15] = 1.0;
  1310. };
  1311. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1312. var matrix = Matrix.Zero();
  1313. matrix.m[0] = (2.0 * znear) / width;
  1314. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1315. matrix.m[5] = (2.0 * znear) / height;
  1316. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1317. matrix.m[10] = -zfar / (znear - zfar);
  1318. matrix.m[8] = matrix.m[9] = 0.0;
  1319. matrix.m[11] = 1.0;
  1320. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1321. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1322. return matrix;
  1323. };
  1324. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1325. var matrix = Matrix.Zero();
  1326. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1327. return matrix;
  1328. };
  1329. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1330. var tan = 1.0 / (Math.tan(fov * 0.5));
  1331. result.m[0] = tan / aspect;
  1332. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1333. result.m[5] = tan;
  1334. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1335. result.m[8] = result.m[9] = 0.0;
  1336. result.m[10] = -zfar / (znear - zfar);
  1337. result.m[11] = 1.0;
  1338. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1339. result.m[14] = (znear * zfar) / (znear - zfar);
  1340. };
  1341. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1342. var cw = viewport.width;
  1343. var ch = viewport.height;
  1344. var cx = viewport.x;
  1345. var cy = viewport.y;
  1346. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  1347. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1348. };
  1349. Matrix.Transpose = function (matrix) {
  1350. var result = new Matrix();
  1351. result.m[0] = matrix.m[0];
  1352. result.m[1] = matrix.m[4];
  1353. result.m[2] = matrix.m[8];
  1354. result.m[3] = matrix.m[12];
  1355. result.m[4] = matrix.m[1];
  1356. result.m[5] = matrix.m[5];
  1357. result.m[6] = matrix.m[9];
  1358. result.m[7] = matrix.m[13];
  1359. result.m[8] = matrix.m[2];
  1360. result.m[9] = matrix.m[6];
  1361. result.m[10] = matrix.m[10];
  1362. result.m[11] = matrix.m[14];
  1363. result.m[12] = matrix.m[3];
  1364. result.m[13] = matrix.m[7];
  1365. result.m[14] = matrix.m[11];
  1366. result.m[15] = matrix.m[15];
  1367. return result;
  1368. };
  1369. Matrix.Reflection = function (plane) {
  1370. var matrix = new Matrix();
  1371. Matrix.ReflectionToRef(plane, matrix);
  1372. return matrix;
  1373. };
  1374. Matrix.ReflectionToRef = function (plane, result) {
  1375. plane.normalize();
  1376. var x = plane.normal.x;
  1377. var y = plane.normal.y;
  1378. var z = plane.normal.z;
  1379. var temp = -2 * x;
  1380. var temp2 = -2 * y;
  1381. var temp3 = -2 * z;
  1382. result.m[0] = (temp * x) + 1;
  1383. result.m[1] = temp2 * x;
  1384. result.m[2] = temp3 * x;
  1385. result.m[3] = 0.0;
  1386. result.m[4] = temp * y;
  1387. result.m[5] = (temp2 * y) + 1;
  1388. result.m[6] = temp3 * y;
  1389. result.m[7] = 0.0;
  1390. result.m[8] = temp * z;
  1391. result.m[9] = temp2 * z;
  1392. result.m[10] = (temp3 * z) + 1;
  1393. result.m[11] = 0.0;
  1394. result.m[12] = temp * plane.d;
  1395. result.m[13] = temp2 * plane.d;
  1396. result.m[14] = temp3 * plane.d;
  1397. result.m[15] = 1.0;
  1398. };
  1399. Matrix._tempQuaternion = new Quaternion();
  1400. Matrix._xAxis = Vector3.Zero();
  1401. Matrix._yAxis = Vector3.Zero();
  1402. Matrix._zAxis = Vector3.Zero();
  1403. return Matrix;
  1404. })();
  1405. BABYLON.Matrix = Matrix;
  1406. var Plane = (function () {
  1407. function Plane(a, b, c, d) {
  1408. this.normal = new Vector3(a, b, c);
  1409. this.d = d;
  1410. }
  1411. Plane.prototype.asArray = function () {
  1412. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1413. };
  1414. Plane.prototype.clone = function () {
  1415. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1416. };
  1417. Plane.prototype.normalize = function () {
  1418. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1419. var magnitude = 0;
  1420. if (norm != 0) {
  1421. magnitude = 1.0 / norm;
  1422. }
  1423. this.normal.x *= magnitude;
  1424. this.normal.y *= magnitude;
  1425. this.normal.z *= magnitude;
  1426. this.d *= magnitude;
  1427. };
  1428. Plane.prototype.transform = function (transformation) {
  1429. var transposedMatrix = BABYLON.Matrix.Transpose(transformation);
  1430. var x = this.normal.x;
  1431. var y = this.normal.y;
  1432. var z = this.normal.z;
  1433. var d = this.d;
  1434. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1435. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1436. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1437. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1438. return new BABYLON.Plane(normalX, normalY, normalZ, finalD);
  1439. };
  1440. Plane.prototype.dotCoordinate = function (point) {
  1441. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1442. };
  1443. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1444. var x1 = point2.x - point1.x;
  1445. var y1 = point2.y - point1.y;
  1446. var z1 = point2.z - point1.z;
  1447. var x2 = point3.x - point1.x;
  1448. var y2 = point3.y - point1.y;
  1449. var z2 = point3.z - point1.z;
  1450. var yz = (y1 * z2) - (z1 * y2);
  1451. var xz = (z1 * x2) - (x1 * z2);
  1452. var xy = (x1 * y2) - (y1 * x2);
  1453. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1454. var invPyth;
  1455. if (pyth != 0) {
  1456. invPyth = 1.0 / pyth;
  1457. } else {
  1458. invPyth = 0;
  1459. }
  1460. this.normal.x = yz * invPyth;
  1461. this.normal.y = xz * invPyth;
  1462. this.normal.z = xy * invPyth;
  1463. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1464. };
  1465. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1466. var dot = Vector3.Dot(this.normal, direction);
  1467. return (dot <= epsilon);
  1468. };
  1469. Plane.prototype.signedDistanceTo = function (point) {
  1470. return Vector3.Dot(point, this.normal) + this.d;
  1471. };
  1472. Plane.FromArray = function (array) {
  1473. return new BABYLON.Plane(array[0], array[1], array[2], array[3]);
  1474. };
  1475. Plane.FromPoints = function (point1, point2, point3) {
  1476. var result = new BABYLON.Plane(0, 0, 0, 0);
  1477. result.copyFromPoints(point1, point2, point3);
  1478. return result;
  1479. };
  1480. Plane.FromPositionAndNormal = function (origin, normal) {
  1481. var result = new BABYLON.Plane(0, 0, 0, 0);
  1482. normal.normalize();
  1483. result.normal = normal;
  1484. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1485. return result;
  1486. };
  1487. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1488. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1489. return Vector3.Dot(point, normal) + d;
  1490. };
  1491. return Plane;
  1492. })();
  1493. BABYLON.Plane = Plane;
  1494. var Viewport = (function () {
  1495. function Viewport(x, y, width, height) {
  1496. this.x = x;
  1497. this.y = y;
  1498. this.width = width;
  1499. this.height = height;
  1500. }
  1501. Viewport.prototype.toGlobal = function (engine) {
  1502. var width = engine.getRenderWidth();
  1503. var height = engine.getRenderHeight();
  1504. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1505. };
  1506. return Viewport;
  1507. })();
  1508. BABYLON.Viewport = Viewport;
  1509. var Frustum = (function () {
  1510. function Frustum() {
  1511. }
  1512. Frustum.GetPlanes = function (transform) {
  1513. var frustumPlanes = [];
  1514. for (var index = 0; index < 6; index++) {
  1515. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1516. }
  1517. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1518. return frustumPlanes;
  1519. };
  1520. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1521. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1522. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1523. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1524. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1525. frustumPlanes[0].normalize();
  1526. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1527. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1528. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1529. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1530. frustumPlanes[1].normalize();
  1531. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1532. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1533. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1534. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1535. frustumPlanes[2].normalize();
  1536. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1537. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1538. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1539. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1540. frustumPlanes[3].normalize();
  1541. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1542. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1543. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1544. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1545. frustumPlanes[4].normalize();
  1546. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1547. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1548. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1549. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1550. frustumPlanes[5].normalize();
  1551. };
  1552. return Frustum;
  1553. })();
  1554. BABYLON.Frustum = Frustum;
  1555. var Ray = (function () {
  1556. function Ray(origin, direction) {
  1557. this.origin = origin;
  1558. this.direction = direction;
  1559. }
  1560. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1561. var d = 0.0;
  1562. var maxValue = Number.MAX_VALUE;
  1563. if (Math.abs(this.direction.x) < 0.0000001) {
  1564. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1565. return false;
  1566. }
  1567. } else {
  1568. var inv = 1.0 / this.direction.x;
  1569. var min = (minimum.x - this.origin.x) * inv;
  1570. var max = (maximum.x - this.origin.x) * inv;
  1571. if (min > max) {
  1572. var temp = min;
  1573. min = max;
  1574. max = temp;
  1575. }
  1576. d = Math.max(min, d);
  1577. maxValue = Math.min(max, maxValue);
  1578. if (d > maxValue) {
  1579. return false;
  1580. }
  1581. }
  1582. if (Math.abs(this.direction.y) < 0.0000001) {
  1583. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1584. return false;
  1585. }
  1586. } else {
  1587. inv = 1.0 / this.direction.y;
  1588. min = (minimum.y - this.origin.y) * inv;
  1589. max = (maximum.y - this.origin.y) * inv;
  1590. if (min > max) {
  1591. temp = min;
  1592. min = max;
  1593. max = temp;
  1594. }
  1595. d = Math.max(min, d);
  1596. maxValue = Math.min(max, maxValue);
  1597. if (d > maxValue) {
  1598. return false;
  1599. }
  1600. }
  1601. if (Math.abs(this.direction.z) < 0.0000001) {
  1602. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1603. return false;
  1604. }
  1605. } else {
  1606. inv = 1.0 / this.direction.z;
  1607. min = (minimum.z - this.origin.z) * inv;
  1608. max = (maximum.z - this.origin.z) * inv;
  1609. if (min > max) {
  1610. temp = min;
  1611. min = max;
  1612. max = temp;
  1613. }
  1614. d = Math.max(min, d);
  1615. maxValue = Math.min(max, maxValue);
  1616. if (d > maxValue) {
  1617. return false;
  1618. }
  1619. }
  1620. return true;
  1621. };
  1622. Ray.prototype.intersectsBox = function (box) {
  1623. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1624. };
  1625. Ray.prototype.intersectsSphere = function (sphere) {
  1626. var x = sphere.center.x - this.origin.x;
  1627. var y = sphere.center.y - this.origin.y;
  1628. var z = sphere.center.z - this.origin.z;
  1629. var pyth = (x * x) + (y * y) + (z * z);
  1630. var rr = sphere.radius * sphere.radius;
  1631. if (pyth <= rr) {
  1632. return true;
  1633. }
  1634. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1635. if (dot < 0.0) {
  1636. return false;
  1637. }
  1638. var temp = pyth - (dot * dot);
  1639. return temp <= rr;
  1640. };
  1641. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1642. if (!this._edge1) {
  1643. this._edge1 = BABYLON.Vector3.Zero();
  1644. this._edge2 = BABYLON.Vector3.Zero();
  1645. this._pvec = BABYLON.Vector3.Zero();
  1646. this._tvec = BABYLON.Vector3.Zero();
  1647. this._qvec = BABYLON.Vector3.Zero();
  1648. }
  1649. vertex1.subtractToRef(vertex0, this._edge1);
  1650. vertex2.subtractToRef(vertex0, this._edge2);
  1651. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1652. var det = Vector3.Dot(this._edge1, this._pvec);
  1653. if (det === 0) {
  1654. return null;
  1655. }
  1656. var invdet = 1 / det;
  1657. this.origin.subtractToRef(vertex0, this._tvec);
  1658. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1659. if (bu < 0 || bu > 1.0) {
  1660. return null;
  1661. }
  1662. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1663. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1664. if (bv < 0 || bu + bv > 1.0) {
  1665. return null;
  1666. }
  1667. return new BABYLON.IntersectionInfo(bu, bv, Vector3.Dot(this._edge2, this._qvec) * invdet);
  1668. };
  1669. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1670. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1671. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1672. var direction = end.subtract(start);
  1673. direction.normalize();
  1674. return new Ray(start, direction);
  1675. };
  1676. Ray.Transform = function (ray, matrix) {
  1677. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  1678. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  1679. return new Ray(newOrigin, newDirection);
  1680. };
  1681. return Ray;
  1682. })();
  1683. BABYLON.Ray = Ray;
  1684. (function (Space) {
  1685. Space[Space["LOCAL"] = 0] = "LOCAL";
  1686. Space[Space["WORLD"] = 1] = "WORLD";
  1687. })(BABYLON.Space || (BABYLON.Space = {}));
  1688. var Space = BABYLON.Space;
  1689. var Axis = (function () {
  1690. function Axis() {
  1691. }
  1692. Axis.X = new BABYLON.Vector3(1, 0, 0);
  1693. Axis.Y = new BABYLON.Vector3(0, 1, 0);
  1694. Axis.Z = new BABYLON.Vector3(0, 0, 1);
  1695. return Axis;
  1696. })();
  1697. BABYLON.Axis = Axis;
  1698. ;
  1699. })(BABYLON || (BABYLON = {}));
  1700. var BABYLON;
  1701. (function (BABYLON) {
  1702. var screenshotCanvas;
  1703. var fpsRange = 60;
  1704. var previousFramesDuration = [];
  1705. var fps = 60;
  1706. var deltaTime = 0;
  1707. var cloneValue = function (source, destinationObject) {
  1708. if (!source)
  1709. return null;
  1710. if (source instanceof BABYLON.Mesh) {
  1711. return null;
  1712. }
  1713. if (source instanceof BABYLON.SubMesh) {
  1714. return source.clone(destinationObject);
  1715. } else if (source.clone) {
  1716. return source.clone();
  1717. }
  1718. return null;
  1719. };
  1720. var Tools = (function () {
  1721. function Tools() {
  1722. }
  1723. Tools.GetFilename = function (path) {
  1724. var index = path.lastIndexOf("/");
  1725. if (index < 0)
  1726. return path;
  1727. return path.substring(index + 1);
  1728. };
  1729. Tools.GetDOMTextContent = function (element) {
  1730. var result = "";
  1731. var child = element.firstChild;
  1732. while (child) {
  1733. if (child.nodeType == 3) {
  1734. result += child.textContent;
  1735. }
  1736. child = child.nextSibling;
  1737. }
  1738. return result;
  1739. };
  1740. Tools.ToDegrees = function (angle) {
  1741. return angle * 180 / Math.PI;
  1742. };
  1743. Tools.ToRadians = function (angle) {
  1744. return angle * Math.PI / 180;
  1745. };
  1746. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  1747. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1748. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1749. for (var index = indexStart; index < indexStart + indexCount; index++) {
  1750. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  1751. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1752. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1753. }
  1754. return {
  1755. minimum: minimum,
  1756. maximum: maximum
  1757. };
  1758. };
  1759. Tools.ExtractMinAndMax = function (positions, start, count) {
  1760. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1761. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1762. for (var index = start; index < start + count; index++) {
  1763. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  1764. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1765. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1766. }
  1767. return {
  1768. minimum: minimum,
  1769. maximum: maximum
  1770. };
  1771. };
  1772. Tools.MakeArray = function (obj, allowsNullUndefined) {
  1773. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  1774. return undefined;
  1775. return Array.isArray(obj) ? obj : [obj];
  1776. };
  1777. Tools.GetPointerPrefix = function () {
  1778. var eventPrefix = "pointer";
  1779. if (!navigator.pointerEnabled) {
  1780. eventPrefix = "mouse";
  1781. }
  1782. return eventPrefix;
  1783. };
  1784. Tools.QueueNewFrame = function (func) {
  1785. if (window.requestAnimationFrame)
  1786. window.requestAnimationFrame(func);
  1787. else if (window.msRequestAnimationFrame)
  1788. window.msRequestAnimationFrame(func);
  1789. else if (window.webkitRequestAnimationFrame)
  1790. window.webkitRequestAnimationFrame(func);
  1791. else if (window.mozRequestAnimationFrame)
  1792. window.mozRequestAnimationFrame(func);
  1793. else if (window.oRequestAnimationFrame)
  1794. window.oRequestAnimationFrame(func);
  1795. else {
  1796. window.setTimeout(func, 16);
  1797. }
  1798. };
  1799. Tools.RequestFullscreen = function (element) {
  1800. if (element.requestFullscreen)
  1801. element.requestFullscreen();
  1802. else if (element.msRequestFullscreen)
  1803. element.msRequestFullscreen();
  1804. else if (element.webkitRequestFullscreen)
  1805. element.webkitRequestFullscreen();
  1806. else if (element.mozRequestFullScreen)
  1807. element.mozRequestFullScreen();
  1808. };
  1809. Tools.ExitFullscreen = function () {
  1810. if (document.exitFullscreen) {
  1811. document.exitFullscreen();
  1812. } else if (document.mozCancelFullScreen) {
  1813. document.mozCancelFullScreen();
  1814. } else if (document.webkitCancelFullScreen) {
  1815. document.webkitCancelFullScreen();
  1816. } else if (document.msCancelFullScreen) {
  1817. document.msCancelFullScreen();
  1818. }
  1819. };
  1820. Tools.CleanUrl = function (url) {
  1821. url = url.replace(/#/mg, "%23");
  1822. return url;
  1823. };
  1824. Tools.LoadImage = function (url, onload, onerror, database) {
  1825. url = Tools.CleanUrl(url);
  1826. var img = new Image();
  1827. img.crossOrigin = 'anonymous';
  1828. img.onload = function () {
  1829. onload(img);
  1830. };
  1831. img.onerror = function (err) {
  1832. onerror(img, err);
  1833. };
  1834. var noIndexedDB = function () {
  1835. img.src = url;
  1836. };
  1837. var loadFromIndexedDB = function () {
  1838. database.loadImageFromDB(url, img);
  1839. };
  1840. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  1841. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1842. } else {
  1843. if (url.indexOf("file:") === -1) {
  1844. noIndexedDB();
  1845. } else {
  1846. try {
  1847. var textureName = url.substring(5);
  1848. var blobURL;
  1849. try {
  1850. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  1851. } catch (ex) {
  1852. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  1853. }
  1854. img.src = blobURL;
  1855. } catch (e) {
  1856. Tools.Log("Error while trying to load texture: " + textureName);
  1857. img.src = null;
  1858. }
  1859. }
  1860. }
  1861. return img;
  1862. };
  1863. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  1864. url = Tools.CleanUrl(url);
  1865. var noIndexedDB = function () {
  1866. var request = new XMLHttpRequest();
  1867. var loadUrl = Tools.BaseUrl + url;
  1868. request.open('GET', loadUrl, true);
  1869. if (useArrayBuffer) {
  1870. request.responseType = "arraybuffer";
  1871. }
  1872. request.onprogress = progressCallBack;
  1873. request.onreadystatechange = function () {
  1874. if (request.readyState == 4) {
  1875. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  1876. callback(!useArrayBuffer ? request.responseText : request.response);
  1877. } else {
  1878. if (onError) {
  1879. onError();
  1880. } else {
  1881. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  1882. }
  1883. }
  1884. }
  1885. };
  1886. request.send(null);
  1887. };
  1888. var loadFromIndexedDB = function () {
  1889. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  1890. };
  1891. if (url.indexOf("file:") !== -1) {
  1892. var fileName = url.substring(5);
  1893. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  1894. } else {
  1895. if (database && database.enableSceneOffline) {
  1896. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1897. } else {
  1898. noIndexedDB();
  1899. }
  1900. }
  1901. };
  1902. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  1903. var reader = new FileReader();
  1904. reader.onload = function (e) {
  1905. callback(e.target.result);
  1906. };
  1907. reader.onprogress = progressCallBack;
  1908. if (!useArrayBuffer) {
  1909. reader.readAsText(fileToLoad);
  1910. } else {
  1911. reader.readAsArrayBuffer(fileToLoad);
  1912. }
  1913. };
  1914. Tools.CheckExtends = function (v, min, max) {
  1915. if (v.x < min.x)
  1916. min.x = v.x;
  1917. if (v.y < min.y)
  1918. min.y = v.y;
  1919. if (v.z < min.z)
  1920. min.z = v.z;
  1921. if (v.x > max.x)
  1922. max.x = v.x;
  1923. if (v.y > max.y)
  1924. max.y = v.y;
  1925. if (v.z > max.z)
  1926. max.z = v.z;
  1927. };
  1928. Tools.WithinEpsilon = function (a, b) {
  1929. var num = a - b;
  1930. return -1.401298E-45 <= num && num <= 1.401298E-45;
  1931. };
  1932. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  1933. for (var prop in source) {
  1934. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  1935. continue;
  1936. }
  1937. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  1938. continue;
  1939. }
  1940. var sourceValue = source[prop];
  1941. var typeOfSourceValue = typeof sourceValue;
  1942. if (typeOfSourceValue == "function") {
  1943. continue;
  1944. }
  1945. if (typeOfSourceValue == "object") {
  1946. if (sourceValue instanceof Array) {
  1947. destination[prop] = [];
  1948. if (sourceValue.length > 0) {
  1949. if (typeof sourceValue[0] == "object") {
  1950. for (var index = 0; index < sourceValue.length; index++) {
  1951. var clonedValue = cloneValue(sourceValue[index], destination);
  1952. if (destination[prop].indexOf(clonedValue) === -1) {
  1953. destination[prop].push(clonedValue);
  1954. }
  1955. }
  1956. } else {
  1957. destination[prop] = sourceValue.slice(0);
  1958. }
  1959. }
  1960. } else {
  1961. destination[prop] = cloneValue(sourceValue, destination);
  1962. }
  1963. } else {
  1964. destination[prop] = sourceValue;
  1965. }
  1966. }
  1967. };
  1968. Tools.IsEmpty = function (obj) {
  1969. for (var i in obj) {
  1970. return false;
  1971. }
  1972. return true;
  1973. };
  1974. Tools.RegisterTopRootEvents = function (events) {
  1975. for (var index = 0; index < events.length; index++) {
  1976. var event = events[index];
  1977. window.addEventListener(event.name, event.handler, false);
  1978. try {
  1979. if (window.parent) {
  1980. window.parent.addEventListener(event.name, event.handler, false);
  1981. }
  1982. } catch (e) {
  1983. }
  1984. }
  1985. };
  1986. Tools.UnregisterTopRootEvents = function (events) {
  1987. for (var index = 0; index < events.length; index++) {
  1988. var event = events[index];
  1989. window.removeEventListener(event.name, event.handler);
  1990. try {
  1991. if (window.parent) {
  1992. window.parent.removeEventListener(event.name, event.handler);
  1993. }
  1994. } catch (e) {
  1995. }
  1996. }
  1997. };
  1998. Tools.GetFps = function () {
  1999. return fps;
  2000. };
  2001. Tools.GetDeltaTime = function () {
  2002. return deltaTime;
  2003. };
  2004. Tools._MeasureFps = function () {
  2005. previousFramesDuration.push((new Date).getTime());
  2006. var length = previousFramesDuration.length;
  2007. if (length >= 2) {
  2008. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  2009. }
  2010. if (length >= fpsRange) {
  2011. if (length > fpsRange) {
  2012. previousFramesDuration.splice(0, 1);
  2013. length = previousFramesDuration.length;
  2014. }
  2015. var sum = 0;
  2016. for (var id = 0; id < length - 1; id++) {
  2017. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  2018. }
  2019. fps = 1000.0 / (sum / (length - 1));
  2020. }
  2021. };
  2022. Tools.CreateScreenshot = function (engine, camera, size) {
  2023. var width;
  2024. var height;
  2025. var scene = camera.getScene();
  2026. var previousCamera = null;
  2027. if (scene.activeCamera !== camera) {
  2028. previousCamera = scene.activeCamera;
  2029. scene.activeCamera = camera;
  2030. }
  2031. if (size.precision) {
  2032. width = Math.round(engine.getRenderWidth() * size.precision);
  2033. height = Math.round(width / engine.getAspectRatio(camera));
  2034. size = { width: width, height: height };
  2035. } else if (size.width && size.height) {
  2036. width = size.width;
  2037. height = size.height;
  2038. } else if (size.width && !size.height) {
  2039. width = size.width;
  2040. height = Math.round(width / engine.getAspectRatio(camera));
  2041. size = { width: width, height: height };
  2042. } else if (size.height && !size.width) {
  2043. height = size.height;
  2044. width = Math.round(height * engine.getAspectRatio(camera));
  2045. size = { width: width, height: height };
  2046. } else if (!isNaN(size)) {
  2047. height = size;
  2048. width = size;
  2049. } else {
  2050. Tools.Error("Invalid 'size' parameter !");
  2051. return;
  2052. }
  2053. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2054. texture.renderList = engine.scenes[0].meshes;
  2055. texture.onAfterRender = function () {
  2056. var numberOfChannelsByLine = width * 4;
  2057. var halfHeight = height / 2;
  2058. var data = engine.readPixels(0, 0, width, height);
  2059. for (var i = 0; i < halfHeight; i++) {
  2060. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2061. var currentCell = j + i * numberOfChannelsByLine;
  2062. var targetLine = height - i - 1;
  2063. var targetCell = j + targetLine * numberOfChannelsByLine;
  2064. var temp = data[currentCell];
  2065. data[currentCell] = data[targetCell];
  2066. data[targetCell] = temp;
  2067. }
  2068. }
  2069. if (!screenshotCanvas) {
  2070. screenshotCanvas = document.createElement('canvas');
  2071. }
  2072. screenshotCanvas.width = width;
  2073. screenshotCanvas.height = height;
  2074. var context = screenshotCanvas.getContext('2d');
  2075. var imageData = context.createImageData(width, height);
  2076. imageData.data.set(data);
  2077. context.putImageData(imageData, 0, 0);
  2078. var base64Image = screenshotCanvas.toDataURL();
  2079. if (("download" in document.createElement("a"))) {
  2080. var a = window.document.createElement("a");
  2081. a.href = base64Image;
  2082. var date = new Date();
  2083. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2084. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2085. window.document.body.appendChild(a);
  2086. a.addEventListener("click", function () {
  2087. a.parentElement.removeChild(a);
  2088. });
  2089. a.click();
  2090. } else {
  2091. var newWindow = window.open("");
  2092. var img = newWindow.document.createElement("img");
  2093. img.src = base64Image;
  2094. newWindow.document.body.appendChild(img);
  2095. }
  2096. };
  2097. texture.render(true);
  2098. texture.dispose();
  2099. if (previousCamera) {
  2100. scene.activeCamera = previousCamera;
  2101. }
  2102. };
  2103. Tools.ValidateXHRData = function (xhr, dataType) {
  2104. if (typeof dataType === "undefined") { dataType = 7; }
  2105. try {
  2106. if (dataType & 1) {
  2107. if (xhr.responseText && xhr.responseText.length > 0) {
  2108. return true;
  2109. } else if (dataType === 1) {
  2110. return false;
  2111. }
  2112. }
  2113. if (dataType & 2) {
  2114. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2115. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2116. return true;
  2117. } else if (dataType === 2) {
  2118. return false;
  2119. }
  2120. }
  2121. if (dataType & 4) {
  2122. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2123. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2124. return true;
  2125. } else {
  2126. return false;
  2127. }
  2128. }
  2129. } catch (e) {
  2130. }
  2131. return false;
  2132. };
  2133. Object.defineProperty(Tools, "NoneLogLevel", {
  2134. get: function () {
  2135. return Tools._NoneLogLevel;
  2136. },
  2137. enumerable: true,
  2138. configurable: true
  2139. });
  2140. Object.defineProperty(Tools, "MessageLogLevel", {
  2141. get: function () {
  2142. return Tools._MessageLogLevel;
  2143. },
  2144. enumerable: true,
  2145. configurable: true
  2146. });
  2147. Object.defineProperty(Tools, "WarningLogLevel", {
  2148. get: function () {
  2149. return Tools._WarningLogLevel;
  2150. },
  2151. enumerable: true,
  2152. configurable: true
  2153. });
  2154. Object.defineProperty(Tools, "ErrorLogLevel", {
  2155. get: function () {
  2156. return Tools._ErrorLogLevel;
  2157. },
  2158. enumerable: true,
  2159. configurable: true
  2160. });
  2161. Object.defineProperty(Tools, "AllLogLevel", {
  2162. get: function () {
  2163. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2164. },
  2165. enumerable: true,
  2166. configurable: true
  2167. });
  2168. Tools._FormatMessage = function (message) {
  2169. var padStr = function (i) {
  2170. return (i < 10) ? "0" + i : "" + i;
  2171. };
  2172. var date = new Date();
  2173. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2174. };
  2175. Tools._LogDisabled = function (message) {
  2176. };
  2177. Tools._LogEnabled = function (message) {
  2178. console.log(Tools._FormatMessage(message));
  2179. };
  2180. Tools._WarnDisabled = function (message) {
  2181. };
  2182. Tools._WarnEnabled = function (message) {
  2183. console.warn(Tools._FormatMessage(message));
  2184. };
  2185. Tools._ErrorDisabled = function (message) {
  2186. };
  2187. Tools._ErrorEnabled = function (message) {
  2188. console.error(Tools._FormatMessage(message));
  2189. };
  2190. Object.defineProperty(Tools, "LogLevels", {
  2191. set: function (level) {
  2192. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2193. Tools.Log = Tools._LogEnabled;
  2194. } else {
  2195. Tools.Log = Tools._LogDisabled;
  2196. }
  2197. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2198. Tools.Warn = Tools._WarnEnabled;
  2199. } else {
  2200. Tools.Warn = Tools._WarnDisabled;
  2201. }
  2202. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2203. Tools.Error = Tools._ErrorEnabled;
  2204. } else {
  2205. Tools.Error = Tools._ErrorDisabled;
  2206. }
  2207. },
  2208. enumerable: true,
  2209. configurable: true
  2210. });
  2211. Tools.BaseUrl = "";
  2212. Tools._NoneLogLevel = 0;
  2213. Tools._MessageLogLevel = 1;
  2214. Tools._WarningLogLevel = 2;
  2215. Tools._ErrorLogLevel = 4;
  2216. Tools.Log = Tools._LogEnabled;
  2217. Tools.Warn = Tools._WarnEnabled;
  2218. Tools.Error = Tools._ErrorEnabled;
  2219. return Tools;
  2220. })();
  2221. BABYLON.Tools = Tools;
  2222. })(BABYLON || (BABYLON = {}));
  2223. var BABYLON;
  2224. (function (BABYLON) {
  2225. var _DepthCullingState = (function () {
  2226. function _DepthCullingState() {
  2227. this._isDepthTestDirty = false;
  2228. this._isDepthMaskDirty = false;
  2229. this._isDepthFuncDirty = false;
  2230. this._isCullFaceDirty = false;
  2231. this._isCullDirty = false;
  2232. }
  2233. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2234. get: function () {
  2235. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2236. },
  2237. enumerable: true,
  2238. configurable: true
  2239. });
  2240. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2241. get: function () {
  2242. return this._cullFace;
  2243. },
  2244. set: function (value) {
  2245. if (this._cullFace === value) {
  2246. return;
  2247. }
  2248. this._cullFace = value;
  2249. this._isCullFaceDirty = true;
  2250. },
  2251. enumerable: true,
  2252. configurable: true
  2253. });
  2254. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2255. get: function () {
  2256. return this._cull;
  2257. },
  2258. set: function (value) {
  2259. if (this._cull === value) {
  2260. return;
  2261. }
  2262. this._cull = value;
  2263. this._isCullDirty = true;
  2264. },
  2265. enumerable: true,
  2266. configurable: true
  2267. });
  2268. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2269. get: function () {
  2270. return this._depthFunc;
  2271. },
  2272. set: function (value) {
  2273. if (this._depthFunc === value) {
  2274. return;
  2275. }
  2276. this._depthFunc = value;
  2277. this._isDepthFuncDirty = true;
  2278. },
  2279. enumerable: true,
  2280. configurable: true
  2281. });
  2282. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2283. get: function () {
  2284. return this._depthMask;
  2285. },
  2286. set: function (value) {
  2287. if (this._depthMask === value) {
  2288. return;
  2289. }
  2290. this._depthMask = value;
  2291. this._isDepthMaskDirty = true;
  2292. },
  2293. enumerable: true,
  2294. configurable: true
  2295. });
  2296. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  2297. get: function () {
  2298. return this._depthTest;
  2299. },
  2300. set: function (value) {
  2301. if (this._depthTest === value) {
  2302. return;
  2303. }
  2304. this._depthTest = value;
  2305. this._isDepthTestDirty = true;
  2306. },
  2307. enumerable: true,
  2308. configurable: true
  2309. });
  2310. _DepthCullingState.prototype.reset = function () {
  2311. this._depthMask = true;
  2312. this._depthTest = true;
  2313. this._depthFunc = null;
  2314. this._cull = null;
  2315. this._cullFace = null;
  2316. this._isDepthTestDirty = true;
  2317. this._isDepthMaskDirty = true;
  2318. this._isDepthFuncDirty = false;
  2319. this._isCullFaceDirty = false;
  2320. this._isCullDirty = false;
  2321. };
  2322. _DepthCullingState.prototype.apply = function (gl) {
  2323. if (!this.isDirty) {
  2324. return;
  2325. }
  2326. if (this._isCullDirty) {
  2327. if (this.cull === true) {
  2328. gl.enable(gl.CULL_FACE);
  2329. } else if (this.cull === false) {
  2330. gl.disable(gl.CULL_FACE);
  2331. }
  2332. this._isCullDirty = false;
  2333. }
  2334. if (this._isCullFaceDirty) {
  2335. gl.cullFace(this.cullFace);
  2336. this._isCullFaceDirty = false;
  2337. }
  2338. if (this._isDepthMaskDirty) {
  2339. gl.depthMask(this.depthMask);
  2340. this._isDepthMaskDirty = false;
  2341. }
  2342. if (this._isDepthTestDirty) {
  2343. if (this.depthTest === true) {
  2344. gl.enable(gl.DEPTH_TEST);
  2345. } else if (this.depthTest === false) {
  2346. gl.disable(gl.DEPTH_TEST);
  2347. }
  2348. this._isDepthTestDirty = false;
  2349. }
  2350. if (this._isDepthFuncDirty) {
  2351. gl.depthFunc(this.depthFunc);
  2352. this._isDepthFuncDirty = false;
  2353. }
  2354. };
  2355. return _DepthCullingState;
  2356. })();
  2357. BABYLON._DepthCullingState = _DepthCullingState;
  2358. var _AlphaState = (function () {
  2359. function _AlphaState() {
  2360. this._isAlphaBlendDirty = false;
  2361. this._isBlendFunctionParametersDirty = false;
  2362. this._alphaBlend = false;
  2363. this._blendFunctionParameters = new Array(4);
  2364. }
  2365. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  2366. get: function () {
  2367. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  2368. },
  2369. enumerable: true,
  2370. configurable: true
  2371. });
  2372. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  2373. get: function () {
  2374. return this._alphaBlend;
  2375. },
  2376. set: function (value) {
  2377. if (this._alphaBlend === value) {
  2378. return;
  2379. }
  2380. this._alphaBlend = value;
  2381. this._isAlphaBlendDirty = true;
  2382. },
  2383. enumerable: true,
  2384. configurable: true
  2385. });
  2386. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  2387. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  2388. return;
  2389. }
  2390. this._blendFunctionParameters[0] = value0;
  2391. this._blendFunctionParameters[1] = value1;
  2392. this._blendFunctionParameters[2] = value2;
  2393. this._blendFunctionParameters[3] = value3;
  2394. this._isBlendFunctionParametersDirty = true;
  2395. };
  2396. _AlphaState.prototype.reset = function () {
  2397. this._alphaBlend = false;
  2398. this._blendFunctionParameters[0] = null;
  2399. this._blendFunctionParameters[1] = null;
  2400. this._blendFunctionParameters[2] = null;
  2401. this._blendFunctionParameters[3] = null;
  2402. this._isAlphaBlendDirty = true;
  2403. this._isBlendFunctionParametersDirty = false;
  2404. };
  2405. _AlphaState.prototype.apply = function (gl) {
  2406. if (!this.isDirty) {
  2407. return;
  2408. }
  2409. if (this._isAlphaBlendDirty) {
  2410. if (this._alphaBlend === true) {
  2411. gl.enable(gl.BLEND);
  2412. } else if (this._alphaBlend === false) {
  2413. gl.disable(gl.BLEND);
  2414. }
  2415. this._isAlphaBlendDirty = false;
  2416. }
  2417. if (this._isBlendFunctionParametersDirty) {
  2418. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  2419. this._isBlendFunctionParametersDirty = false;
  2420. }
  2421. };
  2422. return _AlphaState;
  2423. })();
  2424. BABYLON._AlphaState = _AlphaState;
  2425. var compileShader = function (gl, source, type, defines) {
  2426. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2427. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  2428. gl.compileShader(shader);
  2429. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2430. throw new Error(gl.getShaderInfoLog(shader));
  2431. }
  2432. return shader;
  2433. };
  2434. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  2435. var magFilter = gl.NEAREST;
  2436. var minFilter = gl.NEAREST;
  2437. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  2438. magFilter = gl.LINEAR;
  2439. if (generateMipMaps) {
  2440. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2441. } else {
  2442. minFilter = gl.LINEAR;
  2443. }
  2444. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  2445. magFilter = gl.LINEAR;
  2446. if (generateMipMaps) {
  2447. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2448. } else {
  2449. minFilter = gl.LINEAR;
  2450. }
  2451. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  2452. magFilter = gl.NEAREST;
  2453. if (generateMipMaps) {
  2454. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2455. } else {
  2456. minFilter = gl.NEAREST;
  2457. }
  2458. }
  2459. return {
  2460. min: minFilter,
  2461. mag: magFilter
  2462. };
  2463. };
  2464. var getExponantOfTwo = function (value, max) {
  2465. var count = 1;
  2466. do {
  2467. count *= 2;
  2468. } while(count < value);
  2469. if (count > max)
  2470. count = max;
  2471. return count;
  2472. };
  2473. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  2474. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  2475. var engine = scene.getEngine();
  2476. var potWidth = getExponantOfTwo(width, engine.getCaps().maxTextureSize);
  2477. var potHeight = getExponantOfTwo(height, engine.getCaps().maxTextureSize);
  2478. gl.bindTexture(gl.TEXTURE_2D, texture);
  2479. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2480. processFunction(potWidth, potHeight);
  2481. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  2482. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2483. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2484. if (!noMipmap && !isCompressed) {
  2485. gl.generateMipmap(gl.TEXTURE_2D);
  2486. }
  2487. gl.bindTexture(gl.TEXTURE_2D, null);
  2488. engine._activeTexturesCache = [];
  2489. texture._baseWidth = width;
  2490. texture._baseHeight = height;
  2491. texture._width = potWidth;
  2492. texture._height = potHeight;
  2493. texture.isReady = true;
  2494. scene._removePendingData(texture);
  2495. };
  2496. var cascadeLoad = function (rootUrl, index, loadedImages, scene, onfinish, extensions) {
  2497. var img;
  2498. var onload = function () {
  2499. loadedImages.push(img);
  2500. scene._removePendingData(img);
  2501. if (index != extensions.length - 1) {
  2502. cascadeLoad(rootUrl, index + 1, loadedImages, scene, onfinish, extensions);
  2503. } else {
  2504. onfinish(loadedImages);
  2505. }
  2506. };
  2507. var onerror = function () {
  2508. scene._removePendingData(img);
  2509. };
  2510. img = BABYLON.Tools.LoadImage(rootUrl + extensions[index], onload, onerror, scene.database);
  2511. scene._addPendingData(img);
  2512. };
  2513. var EngineCapabilities = (function () {
  2514. function EngineCapabilities() {
  2515. }
  2516. return EngineCapabilities;
  2517. })();
  2518. BABYLON.EngineCapabilities = EngineCapabilities;
  2519. var Engine = (function () {
  2520. function Engine(canvas, antialias, options) {
  2521. var _this = this;
  2522. this.isFullscreen = false;
  2523. this.isPointerLock = false;
  2524. this.forceWireframe = false;
  2525. this.cullBackFaces = true;
  2526. this.renderEvenInBackground = true;
  2527. this.scenes = new Array();
  2528. this._windowIsBackground = false;
  2529. this._runningLoop = false;
  2530. this._loadingDivBackgroundColor = "black";
  2531. this._depthCullingState = new _DepthCullingState();
  2532. this._alphaState = new _AlphaState();
  2533. this._loadedTexturesCache = new Array();
  2534. this._activeTexturesCache = new Array();
  2535. this._compiledEffects = {};
  2536. this._renderingCanvas = canvas;
  2537. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2538. options = options || {};
  2539. options.antialias = antialias;
  2540. try {
  2541. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  2542. } catch (e) {
  2543. throw new Error("WebGL not supported");
  2544. }
  2545. if (!this._gl) {
  2546. throw new Error("WebGL not supported");
  2547. }
  2548. this._onBlur = function () {
  2549. _this._windowIsBackground = true;
  2550. };
  2551. this._onFocus = function () {
  2552. _this._windowIsBackground = false;
  2553. };
  2554. window.addEventListener("blur", this._onBlur);
  2555. window.addEventListener("focus", this._onFocus);
  2556. this._workingCanvas = document.createElement("canvas");
  2557. this._workingContext = this._workingCanvas.getContext("2d");
  2558. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  2559. this.resize();
  2560. this._caps = new EngineCapabilities();
  2561. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  2562. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  2563. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  2564. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  2565. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  2566. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  2567. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  2568. 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');
  2569. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  2570. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  2571. this.setDepthBuffer(true);
  2572. this.setDepthFunctionToLessOrEqual();
  2573. this.setDepthWrite(true);
  2574. this._onFullscreenChange = function () {
  2575. if (document.fullscreen !== undefined) {
  2576. _this.isFullscreen = document.fullscreen;
  2577. } else if (document.mozFullScreen !== undefined) {
  2578. _this.isFullscreen = document.mozFullScreen;
  2579. } else if (document.webkitIsFullScreen !== undefined) {
  2580. _this.isFullscreen = document.webkitIsFullScreen;
  2581. } else if (document.msIsFullScreen !== undefined) {
  2582. _this.isFullscreen = document.msIsFullScreen;
  2583. }
  2584. if (_this.isFullscreen && _this._pointerLockRequested) {
  2585. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  2586. if (canvas.requestPointerLock) {
  2587. canvas.requestPointerLock();
  2588. }
  2589. }
  2590. };
  2591. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  2592. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  2593. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  2594. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  2595. this._onPointerLockChange = function () {
  2596. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  2597. };
  2598. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  2599. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  2600. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  2601. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  2602. }
  2603. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  2604. get: function () {
  2605. return Engine._ALPHA_DISABLE;
  2606. },
  2607. enumerable: true,
  2608. configurable: true
  2609. });
  2610. Object.defineProperty(Engine, "ALPHA_ADD", {
  2611. get: function () {
  2612. return Engine._ALPHA_ADD;
  2613. },
  2614. enumerable: true,
  2615. configurable: true
  2616. });
  2617. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  2618. get: function () {
  2619. return Engine._ALPHA_COMBINE;
  2620. },
  2621. enumerable: true,
  2622. configurable: true
  2623. });
  2624. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  2625. get: function () {
  2626. return Engine._DELAYLOADSTATE_NONE;
  2627. },
  2628. enumerable: true,
  2629. configurable: true
  2630. });
  2631. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  2632. get: function () {
  2633. return Engine._DELAYLOADSTATE_LOADED;
  2634. },
  2635. enumerable: true,
  2636. configurable: true
  2637. });
  2638. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  2639. get: function () {
  2640. return Engine._DELAYLOADSTATE_LOADING;
  2641. },
  2642. enumerable: true,
  2643. configurable: true
  2644. });
  2645. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  2646. get: function () {
  2647. return Engine._DELAYLOADSTATE_NOTLOADED;
  2648. },
  2649. enumerable: true,
  2650. configurable: true
  2651. });
  2652. Object.defineProperty(Engine, "Version", {
  2653. get: function () {
  2654. return "1.14.0";
  2655. },
  2656. enumerable: true,
  2657. configurable: true
  2658. });
  2659. Engine.prototype.getAspectRatio = function (camera) {
  2660. var viewport = camera.viewport;
  2661. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  2662. };
  2663. Engine.prototype.getRenderWidth = function () {
  2664. if (this._currentRenderTarget) {
  2665. return this._currentRenderTarget._width;
  2666. }
  2667. return this._renderingCanvas.width;
  2668. };
  2669. Engine.prototype.getRenderHeight = function () {
  2670. if (this._currentRenderTarget) {
  2671. return this._currentRenderTarget._height;
  2672. }
  2673. return this._renderingCanvas.height;
  2674. };
  2675. Engine.prototype.getRenderingCanvas = function () {
  2676. return this._renderingCanvas;
  2677. };
  2678. Engine.prototype.getRenderingCanvasClientRect = function () {
  2679. return this._renderingCanvas.getBoundingClientRect();
  2680. };
  2681. Engine.prototype.setHardwareScalingLevel = function (level) {
  2682. this._hardwareScalingLevel = level;
  2683. this.resize();
  2684. };
  2685. Engine.prototype.getHardwareScalingLevel = function () {
  2686. return this._hardwareScalingLevel;
  2687. };
  2688. Engine.prototype.getLoadedTexturesCache = function () {
  2689. return this._loadedTexturesCache;
  2690. };
  2691. Engine.prototype.getCaps = function () {
  2692. return this._caps;
  2693. };
  2694. Engine.prototype.setDepthFunctionToGreater = function () {
  2695. this._depthCullingState.depthFunc = this._gl.GREATER;
  2696. };
  2697. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  2698. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  2699. };
  2700. Engine.prototype.setDepthFunctionToLess = function () {
  2701. this._depthCullingState.depthFunc = this._gl.LESS;
  2702. };
  2703. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  2704. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  2705. };
  2706. Engine.prototype.stopRenderLoop = function () {
  2707. this._renderFunction = null;
  2708. this._runningLoop = false;
  2709. };
  2710. Engine.prototype._renderLoop = function () {
  2711. var _this = this;
  2712. var shouldRender = true;
  2713. if (!this.renderEvenInBackground && this._windowIsBackground) {
  2714. shouldRender = false;
  2715. }
  2716. if (shouldRender) {
  2717. this.beginFrame();
  2718. if (this._renderFunction) {
  2719. this._renderFunction();
  2720. }
  2721. this.endFrame();
  2722. }
  2723. if (this._runningLoop) {
  2724. BABYLON.Tools.QueueNewFrame(function () {
  2725. _this._renderLoop();
  2726. });
  2727. }
  2728. };
  2729. Engine.prototype.runRenderLoop = function (renderFunction) {
  2730. var _this = this;
  2731. this._runningLoop = true;
  2732. this._renderFunction = renderFunction;
  2733. BABYLON.Tools.QueueNewFrame(function () {
  2734. _this._renderLoop();
  2735. });
  2736. };
  2737. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  2738. if (this.isFullscreen) {
  2739. BABYLON.Tools.ExitFullscreen();
  2740. } else {
  2741. this._pointerLockRequested = requestPointerLock;
  2742. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  2743. }
  2744. };
  2745. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  2746. this.applyStates();
  2747. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  2748. if (this._depthCullingState.depthMask) {
  2749. this._gl.clearDepth(1.0);
  2750. }
  2751. var mode = 0;
  2752. if (backBuffer)
  2753. mode |= this._gl.COLOR_BUFFER_BIT;
  2754. if (depthStencil && this._depthCullingState.depthMask)
  2755. mode |= this._gl.DEPTH_BUFFER_BIT;
  2756. this._gl.clear(mode);
  2757. };
  2758. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  2759. var width = requiredWidth || this._renderingCanvas.width;
  2760. var height = requiredHeight || this._renderingCanvas.height;
  2761. var x = viewport.x || 0;
  2762. var y = viewport.y || 0;
  2763. this._cachedViewport = viewport;
  2764. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  2765. };
  2766. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  2767. this._cachedViewport = null;
  2768. this._gl.viewport(x, y, width, height);
  2769. };
  2770. Engine.prototype.beginFrame = function () {
  2771. BABYLON.Tools._MeasureFps();
  2772. };
  2773. Engine.prototype.endFrame = function () {
  2774. this.flushFramebuffer();
  2775. };
  2776. Engine.prototype.resize = function () {
  2777. this._renderingCanvas.width = this._renderingCanvas.clientWidth / this._hardwareScalingLevel;
  2778. this._renderingCanvas.height = this._renderingCanvas.clientHeight / this._hardwareScalingLevel;
  2779. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2780. };
  2781. Engine.prototype.bindFramebuffer = function (texture) {
  2782. this._currentRenderTarget = texture;
  2783. var gl = this._gl;
  2784. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  2785. this._gl.viewport(0, 0, texture._width, texture._height);
  2786. this.wipeCaches();
  2787. };
  2788. Engine.prototype.unBindFramebuffer = function (texture) {
  2789. this._currentRenderTarget = null;
  2790. if (texture.generateMipMaps) {
  2791. var gl = this._gl;
  2792. gl.bindTexture(gl.TEXTURE_2D, texture);
  2793. gl.generateMipmap(gl.TEXTURE_2D);
  2794. gl.bindTexture(gl.TEXTURE_2D, null);
  2795. }
  2796. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2797. };
  2798. Engine.prototype.flushFramebuffer = function () {
  2799. this._gl.flush();
  2800. };
  2801. Engine.prototype.restoreDefaultFramebuffer = function () {
  2802. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2803. this.setViewport(this._cachedViewport);
  2804. this.wipeCaches();
  2805. };
  2806. Engine.prototype._resetVertexBufferBinding = function () {
  2807. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  2808. this._cachedVertexBuffers = null;
  2809. };
  2810. Engine.prototype.createVertexBuffer = function (vertices) {
  2811. var vbo = this._gl.createBuffer();
  2812. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2813. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  2814. this._resetVertexBufferBinding();
  2815. vbo.references = 1;
  2816. return vbo;
  2817. };
  2818. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  2819. var vbo = this._gl.createBuffer();
  2820. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2821. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2822. this._resetVertexBufferBinding();
  2823. vbo.references = 1;
  2824. return vbo;
  2825. };
  2826. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, length) {
  2827. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2828. if (vertices instanceof Float32Array) {
  2829. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  2830. } else {
  2831. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  2832. }
  2833. this._resetVertexBufferBinding();
  2834. };
  2835. Engine.prototype._resetIndexBufferBinding = function () {
  2836. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  2837. this._cachedIndexBuffer = null;
  2838. };
  2839. Engine.prototype.createIndexBuffer = function (indices) {
  2840. var vbo = this._gl.createBuffer();
  2841. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  2842. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  2843. this._resetIndexBufferBinding();
  2844. vbo.references = 1;
  2845. return vbo;
  2846. };
  2847. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  2848. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  2849. this._cachedVertexBuffers = vertexBuffer;
  2850. this._cachedEffectForVertexBuffers = effect;
  2851. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2852. var offset = 0;
  2853. for (var index = 0; index < vertexDeclaration.length; index++) {
  2854. var order = effect.getAttributeLocation(index);
  2855. if (order >= 0) {
  2856. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  2857. }
  2858. offset += vertexDeclaration[index] * 4;
  2859. }
  2860. }
  2861. if (this._cachedIndexBuffer !== indexBuffer) {
  2862. this._cachedIndexBuffer = indexBuffer;
  2863. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  2864. }
  2865. };
  2866. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  2867. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  2868. this._cachedVertexBuffers = vertexBuffers;
  2869. this._cachedEffectForVertexBuffers = effect;
  2870. var attributes = effect.getAttributesNames();
  2871. for (var index = 0; index < attributes.length; index++) {
  2872. var order = effect.getAttributeLocation(index);
  2873. if (order >= 0) {
  2874. var vertexBuffer = vertexBuffers[attributes[index]];
  2875. if (!vertexBuffer) {
  2876. continue;
  2877. }
  2878. var stride = vertexBuffer.getStrideSize();
  2879. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  2880. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  2881. }
  2882. }
  2883. }
  2884. if (this._cachedIndexBuffer !== indexBuffer) {
  2885. this._cachedIndexBuffer = indexBuffer;
  2886. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  2887. }
  2888. };
  2889. Engine.prototype._releaseBuffer = function (buffer) {
  2890. buffer.references--;
  2891. if (buffer.references === 0) {
  2892. this._gl.deleteBuffer(buffer);
  2893. return true;
  2894. }
  2895. return false;
  2896. };
  2897. Engine.prototype.createInstancesBuffer = function (capacity) {
  2898. var buffer = this._gl.createBuffer();
  2899. buffer.capacity = capacity;
  2900. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  2901. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2902. return buffer;
  2903. };
  2904. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  2905. this._gl.deleteBuffer(buffer);
  2906. };
  2907. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  2908. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  2909. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2910. for (var index = 0; index < 4; index++) {
  2911. var offsetLocation = offsetLocations[index];
  2912. this._gl.enableVertexAttribArray(offsetLocation);
  2913. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  2914. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  2915. }
  2916. };
  2917. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  2918. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  2919. for (var index = 0; index < 4; index++) {
  2920. var offsetLocation = offsetLocations[index];
  2921. this._gl.disableVertexAttribArray(offsetLocation);
  2922. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  2923. }
  2924. };
  2925. Engine.prototype.applyStates = function () {
  2926. this._depthCullingState.apply(this._gl);
  2927. this._alphaState.apply(this._gl);
  2928. };
  2929. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  2930. this.applyStates();
  2931. if (instancesCount) {
  2932. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2, instancesCount);
  2933. return;
  2934. }
  2935. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  2936. };
  2937. Engine.prototype._releaseEffect = function (effect) {
  2938. if (this._compiledEffects[effect._key]) {
  2939. delete this._compiledEffects[effect._key];
  2940. if (effect.getProgram()) {
  2941. this._gl.deleteProgram(effect.getProgram());
  2942. }
  2943. }
  2944. };
  2945. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  2946. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  2947. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  2948. var name = vertex + "+" + fragment + "@" + defines;
  2949. if (this._compiledEffects[name]) {
  2950. return this._compiledEffects[name];
  2951. }
  2952. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  2953. effect._key = name;
  2954. this._compiledEffects[name] = effect;
  2955. return effect;
  2956. };
  2957. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  2958. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  2959. if (typeof samplers === "undefined") { samplers = []; }
  2960. if (typeof defines === "undefined") { defines = ""; }
  2961. return this.createEffect({
  2962. vertex: "particles",
  2963. fragmentElement: fragmentName
  2964. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  2965. };
  2966. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  2967. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  2968. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  2969. var shaderProgram = this._gl.createProgram();
  2970. this._gl.attachShader(shaderProgram, vertexShader);
  2971. this._gl.attachShader(shaderProgram, fragmentShader);
  2972. this._gl.linkProgram(shaderProgram);
  2973. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  2974. if (!linked) {
  2975. var error = this._gl.getProgramInfoLog(shaderProgram);
  2976. if (error) {
  2977. throw new Error(error);
  2978. }
  2979. }
  2980. this._gl.deleteShader(vertexShader);
  2981. this._gl.deleteShader(fragmentShader);
  2982. return shaderProgram;
  2983. };
  2984. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  2985. var results = [];
  2986. for (var index = 0; index < uniformsNames.length; index++) {
  2987. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  2988. }
  2989. return results;
  2990. };
  2991. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  2992. var results = [];
  2993. for (var index = 0; index < attributesNames.length; index++) {
  2994. try {
  2995. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  2996. } catch (e) {
  2997. results.push(-1);
  2998. }
  2999. }
  3000. return results;
  3001. };
  3002. Engine.prototype.enableEffect = function (effect) {
  3003. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3004. return;
  3005. }
  3006. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3007. this._gl.useProgram(effect.getProgram());
  3008. for (var i in this._vertexAttribArrays) {
  3009. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3010. continue;
  3011. }
  3012. this._vertexAttribArrays[i] = false;
  3013. this._gl.disableVertexAttribArray(i);
  3014. }
  3015. var attributesCount = effect.getAttributesCount();
  3016. for (var index = 0; index < attributesCount; index++) {
  3017. var order = effect.getAttributeLocation(index);
  3018. if (order >= 0) {
  3019. this._vertexAttribArrays[order] = true;
  3020. this._gl.enableVertexAttribArray(order);
  3021. }
  3022. }
  3023. this._currentEffect = effect;
  3024. };
  3025. Engine.prototype.setArray = function (uniform, array) {
  3026. if (!uniform)
  3027. return;
  3028. this._gl.uniform1fv(uniform, array);
  3029. };
  3030. Engine.prototype.setMatrices = function (uniform, matrices) {
  3031. if (!uniform)
  3032. return;
  3033. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3034. };
  3035. Engine.prototype.setMatrix = function (uniform, matrix) {
  3036. if (!uniform)
  3037. return;
  3038. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3039. };
  3040. Engine.prototype.setFloat = function (uniform, value) {
  3041. if (!uniform)
  3042. return;
  3043. this._gl.uniform1f(uniform, value);
  3044. };
  3045. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3046. if (!uniform)
  3047. return;
  3048. this._gl.uniform2f(uniform, x, y);
  3049. };
  3050. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3051. if (!uniform)
  3052. return;
  3053. this._gl.uniform3f(uniform, x, y, z);
  3054. };
  3055. Engine.prototype.setBool = function (uniform, bool) {
  3056. if (!uniform)
  3057. return;
  3058. this._gl.uniform1i(uniform, bool);
  3059. };
  3060. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3061. if (!uniform)
  3062. return;
  3063. this._gl.uniform4f(uniform, x, y, z, w);
  3064. };
  3065. Engine.prototype.setColor3 = function (uniform, color3) {
  3066. if (!uniform)
  3067. return;
  3068. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3069. };
  3070. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3071. if (!uniform)
  3072. return;
  3073. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3074. };
  3075. Engine.prototype.setState = function (culling, force) {
  3076. if (this._depthCullingState.cull !== culling || force) {
  3077. if (culling) {
  3078. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3079. this._depthCullingState.cull = true;
  3080. } else {
  3081. this._depthCullingState.cull = false;
  3082. }
  3083. }
  3084. };
  3085. Engine.prototype.setDepthBuffer = function (enable) {
  3086. this._depthCullingState.depthTest = enable;
  3087. };
  3088. Engine.prototype.getDepthWrite = function () {
  3089. return this._depthCullingState.depthMask;
  3090. };
  3091. Engine.prototype.setDepthWrite = function (enable) {
  3092. this._depthCullingState.depthMask = enable;
  3093. };
  3094. Engine.prototype.setColorWrite = function (enable) {
  3095. this._gl.colorMask(enable, enable, enable, enable);
  3096. };
  3097. Engine.prototype.setAlphaMode = function (mode) {
  3098. switch (mode) {
  3099. case BABYLON.Engine.ALPHA_DISABLE:
  3100. this.setDepthWrite(true);
  3101. this._alphaState.alphaBlend = false;
  3102. break;
  3103. case BABYLON.Engine.ALPHA_COMBINE:
  3104. this.setDepthWrite(false);
  3105. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3106. this._alphaState.alphaBlend = true;
  3107. break;
  3108. case BABYLON.Engine.ALPHA_ADD:
  3109. this.setDepthWrite(false);
  3110. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3111. this._alphaState.alphaBlend = true;
  3112. break;
  3113. }
  3114. };
  3115. Engine.prototype.setAlphaTesting = function (enable) {
  3116. this._alphaTest = enable;
  3117. };
  3118. Engine.prototype.getAlphaTesting = function () {
  3119. return this._alphaTest;
  3120. };
  3121. Engine.prototype.wipeCaches = function () {
  3122. this._activeTexturesCache = [];
  3123. this._currentEffect = null;
  3124. this._depthCullingState.reset();
  3125. this._alphaState.reset();
  3126. this._cachedVertexBuffers = null;
  3127. this._cachedIndexBuffer = null;
  3128. this._cachedEffectForVertexBuffers = null;
  3129. };
  3130. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3131. var gl = this._gl;
  3132. gl.bindTexture(gl.TEXTURE_2D, texture);
  3133. var magFilter = gl.NEAREST;
  3134. var minFilter = gl.NEAREST;
  3135. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3136. magFilter = gl.LINEAR;
  3137. minFilter = gl.LINEAR;
  3138. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3139. magFilter = gl.LINEAR;
  3140. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3141. }
  3142. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3143. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3144. gl.bindTexture(gl.TEXTURE_2D, null);
  3145. };
  3146. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode) {
  3147. var _this = this;
  3148. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3149. var texture = this._gl.createTexture();
  3150. var extension = url.substr(url.length - 4, 4).toLowerCase();
  3151. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3152. var isTGA = (extension === ".tga");
  3153. scene._addPendingData(texture);
  3154. texture.url = url;
  3155. texture.noMipmap = noMipmap;
  3156. texture.references = 1;
  3157. this._loadedTexturesCache.push(texture);
  3158. if (isTGA) {
  3159. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  3160. var data = new Uint8Array(arrayBuffer);
  3161. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  3162. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  3163. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  3164. }, samplingMode);
  3165. }, null, scene.database, true);
  3166. } else if (isDDS) {
  3167. BABYLON.Tools.LoadFile(url, function (data) {
  3168. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3169. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  3170. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  3171. console.log("loading " + url);
  3172. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  3173. }, samplingMode);
  3174. }, null, scene.database, true);
  3175. } else {
  3176. var onload = function (img) {
  3177. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  3178. var isPot = (img.width == potWidth && img.height == potHeight);
  3179. if (!isPot) {
  3180. _this._workingCanvas.width = potWidth;
  3181. _this._workingCanvas.height = potHeight;
  3182. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3183. }
  3184. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  3185. }, samplingMode);
  3186. };
  3187. var onerror = function () {
  3188. scene._removePendingData(texture);
  3189. };
  3190. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3191. }
  3192. return texture;
  3193. };
  3194. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  3195. var texture = this._gl.createTexture();
  3196. width = getExponantOfTwo(width, this._caps.maxTextureSize);
  3197. height = getExponantOfTwo(height, this._caps.maxTextureSize);
  3198. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3199. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3200. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3201. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3202. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3203. this._activeTexturesCache = [];
  3204. texture._baseWidth = width;
  3205. texture._baseHeight = height;
  3206. texture._width = width;
  3207. texture._height = height;
  3208. texture.isReady = false;
  3209. texture.generateMipMaps = generateMipMaps;
  3210. texture.references = 1;
  3211. this._loadedTexturesCache.push(texture);
  3212. return texture;
  3213. };
  3214. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  3215. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3216. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  3217. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  3218. if (texture.generateMipMaps) {
  3219. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3220. }
  3221. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3222. this._activeTexturesCache = [];
  3223. texture.isReady = true;
  3224. };
  3225. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  3226. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3227. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1);
  3228. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  3229. if (!texture._workingCanvas) {
  3230. texture._workingCanvas = document.createElement("canvas");
  3231. texture._workingContext = texture._workingCanvas.getContext("2d");
  3232. texture._workingCanvas.width = texture._width;
  3233. texture._workingCanvas.height = texture._height;
  3234. }
  3235. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  3236. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3237. } else {
  3238. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3239. }
  3240. if (texture.generateMipMaps) {
  3241. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3242. }
  3243. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3244. this._activeTexturesCache = [];
  3245. texture.isReady = true;
  3246. };
  3247. Engine.prototype.createRenderTargetTexture = function (size, options) {
  3248. var generateMipMaps = false;
  3249. var generateDepthBuffer = true;
  3250. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3251. if (options !== undefined) {
  3252. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  3253. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3254. if (options.samplingMode !== undefined) {
  3255. samplingMode = options.samplingMode;
  3256. }
  3257. }
  3258. var gl = this._gl;
  3259. var texture = gl.createTexture();
  3260. gl.bindTexture(gl.TEXTURE_2D, texture);
  3261. var width = size.width || size;
  3262. var height = size.height || size;
  3263. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3264. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3265. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3266. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3267. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3268. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  3269. var depthBuffer;
  3270. if (generateDepthBuffer) {
  3271. depthBuffer = gl.createRenderbuffer();
  3272. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  3273. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3274. }
  3275. var framebuffer = gl.createFramebuffer();
  3276. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  3277. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3278. if (generateDepthBuffer) {
  3279. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  3280. }
  3281. gl.bindTexture(gl.TEXTURE_2D, null);
  3282. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3283. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3284. texture._framebuffer = framebuffer;
  3285. if (generateDepthBuffer) {
  3286. texture._depthBuffer = depthBuffer;
  3287. }
  3288. texture._width = width;
  3289. texture._height = height;
  3290. texture.isReady = true;
  3291. texture.generateMipMaps = generateMipMaps;
  3292. texture.references = 1;
  3293. this._activeTexturesCache = [];
  3294. this._loadedTexturesCache.push(texture);
  3295. return texture;
  3296. };
  3297. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  3298. var _this = this;
  3299. var gl = this._gl;
  3300. var texture = gl.createTexture();
  3301. texture.isCube = true;
  3302. texture.url = rootUrl;
  3303. texture.references = 1;
  3304. this._loadedTexturesCache.push(texture);
  3305. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  3306. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3307. if (isDDS) {
  3308. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  3309. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3310. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3311. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3312. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3313. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  3314. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  3315. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3316. }
  3317. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3318. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3319. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3320. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3321. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3322. _this._activeTexturesCache = [];
  3323. texture._width = info.width;
  3324. texture._height = info.height;
  3325. texture.isReady = true;
  3326. }, null, null, true);
  3327. } else {
  3328. cascadeLoad(rootUrl, 0, [], scene, function (imgs) {
  3329. var width = getExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  3330. var height = width;
  3331. _this._workingCanvas.width = width;
  3332. _this._workingCanvas.height = height;
  3333. var faces = [
  3334. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3335. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3336. ];
  3337. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3338. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3339. for (var index = 0; index < faces.length; index++) {
  3340. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3341. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  3342. }
  3343. if (!noMipmap) {
  3344. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3345. }
  3346. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3347. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  3348. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3349. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3350. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3351. _this._activeTexturesCache = [];
  3352. texture._width = width;
  3353. texture._height = height;
  3354. texture.isReady = true;
  3355. }, extensions);
  3356. }
  3357. return texture;
  3358. };
  3359. Engine.prototype._releaseTexture = function (texture) {
  3360. var gl = this._gl;
  3361. if (texture._framebuffer) {
  3362. gl.deleteFramebuffer(texture._framebuffer);
  3363. }
  3364. if (texture._depthBuffer) {
  3365. gl.deleteRenderbuffer(texture._depthBuffer);
  3366. }
  3367. gl.deleteTexture(texture);
  3368. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3369. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3370. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3371. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3372. this._activeTexturesCache[channel] = null;
  3373. }
  3374. var index = this._loadedTexturesCache.indexOf(texture);
  3375. if (index !== -1) {
  3376. this._loadedTexturesCache.splice(index, 1);
  3377. }
  3378. };
  3379. Engine.prototype.bindSamplers = function (effect) {
  3380. this._gl.useProgram(effect.getProgram());
  3381. var samplers = effect.getSamplers();
  3382. for (var index = 0; index < samplers.length; index++) {
  3383. var uniform = effect.getUniform(samplers[index]);
  3384. this._gl.uniform1i(uniform, index);
  3385. }
  3386. this._currentEffect = null;
  3387. };
  3388. Engine.prototype._bindTexture = function (channel, texture) {
  3389. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3390. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3391. this._activeTexturesCache[channel] = null;
  3392. };
  3393. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  3394. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3395. };
  3396. Engine.prototype.setTexture = function (channel, texture) {
  3397. if (channel < 0) {
  3398. return;
  3399. }
  3400. if (!texture || !texture.isReady()) {
  3401. if (this._activeTexturesCache[channel] != null) {
  3402. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3403. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3404. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3405. this._activeTexturesCache[channel] = null;
  3406. }
  3407. return;
  3408. }
  3409. if (texture instanceof BABYLON.VideoTexture) {
  3410. if (texture.update()) {
  3411. this._activeTexturesCache[channel] = null;
  3412. }
  3413. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  3414. texture.delayLoad();
  3415. return;
  3416. }
  3417. if (this._activeTexturesCache[channel] == texture) {
  3418. return;
  3419. }
  3420. this._activeTexturesCache[channel] = texture;
  3421. var internalTexture = texture.getInternalTexture();
  3422. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3423. if (internalTexture.isCube) {
  3424. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3425. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3426. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3427. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3428. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3429. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3430. }
  3431. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3432. } else {
  3433. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  3434. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3435. internalTexture._cachedWrapU = texture.wrapU;
  3436. switch (texture.wrapU) {
  3437. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3438. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3439. break;
  3440. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3441. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3442. break;
  3443. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3444. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  3445. break;
  3446. }
  3447. }
  3448. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3449. internalTexture._cachedWrapV = texture.wrapV;
  3450. switch (texture.wrapV) {
  3451. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3452. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  3453. break;
  3454. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3455. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  3456. break;
  3457. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3458. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  3459. break;
  3460. }
  3461. }
  3462. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3463. }
  3464. };
  3465. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  3466. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3467. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  3468. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  3469. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  3470. }
  3471. };
  3472. Engine.prototype.readPixels = function (x, y, width, height) {
  3473. var data = new Uint8Array(height * width * 4);
  3474. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  3475. return data;
  3476. };
  3477. Engine.prototype.dispose = function () {
  3478. this.hideLoadingUI();
  3479. this.stopRenderLoop();
  3480. while (this.scenes.length) {
  3481. this.scenes[0].dispose();
  3482. }
  3483. for (var name in this._compiledEffects) {
  3484. this._gl.deleteProgram(this._compiledEffects[name]._program);
  3485. }
  3486. for (var i in this._vertexAttribArrays) {
  3487. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3488. continue;
  3489. }
  3490. this._gl.disableVertexAttribArray(i);
  3491. }
  3492. window.removeEventListener("blur", this._onBlur);
  3493. window.removeEventListener("focus", this._onFocus);
  3494. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  3495. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  3496. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  3497. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  3498. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  3499. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  3500. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  3501. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  3502. };
  3503. Engine.prototype.displayLoadingUI = function () {
  3504. var _this = this;
  3505. this._loadingDiv = document.createElement("div");
  3506. this._loadingDiv.style.opacity = "0";
  3507. this._loadingDiv.style.transition = "opacity 1.5s ease";
  3508. this._loadingTextDiv = document.createElement("div");
  3509. this._loadingTextDiv.style.position = "absolute";
  3510. this._loadingTextDiv.style.left = "0";
  3511. this._loadingTextDiv.style.top = "50%";
  3512. this._loadingTextDiv.style.marginTop = "80px";
  3513. this._loadingTextDiv.style.width = "100%";
  3514. this._loadingTextDiv.style.height = "20px";
  3515. this._loadingTextDiv.style.fontFamily = "Arial";
  3516. this._loadingTextDiv.style.fontSize = "14px";
  3517. this._loadingTextDiv.style.color = "white";
  3518. this._loadingTextDiv.style.textAlign = "center";
  3519. this._loadingTextDiv.innerHTML = "Loading";
  3520. this._loadingDiv.appendChild(this._loadingTextDiv);
  3521. var imgBack = new Image();
  3522. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAARbSURBVHhe7Z09aFNRFMc716kuLrq4FdyLq4Wi4CAoRQcR0UJBUBdRiuLSIYMo6CA4FF2sgw6CFAdFUOpSQYcWO4hD26UQCfXrIQrx/JJzw1OSWq3NPeL/B4Fy+0jg/HO+7j3vpUcI8b/Q39+/49ihfWdPHT94Yf/e3Se3bd263f8lus218TPn6vV6Ya8Wi/MzNRNmj18iusX9W1evmP1/EKNEIVG6CMbG6E3bt+fT++pHha8NoHdT72bLE8NDg7tGU64gLLndV4Wc4m8j/pS+vr4tGB/DT16v3Fyr8dvBe/jbit8BL0AES9LX1iPAz+BR/hFiLVCynj95dPzNy6fv3IZ/k4L3948Sq7FzYGBg4vLFGxitabuOFCbWNKGrMnbiUuo18KaV6tIHv6YtvL9/nOgE31jCktmrY7k6+/zhE4yP4Vf7hiNqh/BWWEl8mzDol4p22Lf7cIdvdUMEvv0Y2S9fE5S1hLzpqTsPkiep//gFGPnR3Yl7GL5p/xYFBrTwM+iXio3GqpwDGL5p/xYNIX7XG8Q6IJRgdIzf1KBBgafII7oMidhyQtVFaMA2Bt7il4huQRhaXphbcR2g4RXqBzKAGHiCCwGFVUAj/m/RTRDj29cvn10I0PZ3LghH5f4CL1EFlQmqqXK3jDDKFxmhQ3Yt6oQseUZGKmMnTpsOqc8o1F9kBOMjQlOLeqEeIyOc6JV6jYLJD/+XyIFvnzdgl9aXRQ5I2qZDK1SpospMqaoqON/wZZGDciLnMMiXRS7IF4hhqMTNTdk7CFu+LHLhR7BQqBvPDJUUQqCGvCMATHUgBmhWNgApmdOda9YpM+VwRYfuyyIXDK8hBlilNerLIheMZCKGwlUAyru6GlwOgPUbRxADdJ9FAChxXY864viyyEXqPxhc0M2TAfAbatSdRyHtXymhByEdRnE3ky+JnHAIhSA0h74kckETmHoQbSgGwJrCIRMEPSRIBCRIMAhZaYhaggQhJXUJEoRU9mofKwh+F22dLRRfEjlJM7w6KQwCoQpBOKTyJZETjmwRxKqtGV8SOSkNOGjKPQppBEgDDkFgpxdBVGkFgaYQQXRIFQSObk0P5ZFIpAZRHXsQ0r0hCluBWKkuvVbYCkQaCdL5ehBScudJP4yY+rLISdps1NBDEJKXMMmoSfggWC4ZQRR17oFYXph7hSiquIKQ+hJGTX1J5MYSPD/GVdNzsgLBwZVCVyAQAkF0ohiI/c1fS6tNXq9UfEnkhudmIQolsS+J3Hh/UtNDzQLhj42VKJFInqLwFYiUU5ToA+HdfI0JevUpQUAIn+vSz2lHIuUV/dJOIHhOY/IWVWGBIHQtzs88s9zyWBuTgcBLzGOmeNnfF/QslSDgMeQW85i3DOQxuipxAkCyZ8SIm4Omp+7MMlCB59j6sKZcMoM4iIEoeI2J9AKxrFobZx0v4vYInuHFS4J1GQRCAGaLEYQXfyMML5XSQgghhBBCCCH+cXp6vgNhKpSKX/XdOAAAAABJRU5ErkJggg==";
  3523. imgBack.style.position = "absolute";
  3524. imgBack.style.left = "50%";
  3525. imgBack.style.top = "50%";
  3526. imgBack.style.marginLeft = "-50px";
  3527. imgBack.style.marginTop = "-50px";
  3528. imgBack.style.transition = "transform 1.0s ease";
  3529. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  3530. var deg = 360;
  3531. var onTransitionEnd = function () {
  3532. deg += 360;
  3533. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  3534. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  3535. };
  3536. imgBack.addEventListener("transitionend", onTransitionEnd);
  3537. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  3538. this._loadingDiv.appendChild(imgBack);
  3539. var imgFront = new Image();
  3540. imgFront.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAAYJSURBVHhe7Zy/qx1FFMff/2Av2Nvbi4WFiiAEY/OQ2IgQsbCJQoqkCAgpFLXyoZURLfwBIiIpgqZJoYQYlWelNsIrNOxDJcrzfHe+G97dnTl75u7euzv7zgcWHrlnZmfOmXPmzI/NjuM4juM4juM4juM4juM4juM4juM4juM45fPic08/uHf5/CvffH7lnT8PfrtxdHS0n3p+/fHGl5+89/prr5599iEWd8bg0rkXHoFyqehKnlxQpjYSDHTm9JMPsGrHylOPPXofvICKXMcIGtXdf/76AYbm6xyNW9e/eAtKC7rbKLXnvHHx5Sf4auc4Ek7OQkFU1Dap/vv37k/wSjblZANFiFIGzw98hhizwqBgs04mCBdQRNCHidoAEtY+lLIvtSdoGFeyql2ZH57HBH4sE7O+o/r9l+8/ZXUni68+2jsHBQQ9qNRGeP/tSxdSYQX/roUcpL4/f3vtM9TD+jTq92n1LQ7jxF1hhGPtwWL3gGccy8JuS1r8sVWBGXNVdSKMYjBGPUJjCzooiGuSpnwlnnOGP2dhHRSLNgpHp2oMKIriK8TmG4Qh/rwW8D6pps9b9im+LDDipXOqMVJrAngBfg9i98gevWKA+/nnCod3Dr5GfaHaDgidVym6HKRjGIkpqthcAVKGxNqBImbEo66kjCih8AOpNmkUmbMuUrR8kEqiU6FvHZLGAPJ71JCYSyhiBqmwFE2GoD6jLGIfDHtG6EzoU4dK21PCqIRMEF0FGRjFzGDtIkXVAdATvsqfT9CJ0JcOFdYiFIsiMlqYy1YOFpQo2OddqBtyEaq9y+efoVh5oPHoROjLKn0j3JIE5Ka8UqZRtGrMnneX6yVofOhDh94MSbznTcpqmDOt1vyQzOgaJAF4F3JBfIXesrNEGWWmjIX7UBZ6jRJbBMLg/DmJiKUGVHleIpnVNTa+jakzkAviJqLhi4MC9XQGBrZeKJZESSrKy7ik0VGFWhQBRDTHIACKQ5l9nAjy75gya4a2w+Jhs0FJdc0xX/GwUbAqFBkZi7QpJ2w16WUbjFyK9MJF3KaoEM74KhVtLrQOrsmRxkbdHEqmSC/c+EuGnIFkjW7Ih2Kr4CCMIvNG2hrrgLpCjiFloooYCjyYrzCRyvhyBthkIPuQtsZGdnbMTezyDiU71KTC5zr7aVsHbsz2tllrEkS5UHwU1tq1HbtPW4UbeB0O7xx8R5EsMJql+BheUmHjkNVmIRP7LutoM3+D4O4tG7vCkNO9ESZ4lL3J6rKRMPx4qKbD/A0icf8CG7tC7kTahnMTwleuYSrsS7GatRAvfZh1tTm5BmmQCdZ8a0Sefe28xUrRBkmFLKy8KTIKUDRX0Y1xagPgwbaIdeFnQULmKak3xvwNMkVGgok/N5XNoehJvejRlCDl9escI28dJU0tZ++nBTJE9mEF647x5Ehbo4s5hDOKFIU0PdofeA5F5k1q63zIWmQqNI/P3ZubjFTqKxQ3jyjHAOX0RdlgVO9hzRFpczRcjZ3Gbxxpc7Qj6+5pTYF2OFXawNI+yDGf1k2NcvOlzBQeDQ/t7zD7DsEDpJ2xATXaNtDWUS4IzP4DS2ljajAVu57SUkYw245ptxZxA5JiZaJ0DswudGn3kYUy54426EjoT4dZfYbccxC2nI92cDkZHQr96jD4AGkMDKeSy/COBsRe6VTSKFN6irLeaCh3IteQjt1E5+oudsG/b/2DfZ5AqsYo8vMDK9LB1HzSsLWvlGThdxXvC6+NsqyPPWP0pMINtbdsajfVeC6f/GZ+cdAofQoB1d+Hf9waY98I7+RXWab3Lt4zYkjHtTnlOLXHYMsCh1zWeQYehu1zfNPOOiys/d91LAKEBSgh6MJMbSA82AaHofDgAIwbgvVvlLNS11nModMm4UZergLHZBZrodmBuA3lBB1thdorSjkOmATMDwg/UBQVtglqQyx6fbEJ+H3IWIapjYAjAfeIgeCMHldueJvFaqDaAHhwf8qNsEEQ1iQbOoUUGIbCLRc8+Bvfp4jyd2FEijuO4ziO4ziO4ziO4ziO4ziO4ziO4ziOUzw7O/8D0P7rcZ/GEboAAAAASUVORK5CYII=";
  3541. imgFront.style.position = "absolute";
  3542. imgFront.style.left = "50%";
  3543. imgFront.style.top = "50%";
  3544. imgFront.style.marginLeft = "-50px";
  3545. imgFront.style.marginTop = "-50px";
  3546. this._loadingDiv.appendChild(imgFront);
  3547. this._resizeLoadingUI = function () {
  3548. var canvasRect = _this.getRenderingCanvasClientRect();
  3549. _this._loadingDiv.style.position = "absolute";
  3550. _this._loadingDiv.style.left = canvasRect.left + "px";
  3551. _this._loadingDiv.style.top = canvasRect.top + "px";
  3552. _this._loadingDiv.style.width = canvasRect.width + "px";
  3553. _this._loadingDiv.style.height = canvasRect.height + "px";
  3554. };
  3555. this._resizeLoadingUI();
  3556. window.addEventListener("resize", this._resizeLoadingUI);
  3557. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3558. document.body.appendChild(this._loadingDiv);
  3559. setTimeout(function () {
  3560. _this._loadingDiv.style.opacity = "1";
  3561. imgBack.style.transform = "rotateZ(360deg)";
  3562. imgBack.style.webkitTransform = "rotateZ(360deg)";
  3563. }, 0);
  3564. };
  3565. Object.defineProperty(Engine.prototype, "loadingUIText", {
  3566. set: function (text) {
  3567. if (!this._loadingDiv) {
  3568. return;
  3569. }
  3570. this._loadingTextDiv.innerHTML = text;
  3571. },
  3572. enumerable: true,
  3573. configurable: true
  3574. });
  3575. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  3576. get: function () {
  3577. return this._loadingDivBackgroundColor;
  3578. },
  3579. set: function (color) {
  3580. this._loadingDivBackgroundColor = color;
  3581. if (!this._loadingDiv) {
  3582. return;
  3583. }
  3584. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3585. },
  3586. enumerable: true,
  3587. configurable: true
  3588. });
  3589. Engine.prototype.hideLoadingUI = function () {
  3590. var _this = this;
  3591. if (!this._loadingDiv) {
  3592. return;
  3593. }
  3594. var onTransitionEnd = function () {
  3595. if (!_this._loadingDiv) {
  3596. return;
  3597. }
  3598. document.body.removeChild(_this._loadingDiv);
  3599. window.removeEventListener("resize", _this._resizeLoadingUI);
  3600. _this._loadingDiv = null;
  3601. };
  3602. this._loadingDiv.style.opacity = "0";
  3603. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  3604. };
  3605. Engine.isSupported = function () {
  3606. try {
  3607. var tempcanvas = document.createElement("canvas");
  3608. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  3609. return gl != null && !!window.WebGLRenderingContext;
  3610. } catch (e) {
  3611. return false;
  3612. }
  3613. };
  3614. Engine._ALPHA_DISABLE = 0;
  3615. Engine._ALPHA_ADD = 1;
  3616. Engine._ALPHA_COMBINE = 2;
  3617. Engine._DELAYLOADSTATE_NONE = 0;
  3618. Engine._DELAYLOADSTATE_LOADED = 1;
  3619. Engine._DELAYLOADSTATE_LOADING = 2;
  3620. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  3621. Engine.Epsilon = 0.001;
  3622. Engine.CollisionsEpsilon = 0.001;
  3623. Engine.ShadersRepository = "Babylon/Shaders/";
  3624. return Engine;
  3625. })();
  3626. BABYLON.Engine = Engine;
  3627. })(BABYLON || (BABYLON = {}));
  3628. var BABYLON;
  3629. (function (BABYLON) {
  3630. var Node = (function () {
  3631. function Node(name, scene) {
  3632. this.state = "";
  3633. this.animations = new Array();
  3634. this._childrenFlag = -1;
  3635. this._isEnabled = true;
  3636. this._isReady = true;
  3637. this._currentRenderId = -1;
  3638. this.name = name;
  3639. this.id = name;
  3640. this._scene = scene;
  3641. this._initCache();
  3642. }
  3643. Node.prototype.getScene = function () {
  3644. return this._scene;
  3645. };
  3646. Node.prototype.getEngine = function () {
  3647. return this._scene.getEngine();
  3648. };
  3649. Node.prototype.getWorldMatrix = function () {
  3650. return BABYLON.Matrix.Identity();
  3651. };
  3652. Node.prototype._initCache = function () {
  3653. this._cache = {};
  3654. this._cache.parent = undefined;
  3655. };
  3656. Node.prototype.updateCache = function (force) {
  3657. if (!force && this.isSynchronized())
  3658. return;
  3659. this._cache.parent = this.parent;
  3660. this._updateCache();
  3661. };
  3662. Node.prototype._updateCache = function (ignoreParentClass) {
  3663. };
  3664. Node.prototype._isSynchronized = function () {
  3665. return true;
  3666. };
  3667. Node.prototype.isSynchronizedWithParent = function () {
  3668. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  3669. };
  3670. Node.prototype.isSynchronized = function (updateCache) {
  3671. var check = this.hasNewParent();
  3672. check = check || !this.isSynchronizedWithParent();
  3673. check = check || !this._isSynchronized();
  3674. if (updateCache)
  3675. this.updateCache(true);
  3676. return !check;
  3677. };
  3678. Node.prototype.hasNewParent = function (update) {
  3679. if (this._cache.parent === this.parent)
  3680. return false;
  3681. if (update)
  3682. this._cache.parent = this.parent;
  3683. return true;
  3684. };
  3685. Node.prototype.isReady = function () {
  3686. return this._isReady;
  3687. };
  3688. Node.prototype.isEnabled = function () {
  3689. if (!this._isEnabled) {
  3690. return false;
  3691. }
  3692. if (this.parent) {
  3693. return this.parent.isEnabled();
  3694. }
  3695. return true;
  3696. };
  3697. Node.prototype.setEnabled = function (value) {
  3698. this._isEnabled = value;
  3699. };
  3700. Node.prototype.isDescendantOf = function (ancestor) {
  3701. if (this.parent) {
  3702. if (this.parent === ancestor) {
  3703. return true;
  3704. }
  3705. return this.parent.isDescendantOf(ancestor);
  3706. }
  3707. return false;
  3708. };
  3709. Node.prototype._getDescendants = function (list, results) {
  3710. for (var index = 0; index < list.length; index++) {
  3711. var item = list[index];
  3712. if (item.isDescendantOf(this)) {
  3713. results.push(item);
  3714. }
  3715. }
  3716. };
  3717. Node.prototype.getDescendants = function () {
  3718. var results = [];
  3719. this._getDescendants(this._scene.meshes, results);
  3720. this._getDescendants(this._scene.lights, results);
  3721. this._getDescendants(this._scene.cameras, results);
  3722. return results;
  3723. };
  3724. Node.prototype._setReady = function (state) {
  3725. if (state == this._isReady) {
  3726. return;
  3727. }
  3728. if (!state) {
  3729. this._isReady = false;
  3730. return;
  3731. }
  3732. this._isReady = true;
  3733. if (this.onReady) {
  3734. this.onReady(this);
  3735. }
  3736. };
  3737. return Node;
  3738. })();
  3739. BABYLON.Node = Node;
  3740. })(BABYLON || (BABYLON = {}));
  3741. var BABYLON;
  3742. (function (BABYLON) {
  3743. var BoundingSphere = (function () {
  3744. function BoundingSphere(minimum, maximum) {
  3745. this.minimum = minimum;
  3746. this.maximum = maximum;
  3747. this._tempRadiusVector = BABYLON.Vector3.Zero();
  3748. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  3749. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  3750. this.radius = distance * 0.5;
  3751. this.centerWorld = BABYLON.Vector3.Zero();
  3752. this._update(BABYLON.Matrix.Identity());
  3753. }
  3754. BoundingSphere.prototype._update = function (world) {
  3755. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  3756. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  3757. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  3758. };
  3759. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  3760. for (var i = 0; i < 6; i++) {
  3761. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  3762. return false;
  3763. }
  3764. return true;
  3765. };
  3766. BoundingSphere.prototype.intersectsPoint = function (point) {
  3767. var x = this.centerWorld.x - point.x;
  3768. var y = this.centerWorld.y - point.y;
  3769. var z = this.centerWorld.z - point.z;
  3770. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3771. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  3772. return false;
  3773. return true;
  3774. };
  3775. BoundingSphere.Intersects = function (sphere0, sphere1) {
  3776. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  3777. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  3778. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  3779. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3780. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  3781. return false;
  3782. return true;
  3783. };
  3784. return BoundingSphere;
  3785. })();
  3786. BABYLON.BoundingSphere = BoundingSphere;
  3787. })(BABYLON || (BABYLON = {}));
  3788. var BABYLON;
  3789. (function (BABYLON) {
  3790. var BoundingBox = (function () {
  3791. function BoundingBox(minimum, maximum) {
  3792. this.minimum = minimum;
  3793. this.maximum = maximum;
  3794. this.vectors = new Array();
  3795. this.vectorsWorld = new Array();
  3796. this.vectors.push(this.minimum.clone());
  3797. this.vectors.push(this.maximum.clone());
  3798. this.vectors.push(this.minimum.clone());
  3799. this.vectors[2].x = this.maximum.x;
  3800. this.vectors.push(this.minimum.clone());
  3801. this.vectors[3].y = this.maximum.y;
  3802. this.vectors.push(this.minimum.clone());
  3803. this.vectors[4].z = this.maximum.z;
  3804. this.vectors.push(this.maximum.clone());
  3805. this.vectors[5].z = this.minimum.z;
  3806. this.vectors.push(this.maximum.clone());
  3807. this.vectors[6].x = this.minimum.x;
  3808. this.vectors.push(this.maximum.clone());
  3809. this.vectors[7].y = this.minimum.y;
  3810. this.center = this.maximum.add(this.minimum).scale(0.5);
  3811. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  3812. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  3813. for (var index = 0; index < this.vectors.length; index++) {
  3814. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  3815. }
  3816. this.minimumWorld = BABYLON.Vector3.Zero();
  3817. this.maximumWorld = BABYLON.Vector3.Zero();
  3818. this._update(BABYLON.Matrix.Identity());
  3819. }
  3820. BoundingBox.prototype.getWorldMatrix = function () {
  3821. return this._worldMatrix;
  3822. };
  3823. BoundingBox.prototype._update = function (world) {
  3824. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  3825. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  3826. for (var index = 0; index < this.vectors.length; index++) {
  3827. var v = this.vectorsWorld[index];
  3828. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  3829. if (v.x < this.minimumWorld.x)
  3830. this.minimumWorld.x = v.x;
  3831. if (v.y < this.minimumWorld.y)
  3832. this.minimumWorld.y = v.y;
  3833. if (v.z < this.minimumWorld.z)
  3834. this.minimumWorld.z = v.z;
  3835. if (v.x > this.maximumWorld.x)
  3836. this.maximumWorld.x = v.x;
  3837. if (v.y > this.maximumWorld.y)
  3838. this.maximumWorld.y = v.y;
  3839. if (v.z > this.maximumWorld.z)
  3840. this.maximumWorld.z = v.z;
  3841. }
  3842. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  3843. this.center.scaleInPlace(0.5);
  3844. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  3845. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  3846. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  3847. this._worldMatrix = world;
  3848. };
  3849. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  3850. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  3851. };
  3852. BoundingBox.prototype.intersectsPoint = function (point) {
  3853. var delta = BABYLON.Engine.Epsilon;
  3854. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  3855. return false;
  3856. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  3857. return false;
  3858. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  3859. return false;
  3860. return true;
  3861. };
  3862. BoundingBox.prototype.intersectsSphere = function (sphere) {
  3863. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  3864. };
  3865. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  3866. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  3867. return false;
  3868. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  3869. return false;
  3870. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  3871. return false;
  3872. return true;
  3873. };
  3874. BoundingBox.Intersects = function (box0, box1) {
  3875. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  3876. return false;
  3877. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  3878. return false;
  3879. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  3880. return false;
  3881. return true;
  3882. };
  3883. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  3884. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  3885. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  3886. return (num <= (sphereRadius * sphereRadius));
  3887. };
  3888. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  3889. for (var p = 0; p < 6; p++) {
  3890. var inCount = 8;
  3891. for (var i = 0; i < 8; i++) {
  3892. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  3893. --inCount;
  3894. } else {
  3895. break;
  3896. }
  3897. }
  3898. if (inCount == 0)
  3899. return false;
  3900. }
  3901. return true;
  3902. };
  3903. return BoundingBox;
  3904. })();
  3905. BABYLON.BoundingBox = BoundingBox;
  3906. })(BABYLON || (BABYLON = {}));
  3907. var BABYLON;
  3908. (function (BABYLON) {
  3909. var computeBoxExtents = function (axis, box) {
  3910. var p = BABYLON.Vector3.Dot(box.center, axis);
  3911. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  3912. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  3913. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  3914. var r = r0 + r1 + r2;
  3915. return {
  3916. min: p - r,
  3917. max: p + r
  3918. };
  3919. };
  3920. var extentsOverlap = function (min0, max0, min1, max1) {
  3921. return !(min0 > max1 || min1 > max0);
  3922. };
  3923. var axisOverlap = function (axis, box0, box1) {
  3924. var result0 = computeBoxExtents(axis, box0);
  3925. var result1 = computeBoxExtents(axis, box1);
  3926. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  3927. };
  3928. var BoundingInfo = (function () {
  3929. function BoundingInfo(minimum, maximum) {
  3930. this.minimum = minimum;
  3931. this.maximum = maximum;
  3932. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  3933. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  3934. }
  3935. BoundingInfo.prototype._update = function (world) {
  3936. this.boundingBox._update(world);
  3937. this.boundingSphere._update(world);
  3938. };
  3939. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  3940. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  3941. return false;
  3942. return this.boundingBox.isInFrustum(frustumPlanes);
  3943. };
  3944. BoundingInfo.prototype._checkCollision = function (collider) {
  3945. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  3946. };
  3947. BoundingInfo.prototype.intersectsPoint = function (point) {
  3948. if (!this.boundingSphere.centerWorld) {
  3949. return false;
  3950. }
  3951. if (!this.boundingSphere.intersectsPoint(point)) {
  3952. return false;
  3953. }
  3954. if (!this.boundingBox.intersectsPoint(point)) {
  3955. return false;
  3956. }
  3957. return true;
  3958. };
  3959. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  3960. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  3961. return false;
  3962. }
  3963. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  3964. return false;
  3965. }
  3966. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  3967. return false;
  3968. }
  3969. if (!precise) {
  3970. return true;
  3971. }
  3972. var box0 = this.boundingBox;
  3973. var box1 = boundingInfo.boundingBox;
  3974. if (!axisOverlap(box0.directions[0], box0, box1))
  3975. return false;
  3976. if (!axisOverlap(box0.directions[1], box0, box1))
  3977. return false;
  3978. if (!axisOverlap(box0.directions[2], box0, box1))
  3979. return false;
  3980. if (!axisOverlap(box1.directions[0], box0, box1))
  3981. return false;
  3982. if (!axisOverlap(box1.directions[1], box0, box1))
  3983. return false;
  3984. if (!axisOverlap(box1.directions[2], box0, box1))
  3985. return false;
  3986. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  3987. return false;
  3988. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  3989. return false;
  3990. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  3991. return false;
  3992. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  3993. return false;
  3994. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  3995. return false;
  3996. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  3997. return false;
  3998. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  3999. return false;
  4000. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  4001. return false;
  4002. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  4003. return false;
  4004. return true;
  4005. };
  4006. return BoundingInfo;
  4007. })();
  4008. BABYLON.BoundingInfo = BoundingInfo;
  4009. })(BABYLON || (BABYLON = {}));
  4010. var __extends = this.__extends || function (d, b) {
  4011. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4012. function __() { this.constructor = d; }
  4013. __.prototype = b.prototype;
  4014. d.prototype = new __();
  4015. };
  4016. var BABYLON;
  4017. (function (BABYLON) {
  4018. var Light = (function (_super) {
  4019. __extends(Light, _super);
  4020. function Light(name, scene) {
  4021. _super.call(this, name, scene);
  4022. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  4023. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  4024. this.intensity = 1.0;
  4025. this.range = Number.MAX_VALUE;
  4026. this.includedOnlyMeshes = new Array();
  4027. this.excludedMeshes = new Array();
  4028. this._excludedMeshesIds = new Array();
  4029. this._includedOnlyMeshesIds = new Array();
  4030. scene.lights.push(this);
  4031. }
  4032. Light.prototype.getShadowGenerator = function () {
  4033. return this._shadowGenerator;
  4034. };
  4035. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  4036. };
  4037. Light.prototype._getWorldMatrix = function () {
  4038. return BABYLON.Matrix.Identity();
  4039. };
  4040. Light.prototype.canAffectMesh = function (mesh) {
  4041. if (!mesh) {
  4042. return true;
  4043. }
  4044. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  4045. return false;
  4046. }
  4047. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  4048. return false;
  4049. }
  4050. return true;
  4051. };
  4052. Light.prototype.getWorldMatrix = function () {
  4053. this._currentRenderId = this.getScene().getRenderId();
  4054. var worldMatrix = this._getWorldMatrix();
  4055. if (this.parent && this.parent.getWorldMatrix) {
  4056. if (!this._parentedWorldMatrix) {
  4057. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4058. }
  4059. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4060. return this._parentedWorldMatrix;
  4061. }
  4062. return worldMatrix;
  4063. };
  4064. Light.prototype.dispose = function () {
  4065. if (this._shadowGenerator) {
  4066. this._shadowGenerator.dispose();
  4067. this._shadowGenerator = null;
  4068. }
  4069. var index = this.getScene().lights.indexOf(this);
  4070. this.getScene().lights.splice(index, 1);
  4071. };
  4072. return Light;
  4073. })(BABYLON.Node);
  4074. BABYLON.Light = Light;
  4075. })(BABYLON || (BABYLON = {}));
  4076. var __extends = this.__extends || function (d, b) {
  4077. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4078. function __() { this.constructor = d; }
  4079. __.prototype = b.prototype;
  4080. d.prototype = new __();
  4081. };
  4082. var BABYLON;
  4083. (function (BABYLON) {
  4084. var PointLight = (function (_super) {
  4085. __extends(PointLight, _super);
  4086. function PointLight(name, position, scene) {
  4087. _super.call(this, name, scene);
  4088. this.position = position;
  4089. }
  4090. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  4091. if (this.parent && this.parent.getWorldMatrix) {
  4092. if (!this._transformedPosition) {
  4093. this._transformedPosition = BABYLON.Vector3.Zero();
  4094. }
  4095. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4096. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  4097. return;
  4098. }
  4099. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  4100. };
  4101. PointLight.prototype.getShadowGenerator = function () {
  4102. return null;
  4103. };
  4104. PointLight.prototype._getWorldMatrix = function () {
  4105. if (!this._worldMatrix) {
  4106. this._worldMatrix = BABYLON.Matrix.Identity();
  4107. }
  4108. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4109. return this._worldMatrix;
  4110. };
  4111. return PointLight;
  4112. })(BABYLON.Light);
  4113. BABYLON.PointLight = PointLight;
  4114. })(BABYLON || (BABYLON = {}));
  4115. var __extends = this.__extends || function (d, b) {
  4116. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4117. function __() { this.constructor = d; }
  4118. __.prototype = b.prototype;
  4119. d.prototype = new __();
  4120. };
  4121. var BABYLON;
  4122. (function (BABYLON) {
  4123. var SpotLight = (function (_super) {
  4124. __extends(SpotLight, _super);
  4125. function SpotLight(name, position, direction, angle, exponent, scene) {
  4126. _super.call(this, name, scene);
  4127. this.position = position;
  4128. this.direction = direction;
  4129. this.angle = angle;
  4130. this.exponent = exponent;
  4131. }
  4132. SpotLight.prototype.setDirectionToTarget = function (target) {
  4133. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4134. return this.direction;
  4135. };
  4136. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  4137. var normalizeDirection;
  4138. if (this.parent && this.parent.getWorldMatrix) {
  4139. if (!this._transformedDirection) {
  4140. this._transformedDirection = BABYLON.Vector3.Zero();
  4141. }
  4142. if (!this._transformedPosition) {
  4143. this._transformedPosition = BABYLON.Vector3.Zero();
  4144. }
  4145. var parentWorldMatrix = this.parent.getWorldMatrix();
  4146. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  4147. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  4148. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  4149. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  4150. } else {
  4151. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  4152. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4153. }
  4154. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  4155. };
  4156. SpotLight.prototype._getWorldMatrix = function () {
  4157. if (!this._worldMatrix) {
  4158. this._worldMatrix = BABYLON.Matrix.Identity();
  4159. }
  4160. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4161. return this._worldMatrix;
  4162. };
  4163. return SpotLight;
  4164. })(BABYLON.Light);
  4165. BABYLON.SpotLight = SpotLight;
  4166. })(BABYLON || (BABYLON = {}));
  4167. var __extends = this.__extends || function (d, b) {
  4168. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4169. function __() { this.constructor = d; }
  4170. __.prototype = b.prototype;
  4171. d.prototype = new __();
  4172. };
  4173. var BABYLON;
  4174. (function (BABYLON) {
  4175. var DirectionalLight = (function (_super) {
  4176. __extends(DirectionalLight, _super);
  4177. function DirectionalLight(name, direction, scene) {
  4178. _super.call(this, name, scene);
  4179. this.direction = direction;
  4180. this.position = direction.scale(-1);
  4181. }
  4182. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  4183. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4184. return this.direction;
  4185. };
  4186. DirectionalLight.prototype._computeTransformedPosition = function () {
  4187. if (this.parent && this.parent.getWorldMatrix) {
  4188. if (!this._transformedPosition) {
  4189. this._transformedPosition = BABYLON.Vector3.Zero();
  4190. }
  4191. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4192. return true;
  4193. }
  4194. return false;
  4195. };
  4196. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  4197. if (this.parent && this.parent.getWorldMatrix) {
  4198. if (!this._transformedDirection) {
  4199. this._transformedDirection = BABYLON.Vector3.Zero();
  4200. }
  4201. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  4202. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  4203. return;
  4204. }
  4205. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  4206. };
  4207. DirectionalLight.prototype._getWorldMatrix = function () {
  4208. if (!this._worldMatrix) {
  4209. this._worldMatrix = BABYLON.Matrix.Identity();
  4210. }
  4211. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4212. return this._worldMatrix;
  4213. };
  4214. return DirectionalLight;
  4215. })(BABYLON.Light);
  4216. BABYLON.DirectionalLight = DirectionalLight;
  4217. })(BABYLON || (BABYLON = {}));
  4218. var BABYLON;
  4219. (function (BABYLON) {
  4220. var ShadowGenerator = (function () {
  4221. function ShadowGenerator(mapSize, light) {
  4222. var _this = this;
  4223. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4224. this._darkness = 0;
  4225. this._transparencyShadow = false;
  4226. this._viewMatrix = BABYLON.Matrix.Zero();
  4227. this._projectionMatrix = BABYLON.Matrix.Zero();
  4228. this._transformMatrix = BABYLON.Matrix.Zero();
  4229. this._worldViewProjection = BABYLON.Matrix.Zero();
  4230. this._light = light;
  4231. this._scene = light.getScene();
  4232. light._shadowGenerator = this;
  4233. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  4234. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4235. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4236. this._shadowMap.renderParticles = false;
  4237. var renderSubMesh = function (subMesh) {
  4238. var mesh = subMesh.getRenderingMesh();
  4239. var scene = _this._scene;
  4240. var engine = scene.getEngine();
  4241. engine.setState(subMesh.getMaterial().backFaceCulling);
  4242. var batch = mesh._getInstancesRenderList(subMesh._id);
  4243. if (batch.mustReturn) {
  4244. return;
  4245. }
  4246. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  4247. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  4248. engine.enableEffect(_this._effect);
  4249. mesh._bind(subMesh, _this._effect, false);
  4250. var material = subMesh.getMaterial();
  4251. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  4252. if (material && material.needAlphaTesting()) {
  4253. var alphaTexture = material.getAlphaTestTexture();
  4254. _this._effect.setTexture("diffuseSampler", alphaTexture);
  4255. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  4256. }
  4257. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  4258. if (useBones) {
  4259. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  4260. }
  4261. if (hardwareInstancedRendering) {
  4262. mesh._renderWithInstances(subMesh, false, batch, _this._effect, engine);
  4263. } else {
  4264. if (batch.renderSelf[subMesh._id]) {
  4265. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  4266. mesh._draw(subMesh, true);
  4267. }
  4268. if (batch.visibleInstances[subMesh._id]) {
  4269. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  4270. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  4271. _this._effect.setMatrix("world", instance.getWorldMatrix());
  4272. mesh._draw(subMesh, true);
  4273. }
  4274. }
  4275. }
  4276. } else {
  4277. _this._shadowMap.resetRefreshCounter();
  4278. }
  4279. };
  4280. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  4281. var index;
  4282. for (index = 0; index < opaqueSubMeshes.length; index++) {
  4283. renderSubMesh(opaqueSubMeshes.data[index]);
  4284. }
  4285. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  4286. renderSubMesh(alphaTestSubMeshes.data[index]);
  4287. }
  4288. if (_this._transparencyShadow) {
  4289. for (index = 0; index < transparentSubMeshes.length; index++) {
  4290. renderSubMesh(transparentSubMeshes.data[index]);
  4291. }
  4292. }
  4293. };
  4294. }
  4295. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  4296. get: function () {
  4297. return ShadowGenerator._FILTER_NONE;
  4298. },
  4299. enumerable: true,
  4300. configurable: true
  4301. });
  4302. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  4303. get: function () {
  4304. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  4305. },
  4306. enumerable: true,
  4307. configurable: true
  4308. });
  4309. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  4310. get: function () {
  4311. return ShadowGenerator._FILTER_POISSONSAMPLING;
  4312. },
  4313. enumerable: true,
  4314. configurable: true
  4315. });
  4316. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  4317. get: function () {
  4318. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4319. },
  4320. set: function (value) {
  4321. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  4322. },
  4323. enumerable: true,
  4324. configurable: true
  4325. });
  4326. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  4327. get: function () {
  4328. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  4329. },
  4330. set: function (value) {
  4331. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  4332. },
  4333. enumerable: true,
  4334. configurable: true
  4335. });
  4336. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  4337. var defines = [];
  4338. if (this.useVarianceShadowMap) {
  4339. defines.push("#define VSM");
  4340. }
  4341. var attribs = [BABYLON.VertexBuffer.PositionKind];
  4342. var mesh = subMesh.getMesh();
  4343. var material = subMesh.getMaterial();
  4344. if (material && material.needAlphaTesting()) {
  4345. defines.push("#define ALPHATEST");
  4346. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  4347. attribs.push(BABYLON.VertexBuffer.UVKind);
  4348. defines.push("#define UV1");
  4349. }
  4350. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  4351. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  4352. defines.push("#define UV2");
  4353. }
  4354. }
  4355. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  4356. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  4357. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  4358. defines.push("#define BONES");
  4359. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  4360. }
  4361. if (useInstances) {
  4362. defines.push("#define INSTANCES");
  4363. attribs.push("world0");
  4364. attribs.push("world1");
  4365. attribs.push("world2");
  4366. attribs.push("world3");
  4367. }
  4368. var join = defines.join("\n");
  4369. if (this._cachedDefines != join) {
  4370. this._cachedDefines = join;
  4371. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  4372. }
  4373. return this._effect.isReady();
  4374. };
  4375. ShadowGenerator.prototype.getShadowMap = function () {
  4376. return this._shadowMap;
  4377. };
  4378. ShadowGenerator.prototype.getLight = function () {
  4379. return this._light;
  4380. };
  4381. ShadowGenerator.prototype.getTransformMatrix = function () {
  4382. var lightPosition = this._light.position;
  4383. var lightDirection = this._light.direction;
  4384. if (this._light._computeTransformedPosition()) {
  4385. lightPosition = this._light._transformedPosition;
  4386. }
  4387. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  4388. this._cachedPosition = lightPosition.clone();
  4389. this._cachedDirection = lightDirection.clone();
  4390. var activeCamera = this._scene.activeCamera;
  4391. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  4392. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  4393. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  4394. }
  4395. return this._transformMatrix;
  4396. };
  4397. ShadowGenerator.prototype.getDarkness = function () {
  4398. return this._darkness;
  4399. };
  4400. ShadowGenerator.prototype.setDarkness = function (darkness) {
  4401. if (darkness >= 1.0)
  4402. this._darkness = 1.0;
  4403. else if (darkness <= 0.0)
  4404. this._darkness = 0.0;
  4405. else
  4406. this._darkness = darkness;
  4407. };
  4408. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  4409. this._transparencyShadow = hasShadow;
  4410. };
  4411. ShadowGenerator.prototype.dispose = function () {
  4412. this._shadowMap.dispose();
  4413. };
  4414. ShadowGenerator._FILTER_NONE = 0;
  4415. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  4416. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  4417. return ShadowGenerator;
  4418. })();
  4419. BABYLON.ShadowGenerator = ShadowGenerator;
  4420. })(BABYLON || (BABYLON = {}));
  4421. var __extends = this.__extends || function (d, b) {
  4422. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4423. function __() { this.constructor = d; }
  4424. __.prototype = b.prototype;
  4425. d.prototype = new __();
  4426. };
  4427. var BABYLON;
  4428. (function (BABYLON) {
  4429. var HemisphericLight = (function (_super) {
  4430. __extends(HemisphericLight, _super);
  4431. function HemisphericLight(name, direction, scene) {
  4432. _super.call(this, name, scene);
  4433. this.direction = direction;
  4434. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  4435. }
  4436. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  4437. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  4438. return this.direction;
  4439. };
  4440. HemisphericLight.prototype.getShadowGenerator = function () {
  4441. return null;
  4442. };
  4443. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  4444. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4445. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  4446. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  4447. };
  4448. HemisphericLight.prototype._getWorldMatrix = function () {
  4449. if (!this._worldMatrix) {
  4450. this._worldMatrix = BABYLON.Matrix.Identity();
  4451. }
  4452. return this._worldMatrix;
  4453. };
  4454. return HemisphericLight;
  4455. })(BABYLON.Light);
  4456. BABYLON.HemisphericLight = HemisphericLight;
  4457. })(BABYLON || (BABYLON = {}));
  4458. var BABYLON;
  4459. (function (BABYLON) {
  4460. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  4461. if (boxMin.x > sphereCenter.x + sphereRadius)
  4462. return false;
  4463. if (sphereCenter.x - sphereRadius > boxMax.x)
  4464. return false;
  4465. if (boxMin.y > sphereCenter.y + sphereRadius)
  4466. return false;
  4467. if (sphereCenter.y - sphereRadius > boxMax.y)
  4468. return false;
  4469. if (boxMin.z > sphereCenter.z + sphereRadius)
  4470. return false;
  4471. if (sphereCenter.z - sphereRadius > boxMax.z)
  4472. return false;
  4473. return true;
  4474. };
  4475. var getLowestRoot = function (a, b, c, maxR) {
  4476. var determinant = b * b - 4.0 * a * c;
  4477. var result = { root: 0, found: false };
  4478. if (determinant < 0)
  4479. return result;
  4480. var sqrtD = Math.sqrt(determinant);
  4481. var r1 = (-b - sqrtD) / (2.0 * a);
  4482. var r2 = (-b + sqrtD) / (2.0 * a);
  4483. if (r1 > r2) {
  4484. var temp = r2;
  4485. r2 = r1;
  4486. r1 = temp;
  4487. }
  4488. if (r1 > 0 && r1 < maxR) {
  4489. result.root = r1;
  4490. result.found = true;
  4491. return result;
  4492. }
  4493. if (r2 > 0 && r2 < maxR) {
  4494. result.root = r2;
  4495. result.found = true;
  4496. return result;
  4497. }
  4498. return result;
  4499. };
  4500. var Collider = (function () {
  4501. function Collider() {
  4502. this.radius = new BABYLON.Vector3(1, 1, 1);
  4503. this.retry = 0;
  4504. this.basePointWorld = BABYLON.Vector3.Zero();
  4505. this.velocityWorld = BABYLON.Vector3.Zero();
  4506. this.normalizedVelocity = BABYLON.Vector3.Zero();
  4507. this._collisionPoint = BABYLON.Vector3.Zero();
  4508. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  4509. this._tempVector = BABYLON.Vector3.Zero();
  4510. this._tempVector2 = BABYLON.Vector3.Zero();
  4511. this._tempVector3 = BABYLON.Vector3.Zero();
  4512. this._tempVector4 = BABYLON.Vector3.Zero();
  4513. this._edge = BABYLON.Vector3.Zero();
  4514. this._baseToVertex = BABYLON.Vector3.Zero();
  4515. this._destinationPoint = BABYLON.Vector3.Zero();
  4516. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  4517. this._displacementVector = BABYLON.Vector3.Zero();
  4518. }
  4519. Collider.prototype._initialize = function (source, dir, e) {
  4520. this.velocity = dir;
  4521. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  4522. this.basePoint = source;
  4523. source.multiplyToRef(this.radius, this.basePointWorld);
  4524. dir.multiplyToRef(this.radius, this.velocityWorld);
  4525. this.velocityWorldLength = this.velocityWorld.length();
  4526. this.epsilon = e;
  4527. this.collisionFound = false;
  4528. };
  4529. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  4530. pa.subtractToRef(point, this._tempVector);
  4531. pb.subtractToRef(point, this._tempVector2);
  4532. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  4533. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4534. if (d < 0)
  4535. return false;
  4536. pc.subtractToRef(point, this._tempVector3);
  4537. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  4538. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4539. if (d < 0)
  4540. return false;
  4541. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  4542. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4543. return d >= 0;
  4544. };
  4545. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  4546. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  4547. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  4548. if (distance > this.velocityWorldLength + max + sphereRadius) {
  4549. return false;
  4550. }
  4551. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  4552. return false;
  4553. return true;
  4554. };
  4555. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  4556. var t0;
  4557. var embeddedInPlane = false;
  4558. if (!subMesh._trianglePlanes) {
  4559. subMesh._trianglePlanes = [];
  4560. }
  4561. if (!subMesh._trianglePlanes[faceIndex]) {
  4562. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  4563. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  4564. }
  4565. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  4566. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  4567. return;
  4568. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  4569. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  4570. if (normalDotVelocity == 0) {
  4571. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  4572. return;
  4573. embeddedInPlane = true;
  4574. t0 = 0;
  4575. } else {
  4576. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4577. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4578. if (t0 > t1) {
  4579. var temp = t1;
  4580. t1 = t0;
  4581. t0 = temp;
  4582. }
  4583. if (t0 > 1.0 || t1 < 0.0)
  4584. return;
  4585. if (t0 < 0)
  4586. t0 = 0;
  4587. if (t0 > 1.0)
  4588. t0 = 1.0;
  4589. }
  4590. this._collisionPoint.copyFromFloats(0, 0, 0);
  4591. var found = false;
  4592. var t = 1.0;
  4593. if (!embeddedInPlane) {
  4594. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  4595. this.velocity.scaleToRef(t0, this._tempVector);
  4596. this._planeIntersectionPoint.addInPlace(this._tempVector);
  4597. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  4598. found = true;
  4599. t = t0;
  4600. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  4601. }
  4602. }
  4603. if (!found) {
  4604. var velocitySquaredLength = this.velocity.lengthSquared();
  4605. var a = velocitySquaredLength;
  4606. this.basePoint.subtractToRef(p1, this._tempVector);
  4607. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4608. var c = this._tempVector.lengthSquared() - 1.0;
  4609. var lowestRoot = getLowestRoot(a, b, c, t);
  4610. if (lowestRoot.found) {
  4611. t = lowestRoot.root;
  4612. found = true;
  4613. this._collisionPoint.copyFrom(p1);
  4614. }
  4615. this.basePoint.subtractToRef(p2, this._tempVector);
  4616. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4617. c = this._tempVector.lengthSquared() - 1.0;
  4618. lowestRoot = getLowestRoot(a, b, c, t);
  4619. if (lowestRoot.found) {
  4620. t = lowestRoot.root;
  4621. found = true;
  4622. this._collisionPoint.copyFrom(p2);
  4623. }
  4624. this.basePoint.subtractToRef(p3, this._tempVector);
  4625. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4626. c = this._tempVector.lengthSquared() - 1.0;
  4627. lowestRoot = getLowestRoot(a, b, c, t);
  4628. if (lowestRoot.found) {
  4629. t = lowestRoot.root;
  4630. found = true;
  4631. this._collisionPoint.copyFrom(p3);
  4632. }
  4633. p2.subtractToRef(p1, this._edge);
  4634. p1.subtractToRef(this.basePoint, this._baseToVertex);
  4635. var edgeSquaredLength = this._edge.lengthSquared();
  4636. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4637. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4638. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4639. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4640. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4641. lowestRoot = getLowestRoot(a, b, c, t);
  4642. if (lowestRoot.found) {
  4643. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4644. if (f >= 0.0 && f <= 1.0) {
  4645. t = lowestRoot.root;
  4646. found = true;
  4647. this._edge.scaleInPlace(f);
  4648. p1.addToRef(this._edge, this._collisionPoint);
  4649. }
  4650. }
  4651. p3.subtractToRef(p2, this._edge);
  4652. p2.subtractToRef(this.basePoint, this._baseToVertex);
  4653. edgeSquaredLength = this._edge.lengthSquared();
  4654. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4655. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4656. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4657. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4658. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4659. lowestRoot = getLowestRoot(a, b, c, t);
  4660. if (lowestRoot.found) {
  4661. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4662. if (f >= 0.0 && f <= 1.0) {
  4663. t = lowestRoot.root;
  4664. found = true;
  4665. this._edge.scaleInPlace(f);
  4666. p2.addToRef(this._edge, this._collisionPoint);
  4667. }
  4668. }
  4669. p1.subtractToRef(p3, this._edge);
  4670. p3.subtractToRef(this.basePoint, this._baseToVertex);
  4671. edgeSquaredLength = this._edge.lengthSquared();
  4672. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4673. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4674. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4675. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4676. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4677. lowestRoot = getLowestRoot(a, b, c, t);
  4678. if (lowestRoot.found) {
  4679. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4680. if (f >= 0.0 && f <= 1.0) {
  4681. t = lowestRoot.root;
  4682. found = true;
  4683. this._edge.scaleInPlace(f);
  4684. p3.addToRef(this._edge, this._collisionPoint);
  4685. }
  4686. }
  4687. }
  4688. if (found) {
  4689. var distToCollision = t * this.velocity.length();
  4690. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  4691. if (!this.intersectionPoint) {
  4692. this.intersectionPoint = this._collisionPoint.clone();
  4693. } else {
  4694. this.intersectionPoint.copyFrom(this._collisionPoint);
  4695. }
  4696. this.nearestDistance = distToCollision;
  4697. this.collisionFound = true;
  4698. this.collidedMesh = subMesh.getMesh();
  4699. }
  4700. }
  4701. };
  4702. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  4703. for (var i = indexStart; i < indexEnd; i += 3) {
  4704. var p1 = pts[indices[i] - decal];
  4705. var p2 = pts[indices[i + 1] - decal];
  4706. var p3 = pts[indices[i + 2] - decal];
  4707. this._testTriangle(i, subMesh, p3, p2, p1);
  4708. }
  4709. };
  4710. Collider.prototype._getResponse = function (pos, vel) {
  4711. pos.addToRef(vel, this._destinationPoint);
  4712. vel.scaleInPlace((this.nearestDistance / vel.length()));
  4713. this.basePoint.addToRef(vel, pos);
  4714. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  4715. this._slidePlaneNormal.normalize();
  4716. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  4717. pos.addInPlace(this._displacementVector);
  4718. this.intersectionPoint.addInPlace(this._displacementVector);
  4719. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  4720. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  4721. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  4722. };
  4723. return Collider;
  4724. })();
  4725. BABYLON.Collider = Collider;
  4726. })(BABYLON || (BABYLON = {}));
  4727. var __extends = this.__extends || function (d, b) {
  4728. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4729. function __() { this.constructor = d; }
  4730. __.prototype = b.prototype;
  4731. d.prototype = new __();
  4732. };
  4733. var BABYLON;
  4734. (function (BABYLON) {
  4735. var Camera = (function (_super) {
  4736. __extends(Camera, _super);
  4737. function Camera(name, position, scene) {
  4738. _super.call(this, name, scene);
  4739. this.position = position;
  4740. this.upVector = BABYLON.Vector3.Up();
  4741. this.orthoLeft = null;
  4742. this.orthoRight = null;
  4743. this.orthoBottom = null;
  4744. this.orthoTop = null;
  4745. this.fov = 0.8;
  4746. this.minZ = 1.0;
  4747. this.maxZ = 10000.0;
  4748. this.inertia = 0.9;
  4749. this.mode = Camera.PERSPECTIVE_CAMERA;
  4750. this.isIntermediate = false;
  4751. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  4752. this.subCameras = [];
  4753. this.layerMask = 0xFFFFFFFF;
  4754. this._computedViewMatrix = BABYLON.Matrix.Identity();
  4755. this._projectionMatrix = new BABYLON.Matrix();
  4756. this._postProcesses = new Array();
  4757. this._postProcessesTakenIndices = [];
  4758. scene.cameras.push(this);
  4759. if (!scene.activeCamera) {
  4760. scene.activeCamera = this;
  4761. }
  4762. }
  4763. Camera.prototype._initCache = function () {
  4764. _super.prototype._initCache.call(this);
  4765. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4766. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4767. this._cache.mode = undefined;
  4768. this._cache.minZ = undefined;
  4769. this._cache.maxZ = undefined;
  4770. this._cache.fov = undefined;
  4771. this._cache.aspectRatio = undefined;
  4772. this._cache.orthoLeft = undefined;
  4773. this._cache.orthoRight = undefined;
  4774. this._cache.orthoBottom = undefined;
  4775. this._cache.orthoTop = undefined;
  4776. this._cache.renderWidth = undefined;
  4777. this._cache.renderHeight = undefined;
  4778. };
  4779. Camera.prototype._updateCache = function (ignoreParentClass) {
  4780. if (!ignoreParentClass) {
  4781. _super.prototype._updateCache.call(this);
  4782. }
  4783. var engine = this.getEngine();
  4784. this._cache.position.copyFrom(this.position);
  4785. this._cache.upVector.copyFrom(this.upVector);
  4786. this._cache.mode = this.mode;
  4787. this._cache.minZ = this.minZ;
  4788. this._cache.maxZ = this.maxZ;
  4789. this._cache.fov = this.fov;
  4790. this._cache.aspectRatio = engine.getAspectRatio(this);
  4791. this._cache.orthoLeft = this.orthoLeft;
  4792. this._cache.orthoRight = this.orthoRight;
  4793. this._cache.orthoBottom = this.orthoBottom;
  4794. this._cache.orthoTop = this.orthoTop;
  4795. this._cache.renderWidth = engine.getRenderWidth();
  4796. this._cache.renderHeight = engine.getRenderHeight();
  4797. };
  4798. Camera.prototype._updateFromScene = function () {
  4799. this.updateCache();
  4800. this._update();
  4801. };
  4802. Camera.prototype._isSynchronized = function () {
  4803. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  4804. };
  4805. Camera.prototype._isSynchronizedViewMatrix = function () {
  4806. if (!_super.prototype._isSynchronized.call(this))
  4807. return false;
  4808. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  4809. };
  4810. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  4811. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  4812. if (!check) {
  4813. return false;
  4814. }
  4815. var engine = this.getEngine();
  4816. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4817. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  4818. } else {
  4819. check = this._cache.orthoLeft === this.orthoLeft && this._cache.orthoRight === this.orthoRight && this._cache.orthoBottom === this.orthoBottom && this._cache.orthoTop === this.orthoTop && this._cache.renderWidth === engine.getRenderWidth() && this._cache.renderHeight === engine.getRenderHeight();
  4820. }
  4821. return check;
  4822. };
  4823. Camera.prototype.attachControl = function (element) {
  4824. };
  4825. Camera.prototype.detachControl = function (element) {
  4826. };
  4827. Camera.prototype._update = function () {
  4828. };
  4829. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  4830. if (typeof insertAt === "undefined") { insertAt = null; }
  4831. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  4832. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  4833. return 0;
  4834. }
  4835. if (insertAt == null || insertAt < 0) {
  4836. this._postProcesses.push(postProcess);
  4837. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  4838. return this._postProcesses.length - 1;
  4839. }
  4840. var add = 0;
  4841. if (this._postProcesses[insertAt]) {
  4842. var start = this._postProcesses.length - 1;
  4843. for (var i = start; i >= insertAt + 1; --i) {
  4844. this._postProcesses[i + 1] = this._postProcesses[i];
  4845. }
  4846. add = 1;
  4847. }
  4848. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  4849. if (this._postProcessesTakenIndices[i] < insertAt) {
  4850. continue;
  4851. }
  4852. start = this._postProcessesTakenIndices.length - 1;
  4853. for (var j = start; j >= i; --j) {
  4854. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  4855. }
  4856. this._postProcessesTakenIndices[i] = insertAt;
  4857. break;
  4858. }
  4859. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  4860. this._postProcessesTakenIndices.push(insertAt);
  4861. }
  4862. var result = insertAt + add;
  4863. this._postProcesses[result] = postProcess;
  4864. return result;
  4865. };
  4866. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  4867. if (typeof atIndices === "undefined") { atIndices = null; }
  4868. var result = [];
  4869. if (!atIndices) {
  4870. var length = this._postProcesses.length;
  4871. for (var i = 0; i < length; i++) {
  4872. if (this._postProcesses[i] !== postProcess) {
  4873. continue;
  4874. }
  4875. delete this._postProcesses[i];
  4876. var index = this._postProcessesTakenIndices.indexOf(i);
  4877. this._postProcessesTakenIndices.splice(index, 1);
  4878. }
  4879. } else {
  4880. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  4881. for (i = 0; i < atIndices.length; i++) {
  4882. var foundPostProcess = this._postProcesses[atIndices[i]];
  4883. if (foundPostProcess !== postProcess) {
  4884. result.push(i);
  4885. continue;
  4886. }
  4887. delete this._postProcesses[atIndices[i]];
  4888. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  4889. this._postProcessesTakenIndices.splice(index, 1);
  4890. }
  4891. }
  4892. return result;
  4893. };
  4894. Camera.prototype.getWorldMatrix = function () {
  4895. if (!this._worldMatrix) {
  4896. this._worldMatrix = BABYLON.Matrix.Identity();
  4897. }
  4898. var viewMatrix = this.getViewMatrix();
  4899. viewMatrix.invertToRef(this._worldMatrix);
  4900. return this._worldMatrix;
  4901. };
  4902. Camera.prototype._getViewMatrix = function () {
  4903. return BABYLON.Matrix.Identity();
  4904. };
  4905. Camera.prototype.getViewMatrix = function () {
  4906. this._computedViewMatrix = this._computeViewMatrix();
  4907. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  4908. return this._computedViewMatrix;
  4909. }
  4910. if (!this._worldMatrix) {
  4911. this._worldMatrix = BABYLON.Matrix.Identity();
  4912. }
  4913. this._computedViewMatrix.invertToRef(this._worldMatrix);
  4914. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  4915. this._computedViewMatrix.invert();
  4916. this._currentRenderId = this.getScene().getRenderId();
  4917. return this._computedViewMatrix;
  4918. };
  4919. Camera.prototype._computeViewMatrix = function (force) {
  4920. if (!force && this._isSynchronizedViewMatrix()) {
  4921. return this._computedViewMatrix;
  4922. }
  4923. this._computedViewMatrix = this._getViewMatrix();
  4924. if (!this.parent || !this.parent.getWorldMatrix) {
  4925. this._currentRenderId = this.getScene().getRenderId();
  4926. }
  4927. return this._computedViewMatrix;
  4928. };
  4929. Camera.prototype.getProjectionMatrix = function (force) {
  4930. if (!force && this._isSynchronizedProjectionMatrix()) {
  4931. return this._projectionMatrix;
  4932. }
  4933. var engine = this.getEngine();
  4934. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4935. if (this.minZ <= 0) {
  4936. this.minZ = 0.1;
  4937. }
  4938. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  4939. return this._projectionMatrix;
  4940. }
  4941. var halfWidth = engine.getRenderWidth() / 2.0;
  4942. var halfHeight = engine.getRenderHeight() / 2.0;
  4943. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  4944. return this._projectionMatrix;
  4945. };
  4946. Camera.prototype.dispose = function () {
  4947. var index = this.getScene().cameras.indexOf(this);
  4948. this.getScene().cameras.splice(index, 1);
  4949. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  4950. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  4951. }
  4952. };
  4953. Camera.PERSPECTIVE_CAMERA = 0;
  4954. Camera.ORTHOGRAPHIC_CAMERA = 1;
  4955. return Camera;
  4956. })(BABYLON.Node);
  4957. BABYLON.Camera = Camera;
  4958. })(BABYLON || (BABYLON = {}));
  4959. var __extends = this.__extends || function (d, b) {
  4960. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4961. function __() { this.constructor = d; }
  4962. __.prototype = b.prototype;
  4963. d.prototype = new __();
  4964. };
  4965. var BABYLON;
  4966. (function (BABYLON) {
  4967. var TargetCamera = (function (_super) {
  4968. __extends(TargetCamera, _super);
  4969. function TargetCamera(name, position, scene) {
  4970. _super.call(this, name, position, scene);
  4971. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  4972. this.cameraRotation = new BABYLON.Vector2(0, 0);
  4973. this.rotation = new BABYLON.Vector3(0, 0, 0);
  4974. this.speed = 2.0;
  4975. this.noRotationConstraint = false;
  4976. this.lockedTarget = null;
  4977. this._currentTarget = BABYLON.Vector3.Zero();
  4978. this._viewMatrix = BABYLON.Matrix.Zero();
  4979. this._camMatrix = BABYLON.Matrix.Zero();
  4980. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  4981. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  4982. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  4983. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  4984. this._lookAtTemp = BABYLON.Matrix.Zero();
  4985. this._tempMatrix = BABYLON.Matrix.Zero();
  4986. }
  4987. TargetCamera.prototype._getLockedTargetPosition = function () {
  4988. if (!this.lockedTarget) {
  4989. return null;
  4990. }
  4991. return this.lockedTarget.position || this.lockedTarget;
  4992. };
  4993. TargetCamera.prototype._initCache = function () {
  4994. _super.prototype._initCache.call(this);
  4995. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4996. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4997. };
  4998. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  4999. if (!ignoreParentClass) {
  5000. _super.prototype._updateCache.call(this);
  5001. }
  5002. var lockedTargetPosition = this._getLockedTargetPosition();
  5003. if (!lockedTargetPosition) {
  5004. this._cache.lockedTarget = null;
  5005. } else {
  5006. if (!this._cache.lockedTarget) {
  5007. this._cache.lockedTarget = lockedTargetPosition.clone();
  5008. } else {
  5009. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  5010. }
  5011. }
  5012. this._cache.rotation.copyFrom(this.rotation);
  5013. };
  5014. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  5015. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  5016. return false;
  5017. }
  5018. var lockedTargetPosition = this._getLockedTargetPosition();
  5019. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  5020. };
  5021. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  5022. return this.speed * ((BABYLON.Tools.GetDeltaTime() / (BABYLON.Tools.GetFps() * 10.0)));
  5023. };
  5024. TargetCamera.prototype.setTarget = function (target) {
  5025. this.upVector.normalize();
  5026. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  5027. this._camMatrix.invert();
  5028. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  5029. var vDir = target.subtract(this.position);
  5030. if (vDir.x >= 0.0) {
  5031. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  5032. } else {
  5033. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  5034. }
  5035. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  5036. if (isNaN(this.rotation.x)) {
  5037. this.rotation.x = 0;
  5038. }
  5039. if (isNaN(this.rotation.y)) {
  5040. this.rotation.y = 0;
  5041. }
  5042. if (isNaN(this.rotation.z)) {
  5043. this.rotation.z = 0;
  5044. }
  5045. };
  5046. TargetCamera.prototype.getTarget = function () {
  5047. return this._currentTarget;
  5048. };
  5049. TargetCamera.prototype._decideIfNeedsToMove = function () {
  5050. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5051. };
  5052. TargetCamera.prototype._updatePosition = function () {
  5053. this.position.addInPlace(this.cameraDirection);
  5054. };
  5055. TargetCamera.prototype._update = function () {
  5056. var needToMove = this._decideIfNeedsToMove();
  5057. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5058. if (needToMove) {
  5059. this._updatePosition();
  5060. }
  5061. if (needToRotate) {
  5062. this.rotation.x += this.cameraRotation.x;
  5063. this.rotation.y += this.cameraRotation.y;
  5064. if (!this.noRotationConstraint) {
  5065. var limit = (Math.PI / 2) * 0.95;
  5066. if (this.rotation.x > limit)
  5067. this.rotation.x = limit;
  5068. if (this.rotation.x < -limit)
  5069. this.rotation.x = -limit;
  5070. }
  5071. }
  5072. if (needToMove) {
  5073. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  5074. this.cameraDirection.x = 0;
  5075. }
  5076. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  5077. this.cameraDirection.y = 0;
  5078. }
  5079. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  5080. this.cameraDirection.z = 0;
  5081. }
  5082. this.cameraDirection.scaleInPlace(this.inertia);
  5083. }
  5084. if (needToRotate) {
  5085. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  5086. this.cameraRotation.x = 0;
  5087. }
  5088. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  5089. this.cameraRotation.y = 0;
  5090. }
  5091. this.cameraRotation.scaleInPlace(this.inertia);
  5092. }
  5093. };
  5094. TargetCamera.prototype._getViewMatrix = function () {
  5095. if (!this.lockedTarget) {
  5096. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  5097. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  5098. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5099. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  5100. this._lookAtTemp.invert();
  5101. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  5102. } else {
  5103. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5104. }
  5105. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  5106. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  5107. } else {
  5108. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  5109. }
  5110. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  5111. return this._viewMatrix;
  5112. };
  5113. return TargetCamera;
  5114. })(BABYLON.Camera);
  5115. BABYLON.TargetCamera = TargetCamera;
  5116. })(BABYLON || (BABYLON = {}));
  5117. var __extends = this.__extends || function (d, b) {
  5118. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5119. function __() { this.constructor = d; }
  5120. __.prototype = b.prototype;
  5121. d.prototype = new __();
  5122. };
  5123. var BABYLON;
  5124. (function (BABYLON) {
  5125. var FollowCamera = (function (_super) {
  5126. __extends(FollowCamera, _super);
  5127. function FollowCamera(name, position, scene) {
  5128. _super.call(this, name, position, scene);
  5129. this.radius = 12;
  5130. this.rotationOffset = 0;
  5131. this.heightOffset = 4;
  5132. this.cameraAcceleration = 0.05;
  5133. this.maxCameraSpeed = 20;
  5134. }
  5135. FollowCamera.prototype.getRadians = function (degrees) {
  5136. return degrees * Math.PI / 180;
  5137. };
  5138. FollowCamera.prototype.follow = function (cameraTarget) {
  5139. if (!cameraTarget)
  5140. return;
  5141. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  5142. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  5143. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  5144. var dx = targetX - this.position.x;
  5145. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  5146. var dz = (targetZ) - this.position.z;
  5147. var vx = dx * this.cameraAcceleration * 2;
  5148. var vy = dy * this.cameraAcceleration;
  5149. var vz = dz * this.cameraAcceleration * 2;
  5150. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  5151. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5152. }
  5153. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  5154. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5155. }
  5156. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  5157. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5158. }
  5159. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  5160. this.setTarget(cameraTarget.position);
  5161. };
  5162. FollowCamera.prototype._update = function () {
  5163. _super.prototype._update.call(this);
  5164. this.follow(this.target);
  5165. };
  5166. return FollowCamera;
  5167. })(BABYLON.TargetCamera);
  5168. BABYLON.FollowCamera = FollowCamera;
  5169. })(BABYLON || (BABYLON = {}));
  5170. var __extends = this.__extends || function (d, b) {
  5171. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5172. function __() { this.constructor = d; }
  5173. __.prototype = b.prototype;
  5174. d.prototype = new __();
  5175. };
  5176. var BABYLON;
  5177. (function (BABYLON) {
  5178. var FreeCamera = (function (_super) {
  5179. __extends(FreeCamera, _super);
  5180. function FreeCamera(name, position, scene) {
  5181. _super.call(this, name, position, scene);
  5182. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  5183. this.keysUp = [38];
  5184. this.keysDown = [40];
  5185. this.keysLeft = [37];
  5186. this.keysRight = [39];
  5187. this.checkCollisions = false;
  5188. this.applyGravity = false;
  5189. this.angularSensibility = 2000.0;
  5190. this._keys = [];
  5191. this._collider = new BABYLON.Collider();
  5192. this._needMoveForGravity = true;
  5193. this._oldPosition = BABYLON.Vector3.Zero();
  5194. this._diffPosition = BABYLON.Vector3.Zero();
  5195. this._newPosition = BABYLON.Vector3.Zero();
  5196. }
  5197. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  5198. var _this = this;
  5199. var previousPosition;
  5200. var engine = this.getEngine();
  5201. if (this._attachedElement) {
  5202. return;
  5203. }
  5204. this._attachedElement = element;
  5205. if (this._onMouseDown === undefined) {
  5206. this._onMouseDown = function (evt) {
  5207. previousPosition = {
  5208. x: evt.clientX,
  5209. y: evt.clientY
  5210. };
  5211. if (!noPreventDefault) {
  5212. evt.preventDefault();
  5213. }
  5214. };
  5215. this._onMouseUp = function (evt) {
  5216. previousPosition = null;
  5217. if (!noPreventDefault) {
  5218. evt.preventDefault();
  5219. }
  5220. };
  5221. this._onMouseOut = function (evt) {
  5222. previousPosition = null;
  5223. _this._keys = [];
  5224. if (!noPreventDefault) {
  5225. evt.preventDefault();
  5226. }
  5227. };
  5228. this._onMouseMove = function (evt) {
  5229. if (!previousPosition && !engine.isPointerLock) {
  5230. return;
  5231. }
  5232. var offsetX;
  5233. var offsetY;
  5234. if (!engine.isPointerLock) {
  5235. offsetX = evt.clientX - previousPosition.x;
  5236. offsetY = evt.clientY - previousPosition.y;
  5237. } else {
  5238. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5239. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5240. }
  5241. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  5242. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  5243. previousPosition = {
  5244. x: evt.clientX,
  5245. y: evt.clientY
  5246. };
  5247. if (!noPreventDefault) {
  5248. evt.preventDefault();
  5249. }
  5250. };
  5251. this._onKeyDown = function (evt) {
  5252. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  5253. var index = _this._keys.indexOf(evt.keyCode);
  5254. if (index === -1) {
  5255. _this._keys.push(evt.keyCode);
  5256. }
  5257. if (!noPreventDefault) {
  5258. evt.preventDefault();
  5259. }
  5260. }
  5261. };
  5262. this._onKeyUp = function (evt) {
  5263. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  5264. var index = _this._keys.indexOf(evt.keyCode);
  5265. if (index >= 0) {
  5266. _this._keys.splice(index, 1);
  5267. }
  5268. if (!noPreventDefault) {
  5269. evt.preventDefault();
  5270. }
  5271. }
  5272. };
  5273. this._onLostFocus = function () {
  5274. _this._keys = [];
  5275. };
  5276. this._reset = function () {
  5277. _this._keys = [];
  5278. previousPosition = null;
  5279. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5280. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  5281. };
  5282. }
  5283. element.addEventListener("mousedown", this._onMouseDown, false);
  5284. element.addEventListener("mouseup", this._onMouseUp, false);
  5285. element.addEventListener("mouseout", this._onMouseOut, false);
  5286. element.addEventListener("mousemove", this._onMouseMove, false);
  5287. BABYLON.Tools.RegisterTopRootEvents([
  5288. { name: "keydown", handler: this._onKeyDown },
  5289. { name: "keyup", handler: this._onKeyUp },
  5290. { name: "blur", handler: this._onLostFocus }
  5291. ]);
  5292. };
  5293. FreeCamera.prototype.detachControl = function (element) {
  5294. if (this._attachedElement != element) {
  5295. return;
  5296. }
  5297. element.removeEventListener("mousedown", this._onMouseDown);
  5298. element.removeEventListener("mouseup", this._onMouseUp);
  5299. element.removeEventListener("mouseout", this._onMouseOut);
  5300. element.removeEventListener("mousemove", this._onMouseMove);
  5301. BABYLON.Tools.UnregisterTopRootEvents([
  5302. { name: "keydown", handler: this._onKeyDown },
  5303. { name: "keyup", handler: this._onKeyUp },
  5304. { name: "blur", handler: this._onLostFocus }
  5305. ]);
  5306. this._attachedElement = null;
  5307. if (this._reset) {
  5308. this._reset();
  5309. }
  5310. };
  5311. FreeCamera.prototype._collideWithWorld = function (velocity) {
  5312. var globalPosition;
  5313. if (this.parent) {
  5314. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  5315. } else {
  5316. globalPosition = this.position;
  5317. }
  5318. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  5319. this._collider.radius = this.ellipsoid;
  5320. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  5321. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  5322. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  5323. this.position.addInPlace(this._diffPosition);
  5324. if (this.onCollide) {
  5325. this.onCollide(this._collider.collidedMesh);
  5326. }
  5327. }
  5328. };
  5329. FreeCamera.prototype._checkInputs = function () {
  5330. if (!this._localDirection) {
  5331. this._localDirection = BABYLON.Vector3.Zero();
  5332. this._transformedDirection = BABYLON.Vector3.Zero();
  5333. }
  5334. for (var index = 0; index < this._keys.length; index++) {
  5335. var keyCode = this._keys[index];
  5336. var speed = this._computeLocalCameraSpeed();
  5337. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5338. this._localDirection.copyFromFloats(-speed, 0, 0);
  5339. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5340. this._localDirection.copyFromFloats(0, 0, speed);
  5341. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5342. this._localDirection.copyFromFloats(speed, 0, 0);
  5343. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5344. this._localDirection.copyFromFloats(0, 0, -speed);
  5345. }
  5346. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  5347. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  5348. this.cameraDirection.addInPlace(this._transformedDirection);
  5349. }
  5350. };
  5351. FreeCamera.prototype._decideIfNeedsToMove = function () {
  5352. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5353. };
  5354. FreeCamera.prototype._updatePosition = function () {
  5355. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  5356. this._collideWithWorld(this.cameraDirection);
  5357. if (this.applyGravity) {
  5358. var oldPosition = this.position;
  5359. this._collideWithWorld(this.getScene().gravity);
  5360. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  5361. }
  5362. } else {
  5363. this.position.addInPlace(this.cameraDirection);
  5364. }
  5365. };
  5366. FreeCamera.prototype._update = function () {
  5367. this._checkInputs();
  5368. _super.prototype._update.call(this);
  5369. };
  5370. return FreeCamera;
  5371. })(BABYLON.TargetCamera);
  5372. BABYLON.FreeCamera = FreeCamera;
  5373. })(BABYLON || (BABYLON = {}));
  5374. var __extends = this.__extends || function (d, b) {
  5375. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5376. function __() { this.constructor = d; }
  5377. __.prototype = b.prototype;
  5378. d.prototype = new __();
  5379. };
  5380. var BABYLON;
  5381. (function (BABYLON) {
  5382. var TouchCamera = (function (_super) {
  5383. __extends(TouchCamera, _super);
  5384. function TouchCamera(name, position, scene) {
  5385. _super.call(this, name, position, scene);
  5386. this._offsetX = null;
  5387. this._offsetY = null;
  5388. this._pointerCount = 0;
  5389. this._pointerPressed = [];
  5390. this.angularSensibility = 200000.0;
  5391. this.moveSensibility = 500.0;
  5392. }
  5393. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5394. var _this = this;
  5395. var previousPosition;
  5396. if (this._attachedCanvas) {
  5397. return;
  5398. }
  5399. this._attachedCanvas = canvas;
  5400. if (this._onPointerDown === undefined) {
  5401. this._onPointerDown = function (evt) {
  5402. if (!noPreventDefault) {
  5403. evt.preventDefault();
  5404. }
  5405. _this._pointerPressed.push(evt.pointerId);
  5406. if (_this._pointerPressed.length !== 1) {
  5407. return;
  5408. }
  5409. previousPosition = {
  5410. x: evt.clientX,
  5411. y: evt.clientY
  5412. };
  5413. };
  5414. this._onPointerUp = function (evt) {
  5415. if (!noPreventDefault) {
  5416. evt.preventDefault();
  5417. }
  5418. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5419. if (index === -1) {
  5420. return;
  5421. }
  5422. _this._pointerPressed.splice(index, 1);
  5423. if (index != 0) {
  5424. return;
  5425. }
  5426. previousPosition = null;
  5427. _this._offsetX = null;
  5428. _this._offsetY = null;
  5429. };
  5430. this._onPointerMove = function (evt) {
  5431. if (!noPreventDefault) {
  5432. evt.preventDefault();
  5433. }
  5434. if (!previousPosition) {
  5435. return;
  5436. }
  5437. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5438. if (index != 0) {
  5439. return;
  5440. }
  5441. _this._offsetX = evt.clientX - previousPosition.x;
  5442. _this._offsetY = -(evt.clientY - previousPosition.y);
  5443. };
  5444. this._onLostFocus = function () {
  5445. _this._offsetX = null;
  5446. _this._offsetY = null;
  5447. };
  5448. }
  5449. canvas.addEventListener("pointerdown", this._onPointerDown);
  5450. canvas.addEventListener("pointerup", this._onPointerUp);
  5451. canvas.addEventListener("pointerout", this._onPointerUp);
  5452. canvas.addEventListener("pointermove", this._onPointerMove);
  5453. BABYLON.Tools.RegisterTopRootEvents([
  5454. { name: "blur", handler: this._onLostFocus }
  5455. ]);
  5456. };
  5457. TouchCamera.prototype.detachControl = function (canvas) {
  5458. if (this._attachedCanvas != canvas) {
  5459. return;
  5460. }
  5461. canvas.removeEventListener("pointerdown", this._onPointerDown);
  5462. canvas.removeEventListener("pointerup", this._onPointerUp);
  5463. canvas.removeEventListener("pointerout", this._onPointerUp);
  5464. canvas.removeEventListener("pointermove", this._onPointerMove);
  5465. BABYLON.Tools.UnregisterTopRootEvents([
  5466. { name: "blur", handler: this._onLostFocus }
  5467. ]);
  5468. this._attachedCanvas = null;
  5469. };
  5470. TouchCamera.prototype._checkInputs = function () {
  5471. if (!this._offsetX) {
  5472. return;
  5473. }
  5474. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  5475. if (this._pointerPressed.length > 1) {
  5476. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  5477. } else {
  5478. var speed = this._computeLocalCameraSpeed();
  5479. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5480. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5481. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5482. }
  5483. };
  5484. return TouchCamera;
  5485. })(BABYLON.FreeCamera);
  5486. BABYLON.TouchCamera = TouchCamera;
  5487. })(BABYLON || (BABYLON = {}));
  5488. var __extends = this.__extends || function (d, b) {
  5489. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5490. function __() { this.constructor = d; }
  5491. __.prototype = b.prototype;
  5492. d.prototype = new __();
  5493. };
  5494. var BABYLON;
  5495. (function (BABYLON) {
  5496. var DeviceOrientationCamera = (function (_super) {
  5497. __extends(DeviceOrientationCamera, _super);
  5498. function DeviceOrientationCamera(name, position, scene) {
  5499. var _this = this;
  5500. _super.call(this, name, position, scene);
  5501. this._offsetX = null;
  5502. this._offsetY = null;
  5503. this._orientationGamma = 0;
  5504. this._orientationBeta = 0;
  5505. this._initialOrientationGamma = 0;
  5506. this._initialOrientationBeta = 0;
  5507. this.angularSensibility = 10000.0;
  5508. this.moveSensibility = 50.0;
  5509. window.addEventListener("resize", function () {
  5510. _this._initialOrientationGamma = null;
  5511. }, false);
  5512. }
  5513. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5514. var _this = this;
  5515. if (this._attachedCanvas) {
  5516. return;
  5517. }
  5518. this._attachedCanvas = canvas;
  5519. if (!this._orientationChanged) {
  5520. this._orientationChanged = function (evt) {
  5521. if (!_this._initialOrientationGamma) {
  5522. _this._initialOrientationGamma = evt.gamma;
  5523. _this._initialOrientationBeta = evt.beta;
  5524. }
  5525. _this._orientationGamma = evt.gamma;
  5526. _this._orientationBeta = evt.beta;
  5527. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  5528. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  5529. };
  5530. }
  5531. window.addEventListener("deviceorientation", this._orientationChanged);
  5532. };
  5533. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  5534. if (this._attachedCanvas != canvas) {
  5535. return;
  5536. }
  5537. window.removeEventListener("deviceorientation", this._orientationChanged);
  5538. this._attachedCanvas = null;
  5539. this._orientationGamma = 0;
  5540. this._orientationBeta = 0;
  5541. this._initialOrientationGamma = 0;
  5542. this._initialOrientationBeta = 0;
  5543. };
  5544. DeviceOrientationCamera.prototype._checkInputs = function () {
  5545. if (!this._offsetX) {
  5546. return;
  5547. }
  5548. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  5549. var speed = this._computeLocalCameraSpeed();
  5550. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5551. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5552. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5553. };
  5554. return DeviceOrientationCamera;
  5555. })(BABYLON.FreeCamera);
  5556. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  5557. })(BABYLON || (BABYLON = {}));
  5558. var __extends = this.__extends || function (d, b) {
  5559. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5560. function __() { this.constructor = d; }
  5561. __.prototype = b.prototype;
  5562. d.prototype = new __();
  5563. };
  5564. var BABYLON;
  5565. (function (BABYLON) {
  5566. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  5567. var ArcRotateCamera = (function (_super) {
  5568. __extends(ArcRotateCamera, _super);
  5569. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  5570. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  5571. this.alpha = alpha;
  5572. this.beta = beta;
  5573. this.radius = radius;
  5574. this.target = target;
  5575. this.inertialAlphaOffset = 0;
  5576. this.inertialBetaOffset = 0;
  5577. this.inertialRadiusOffset = 0;
  5578. this.lowerAlphaLimit = null;
  5579. this.upperAlphaLimit = null;
  5580. this.lowerBetaLimit = 0.01;
  5581. this.upperBetaLimit = Math.PI;
  5582. this.lowerRadiusLimit = null;
  5583. this.upperRadiusLimit = null;
  5584. this.angularSensibility = 1000.0;
  5585. this.wheelPrecision = 3.0;
  5586. this.keysUp = [38];
  5587. this.keysDown = [40];
  5588. this.keysLeft = [37];
  5589. this.keysRight = [39];
  5590. this.zoomOnFactor = 1;
  5591. this._keys = [];
  5592. this._viewMatrix = new BABYLON.Matrix();
  5593. this.checkCollisions = false;
  5594. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  5595. this._collider = new BABYLON.Collider();
  5596. this._previousPosition = BABYLON.Vector3.Zero();
  5597. this._collisionVelocity = BABYLON.Vector3.Zero();
  5598. this._newPosition = BABYLON.Vector3.Zero();
  5599. this.pinchPrecision = 20;
  5600. this.getViewMatrix();
  5601. }
  5602. ArcRotateCamera.prototype._getTargetPosition = function () {
  5603. return this.target.position || this.target;
  5604. };
  5605. ArcRotateCamera.prototype._initCache = function () {
  5606. _super.prototype._initCache.call(this);
  5607. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5608. this._cache.alpha = undefined;
  5609. this._cache.beta = undefined;
  5610. this._cache.radius = undefined;
  5611. };
  5612. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  5613. if (!ignoreParentClass) {
  5614. _super.prototype._updateCache.call(this);
  5615. }
  5616. this._cache.target.copyFrom(this._getTargetPosition());
  5617. this._cache.alpha = this.alpha;
  5618. this._cache.beta = this.beta;
  5619. this._cache.radius = this.radius;
  5620. };
  5621. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  5622. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  5623. return false;
  5624. return this._cache.target.equals(this._getTargetPosition()) && this._cache.alpha === this.alpha && this._cache.beta === this.beta && this._cache.radius === this.radius;
  5625. };
  5626. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  5627. var _this = this;
  5628. var previousPosition;
  5629. var pointerId;
  5630. var pinchStarted = false;
  5631. var pinchPointX1, pinchPointX2;
  5632. if (this._attachedElement) {
  5633. return;
  5634. }
  5635. this._attachedElement = element;
  5636. var engine = this.getEngine();
  5637. if (this._onPointerDown === undefined) {
  5638. this._onPointerDown = function (evt) {
  5639. if (pointerId) {
  5640. return;
  5641. }
  5642. pointerId = evt.pointerId;
  5643. previousPosition = {
  5644. x: evt.clientX,
  5645. y: evt.clientY
  5646. };
  5647. if (!noPreventDefault) {
  5648. evt.preventDefault();
  5649. }
  5650. };
  5651. this._onPointerUp = function (evt) {
  5652. previousPosition = null;
  5653. pointerId = null;
  5654. if (!noPreventDefault) {
  5655. evt.preventDefault();
  5656. }
  5657. };
  5658. this._onPointerMove = function (evt) {
  5659. if (!previousPosition) {
  5660. return;
  5661. }
  5662. if (pointerId !== evt.pointerId) {
  5663. return;
  5664. }
  5665. if (pinchStarted) {
  5666. return;
  5667. }
  5668. var offsetX = evt.clientX - previousPosition.x;
  5669. var offsetY = evt.clientY - previousPosition.y;
  5670. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5671. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5672. previousPosition = {
  5673. x: evt.clientX,
  5674. y: evt.clientY
  5675. };
  5676. if (!noPreventDefault) {
  5677. evt.preventDefault();
  5678. }
  5679. };
  5680. this._onMouseMove = function (evt) {
  5681. if (!engine.isPointerLock) {
  5682. return;
  5683. }
  5684. if (pinchStarted) {
  5685. return;
  5686. }
  5687. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5688. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5689. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5690. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5691. if (!noPreventDefault) {
  5692. evt.preventDefault();
  5693. }
  5694. };
  5695. this._wheel = function (event) {
  5696. var delta = 0;
  5697. if (event.wheelDelta) {
  5698. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  5699. } else if (event.detail) {
  5700. delta = -event.detail / _this.wheelPrecision;
  5701. }
  5702. if (delta)
  5703. _this.inertialRadiusOffset += delta;
  5704. if (event.preventDefault) {
  5705. if (!noPreventDefault) {
  5706. event.preventDefault();
  5707. }
  5708. }
  5709. };
  5710. this._onKeyDown = function (evt) {
  5711. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  5712. var index = _this._keys.indexOf(evt.keyCode);
  5713. if (index === -1) {
  5714. _this._keys.push(evt.keyCode);
  5715. }
  5716. if (evt.preventDefault) {
  5717. if (!noPreventDefault) {
  5718. evt.preventDefault();
  5719. }
  5720. }
  5721. }
  5722. };
  5723. this._onKeyUp = function (evt) {
  5724. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  5725. var index = _this._keys.indexOf(evt.keyCode);
  5726. if (index >= 0) {
  5727. _this._keys.splice(index, 1);
  5728. }
  5729. if (evt.preventDefault) {
  5730. if (!noPreventDefault) {
  5731. evt.preventDefault();
  5732. }
  5733. }
  5734. }
  5735. };
  5736. this._onLostFocus = function () {
  5737. _this._keys = [];
  5738. pointerId = null;
  5739. };
  5740. this._onGestureStart = function (e) {
  5741. if (window.MSGesture === undefined) {
  5742. return;
  5743. }
  5744. if (!_this._MSGestureHandler) {
  5745. _this._MSGestureHandler = new MSGesture();
  5746. _this._MSGestureHandler.target = element;
  5747. }
  5748. _this._MSGestureHandler.addPointer(e.pointerId);
  5749. };
  5750. this._onGesture = function (e) {
  5751. _this.radius *= e.scale;
  5752. if (e.preventDefault) {
  5753. if (!noPreventDefault) {
  5754. e.stopPropagation();
  5755. e.preventDefault();
  5756. }
  5757. }
  5758. };
  5759. this._reset = function () {
  5760. _this._keys = [];
  5761. _this.inertialAlphaOffset = 0;
  5762. _this.inertialBetaOffset = 0;
  5763. _this.inertialRadiusOffset = 0;
  5764. previousPosition = null;
  5765. pointerId = null;
  5766. };
  5767. this._touchStart = function (event) {
  5768. if (event.touches.length == 2) {
  5769. pinchStarted = true;
  5770. _this._pinchStart(event);
  5771. }
  5772. };
  5773. this._touchMove = function (event) {
  5774. if (pinchStarted) {
  5775. _this._pinchMove(event);
  5776. }
  5777. };
  5778. this._touchEnd = function (event) {
  5779. if (pinchStarted) {
  5780. _this._pinchEnd(event);
  5781. }
  5782. };
  5783. this._pinchStart = function (event) {
  5784. pinchPointX1 = event.touches[0].clientX;
  5785. pinchPointX2 = event.touches[1].clientX;
  5786. pinchStarted = true;
  5787. };
  5788. this._pinchMove = function (event) {
  5789. var delta = 0;
  5790. var direction = 1;
  5791. var distanceXOrigine, distanceXNow;
  5792. if (event.touches.length != 2)
  5793. return;
  5794. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  5795. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  5796. if (distanceXNow < distanceXOrigine) {
  5797. direction = -1;
  5798. }
  5799. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  5800. _this.inertialRadiusOffset += delta;
  5801. pinchPointX1 = event.touches[0].clientX;
  5802. pinchPointX2 = event.touches[1].clientX;
  5803. };
  5804. this._pinchEnd = function (event) {
  5805. pinchStarted = false;
  5806. };
  5807. }
  5808. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  5809. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  5810. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  5811. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  5812. element.addEventListener("mousemove", this._onMouseMove, false);
  5813. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  5814. element.addEventListener("MSGestureChange", this._onGesture, false);
  5815. element.addEventListener('mousewheel', this._wheel, false);
  5816. element.addEventListener('DOMMouseScroll', this._wheel, false);
  5817. element.addEventListener('touchstart', this._touchStart, false);
  5818. element.addEventListener('touchmove', this._touchMove, false);
  5819. element.addEventListener('touchend', this._touchEnd, false);
  5820. BABYLON.Tools.RegisterTopRootEvents([
  5821. { name: "keydown", handler: this._onKeyDown },
  5822. { name: "keyup", handler: this._onKeyUp },
  5823. { name: "blur", handler: this._onLostFocus }
  5824. ]);
  5825. };
  5826. ArcRotateCamera.prototype.detachControl = function (element) {
  5827. if (this._attachedElement != element) {
  5828. return;
  5829. }
  5830. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  5831. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  5832. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  5833. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  5834. element.removeEventListener("mousemove", this._onMouseMove);
  5835. element.removeEventListener("MSPointerDown", this._onGestureStart);
  5836. element.removeEventListener("MSGestureChange", this._onGesture);
  5837. element.removeEventListener('mousewheel', this._wheel);
  5838. element.removeEventListener('DOMMouseScroll', this._wheel);
  5839. element.removeEventListener('touchstart', this._touchStart);
  5840. element.removeEventListener('touchmove', this._touchMove);
  5841. element.removeEventListener('touchend', this._touchEnd);
  5842. BABYLON.Tools.UnregisterTopRootEvents([
  5843. { name: "keydown", handler: this._onKeyDown },
  5844. { name: "keyup", handler: this._onKeyUp },
  5845. { name: "blur", handler: this._onLostFocus }
  5846. ]);
  5847. this._MSGestureHandler = null;
  5848. this._attachedElement = null;
  5849. if (this._reset) {
  5850. this._reset();
  5851. }
  5852. };
  5853. ArcRotateCamera.prototype._update = function () {
  5854. for (var index = 0; index < this._keys.length; index++) {
  5855. var keyCode = this._keys[index];
  5856. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5857. this.inertialAlphaOffset -= 0.01;
  5858. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5859. this.inertialBetaOffset -= 0.01;
  5860. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5861. this.inertialAlphaOffset += 0.01;
  5862. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5863. this.inertialBetaOffset += 0.01;
  5864. }
  5865. }
  5866. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  5867. this.alpha += this.inertialAlphaOffset;
  5868. this.beta += this.inertialBetaOffset;
  5869. this.radius -= this.inertialRadiusOffset;
  5870. this.inertialAlphaOffset *= this.inertia;
  5871. this.inertialBetaOffset *= this.inertia;
  5872. this.inertialRadiusOffset *= this.inertia;
  5873. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  5874. this.inertialAlphaOffset = 0;
  5875. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  5876. this.inertialBetaOffset = 0;
  5877. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  5878. this.inertialRadiusOffset = 0;
  5879. }
  5880. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  5881. this.alpha = this.lowerAlphaLimit;
  5882. }
  5883. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  5884. this.alpha = this.upperAlphaLimit;
  5885. }
  5886. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  5887. this.beta = this.lowerBetaLimit;
  5888. }
  5889. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  5890. this.beta = this.upperBetaLimit;
  5891. }
  5892. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  5893. this.radius = this.lowerRadiusLimit;
  5894. }
  5895. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  5896. this.radius = this.upperRadiusLimit;
  5897. }
  5898. };
  5899. ArcRotateCamera.prototype.setPosition = function (position) {
  5900. var radiusv3 = position.subtract(this._getTargetPosition());
  5901. this.radius = radiusv3.length();
  5902. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  5903. if (radiusv3.z < 0) {
  5904. this.alpha = 2 * Math.PI - this.alpha;
  5905. }
  5906. this.beta = Math.acos(radiusv3.y / this.radius);
  5907. };
  5908. ArcRotateCamera.prototype._getViewMatrix = function () {
  5909. var cosa = Math.cos(this.alpha);
  5910. var sina = Math.sin(this.alpha);
  5911. var cosb = Math.cos(this.beta);
  5912. var sinb = Math.sin(this.beta);
  5913. var target = this._getTargetPosition();
  5914. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  5915. if (this.checkCollisions) {
  5916. this._collider.radius = this.collisionRadius;
  5917. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  5918. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  5919. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  5920. this.position.copyFrom(this._previousPosition);
  5921. this.alpha = this._previousAlpha;
  5922. this.beta = this._previousBeta;
  5923. this.radius = this._previousRadius;
  5924. if (this.onCollide) {
  5925. this.onCollide(this._collider.collidedMesh);
  5926. }
  5927. }
  5928. }
  5929. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  5930. this._previousAlpha = this.alpha;
  5931. this._previousBeta = this.beta;
  5932. this._previousRadius = this.radius;
  5933. this._previousPosition.copyFrom(this.position);
  5934. return this._viewMatrix;
  5935. };
  5936. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  5937. meshes = meshes || this.getScene().meshes;
  5938. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  5939. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  5940. this.radius = distance * this.zoomOnFactor;
  5941. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  5942. };
  5943. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  5944. var meshesOrMinMaxVector;
  5945. var distance;
  5946. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  5947. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  5948. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  5949. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  5950. } else {
  5951. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  5952. distance = meshesOrMinMaxVectorAndDistance.distance;
  5953. }
  5954. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  5955. this.maxZ = distance * 2;
  5956. };
  5957. return ArcRotateCamera;
  5958. })(BABYLON.Camera);
  5959. BABYLON.ArcRotateCamera = ArcRotateCamera;
  5960. })(BABYLON || (BABYLON = {}));
  5961. var BABYLON;
  5962. (function (BABYLON) {
  5963. var Scene = (function () {
  5964. function Scene(engine) {
  5965. this.autoClear = true;
  5966. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  5967. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  5968. this.forceWireframe = false;
  5969. this.cameraToUseForPointers = null;
  5970. this.fogMode = BABYLON.Scene.FOGMODE_NONE;
  5971. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  5972. this.fogDensity = 0.1;
  5973. this.fogStart = 0;
  5974. this.fogEnd = 1000.0;
  5975. this.lightsEnabled = true;
  5976. this.lights = new Array();
  5977. this.cameras = new Array();
  5978. this.activeCameras = new Array();
  5979. this.meshes = new Array();
  5980. this._geometries = new Array();
  5981. this.materials = new Array();
  5982. this.multiMaterials = new Array();
  5983. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  5984. this.texturesEnabled = true;
  5985. this.textures = new Array();
  5986. this.particlesEnabled = true;
  5987. this.particleSystems = new Array();
  5988. this.spriteManagers = new Array();
  5989. this.layers = new Array();
  5990. this.skeletons = new Array();
  5991. this.lensFlareSystems = new Array();
  5992. this.collisionsEnabled = true;
  5993. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  5994. this.postProcessesEnabled = true;
  5995. this.renderTargetsEnabled = true;
  5996. this.customRenderTargets = new Array();
  5997. this.importedMeshesFiles = new Array();
  5998. this._actionManagers = new Array();
  5999. this._meshesForIntersections = new BABYLON.SmartArray(256);
  6000. this._totalVertices = 0;
  6001. this._activeVertices = 0;
  6002. this._activeParticles = 0;
  6003. this._lastFrameDuration = 0;
  6004. this._evaluateActiveMeshesDuration = 0;
  6005. this._renderTargetsDuration = 0;
  6006. this._particlesDuration = 0;
  6007. this._renderDuration = 0;
  6008. this._spritesDuration = 0;
  6009. this._animationRatio = 0;
  6010. this._renderId = 0;
  6011. this._executeWhenReadyTimeoutId = -1;
  6012. this._toBeDisposed = new BABYLON.SmartArray(256);
  6013. this._onReadyCallbacks = new Array();
  6014. this._pendingData = [];
  6015. this._onBeforeRenderCallbacks = new Array();
  6016. this._activeMeshes = new BABYLON.SmartArray(256);
  6017. this._processedMaterials = new BABYLON.SmartArray(256);
  6018. this._renderTargets = new BABYLON.SmartArray(256);
  6019. this._activeParticleSystems = new BABYLON.SmartArray(256);
  6020. this._activeSkeletons = new BABYLON.SmartArray(32);
  6021. this._activeAnimatables = new Array();
  6022. this._transformMatrix = BABYLON.Matrix.Zero();
  6023. this._scaledPosition = BABYLON.Vector3.Zero();
  6024. this._scaledVelocity = BABYLON.Vector3.Zero();
  6025. this._engine = engine;
  6026. engine.scenes.push(this);
  6027. this._renderingManager = new BABYLON.RenderingManager(this);
  6028. this.postProcessManager = new BABYLON.PostProcessManager(this);
  6029. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  6030. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  6031. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  6032. this.attachControl();
  6033. }
  6034. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  6035. get: function () {
  6036. return this._meshUnderPointer;
  6037. },
  6038. enumerable: true,
  6039. configurable: true
  6040. });
  6041. Object.defineProperty(Scene.prototype, "pointerX", {
  6042. get: function () {
  6043. return this._pointerX;
  6044. },
  6045. enumerable: true,
  6046. configurable: true
  6047. });
  6048. Object.defineProperty(Scene.prototype, "pointerY", {
  6049. get: function () {
  6050. return this._pointerY;
  6051. },
  6052. enumerable: true,
  6053. configurable: true
  6054. });
  6055. Scene.prototype.getBoundingBoxRenderer = function () {
  6056. return this._boundingBoxRenderer;
  6057. };
  6058. Scene.prototype.getOutlineRenderer = function () {
  6059. return this._outlineRenderer;
  6060. };
  6061. Scene.prototype.getEngine = function () {
  6062. return this._engine;
  6063. };
  6064. Scene.prototype.getTotalVertices = function () {
  6065. return this._totalVertices;
  6066. };
  6067. Scene.prototype.getActiveVertices = function () {
  6068. return this._activeVertices;
  6069. };
  6070. Scene.prototype.getActiveParticles = function () {
  6071. return this._activeParticles;
  6072. };
  6073. Scene.prototype.getLastFrameDuration = function () {
  6074. return this._lastFrameDuration;
  6075. };
  6076. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  6077. return this._evaluateActiveMeshesDuration;
  6078. };
  6079. Scene.prototype.getActiveMeshes = function () {
  6080. return this._activeMeshes;
  6081. };
  6082. Scene.prototype.getRenderTargetsDuration = function () {
  6083. return this._renderTargetsDuration;
  6084. };
  6085. Scene.prototype.getRenderDuration = function () {
  6086. return this._renderDuration;
  6087. };
  6088. Scene.prototype.getParticlesDuration = function () {
  6089. return this._particlesDuration;
  6090. };
  6091. Scene.prototype.getSpritesDuration = function () {
  6092. return this._spritesDuration;
  6093. };
  6094. Scene.prototype.getAnimationRatio = function () {
  6095. return this._animationRatio;
  6096. };
  6097. Scene.prototype.getRenderId = function () {
  6098. return this._renderId;
  6099. };
  6100. Scene.prototype._updatePointerPosition = function (evt) {
  6101. var canvasRect = this._engine.getRenderingCanvasClientRect();
  6102. this._pointerX = evt.clientX - canvasRect.left;
  6103. this._pointerY = evt.clientY - canvasRect.top;
  6104. if (this.cameraToUseForPointers) {
  6105. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  6106. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  6107. }
  6108. };
  6109. Scene.prototype.attachControl = function () {
  6110. var _this = this;
  6111. this._onPointerMove = function (evt) {
  6112. var canvas = _this._engine.getRenderingCanvas();
  6113. _this._updatePointerPosition(evt);
  6114. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  6115. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  6116. }, false, _this.cameraToUseForPointers);
  6117. if (pickResult.hit) {
  6118. _this._meshUnderPointer = pickResult.pickedMesh;
  6119. _this.setPointerOverMesh(pickResult.pickedMesh);
  6120. canvas.style.cursor = "pointer";
  6121. } else {
  6122. _this.setPointerOverMesh(null);
  6123. canvas.style.cursor = "";
  6124. _this._meshUnderPointer = null;
  6125. }
  6126. };
  6127. this._onPointerDown = function (evt) {
  6128. var predicate = null;
  6129. if (!_this.onPointerDown) {
  6130. predicate = function (mesh) {
  6131. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  6132. };
  6133. }
  6134. _this._updatePointerPosition(evt);
  6135. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  6136. if (pickResult.hit) {
  6137. if (pickResult.pickedMesh.actionManager) {
  6138. switch (evt.button) {
  6139. case 0:
  6140. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6141. break;
  6142. case 1:
  6143. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6144. break;
  6145. case 2:
  6146. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6147. break;
  6148. }
  6149. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6150. }
  6151. }
  6152. if (_this.onPointerDown) {
  6153. _this.onPointerDown(evt, pickResult);
  6154. }
  6155. };
  6156. this._onKeyDown = function (evt) {
  6157. if (_this.actionManager) {
  6158. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6159. }
  6160. };
  6161. this._onKeyUp = function (evt) {
  6162. if (_this.actionManager) {
  6163. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6164. }
  6165. };
  6166. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6167. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6168. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6169. window.addEventListener("keydown", this._onKeyDown, false);
  6170. window.addEventListener("keyup", this._onKeyUp, false);
  6171. };
  6172. Scene.prototype.detachControl = function () {
  6173. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6174. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  6175. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  6176. window.removeEventListener("keydown", this._onKeyDown);
  6177. window.removeEventListener("keyup", this._onKeyUp);
  6178. };
  6179. Scene.prototype.isReady = function () {
  6180. if (this._pendingData.length > 0) {
  6181. return false;
  6182. }
  6183. for (var index = 0; index < this._geometries.length; index++) {
  6184. var geometry = this._geometries[index];
  6185. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  6186. return false;
  6187. }
  6188. }
  6189. for (index = 0; index < this.meshes.length; index++) {
  6190. var mesh = this.meshes[index];
  6191. if (!mesh.isReady()) {
  6192. return false;
  6193. }
  6194. var mat = mesh.material;
  6195. if (mat) {
  6196. if (!mat.isReady(mesh)) {
  6197. return false;
  6198. }
  6199. }
  6200. }
  6201. return true;
  6202. };
  6203. Scene.prototype.registerBeforeRender = function (func) {
  6204. this._onBeforeRenderCallbacks.push(func);
  6205. };
  6206. Scene.prototype.unregisterBeforeRender = function (func) {
  6207. var index = this._onBeforeRenderCallbacks.indexOf(func);
  6208. if (index > -1) {
  6209. this._onBeforeRenderCallbacks.splice(index, 1);
  6210. }
  6211. };
  6212. Scene.prototype._addPendingData = function (data) {
  6213. this._pendingData.push(data);
  6214. };
  6215. Scene.prototype._removePendingData = function (data) {
  6216. var index = this._pendingData.indexOf(data);
  6217. if (index !== -1) {
  6218. this._pendingData.splice(index, 1);
  6219. }
  6220. };
  6221. Scene.prototype.getWaitingItemsCount = function () {
  6222. return this._pendingData.length;
  6223. };
  6224. Scene.prototype.executeWhenReady = function (func) {
  6225. var _this = this;
  6226. this._onReadyCallbacks.push(func);
  6227. if (this._executeWhenReadyTimeoutId !== -1) {
  6228. return;
  6229. }
  6230. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6231. _this._checkIsReady();
  6232. }, 150);
  6233. };
  6234. Scene.prototype._checkIsReady = function () {
  6235. var _this = this;
  6236. if (this.isReady()) {
  6237. this._onReadyCallbacks.forEach(function (func) {
  6238. func();
  6239. });
  6240. this._onReadyCallbacks = [];
  6241. this._executeWhenReadyTimeoutId = -1;
  6242. return;
  6243. }
  6244. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6245. _this._checkIsReady();
  6246. }, 150);
  6247. };
  6248. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  6249. if (speedRatio === undefined) {
  6250. speedRatio = 1.0;
  6251. }
  6252. this.stopAnimation(target);
  6253. if (!animatable) {
  6254. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  6255. }
  6256. if (target.animations) {
  6257. animatable.appendAnimations(target, target.animations);
  6258. }
  6259. if (target.getAnimatables) {
  6260. var animatables = target.getAnimatables();
  6261. for (var index = 0; index < animatables.length; index++) {
  6262. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  6263. }
  6264. }
  6265. return animatable;
  6266. };
  6267. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  6268. if (speedRatio === undefined) {
  6269. speedRatio = 1.0;
  6270. }
  6271. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  6272. return animatable;
  6273. };
  6274. Scene.prototype.getAnimatableByTarget = function (target) {
  6275. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6276. if (this._activeAnimatables[index].target === target) {
  6277. return this._activeAnimatables[index];
  6278. }
  6279. }
  6280. return null;
  6281. };
  6282. Scene.prototype.stopAnimation = function (target) {
  6283. var animatable = this.getAnimatableByTarget(target);
  6284. if (animatable) {
  6285. animatable.stop();
  6286. }
  6287. };
  6288. Scene.prototype._animate = function () {
  6289. if (!this._animationStartDate) {
  6290. this._animationStartDate = new Date().getTime();
  6291. }
  6292. var now = new Date().getTime();
  6293. var delay = now - this._animationStartDate;
  6294. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6295. if (!this._activeAnimatables[index]._animate(delay)) {
  6296. this._activeAnimatables.splice(index, 1);
  6297. index--;
  6298. }
  6299. }
  6300. };
  6301. Scene.prototype.getViewMatrix = function () {
  6302. return this._viewMatrix;
  6303. };
  6304. Scene.prototype.getProjectionMatrix = function () {
  6305. return this._projectionMatrix;
  6306. };
  6307. Scene.prototype.getTransformMatrix = function () {
  6308. return this._transformMatrix;
  6309. };
  6310. Scene.prototype.setTransformMatrix = function (view, projection) {
  6311. this._viewMatrix = view;
  6312. this._projectionMatrix = projection;
  6313. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6314. };
  6315. Scene.prototype.setActiveCameraByID = function (id) {
  6316. var camera = this.getCameraByID(id);
  6317. if (camera) {
  6318. this.activeCamera = camera;
  6319. return camera;
  6320. }
  6321. return null;
  6322. };
  6323. Scene.prototype.setActiveCameraByName = function (name) {
  6324. var camera = this.getCameraByName(name);
  6325. if (camera) {
  6326. this.activeCamera = camera;
  6327. return camera;
  6328. }
  6329. return null;
  6330. };
  6331. Scene.prototype.getMaterialByID = function (id) {
  6332. for (var index = 0; index < this.materials.length; index++) {
  6333. if (this.materials[index].id === id) {
  6334. return this.materials[index];
  6335. }
  6336. }
  6337. return null;
  6338. };
  6339. Scene.prototype.getMaterialByName = function (name) {
  6340. for (var index = 0; index < this.materials.length; index++) {
  6341. if (this.materials[index].name === name) {
  6342. return this.materials[index];
  6343. }
  6344. }
  6345. return null;
  6346. };
  6347. Scene.prototype.getCameraByID = function (id) {
  6348. for (var index = 0; index < this.cameras.length; index++) {
  6349. if (this.cameras[index].id === id) {
  6350. return this.cameras[index];
  6351. }
  6352. }
  6353. return null;
  6354. };
  6355. Scene.prototype.getCameraByName = function (name) {
  6356. for (var index = 0; index < this.cameras.length; index++) {
  6357. if (this.cameras[index].name === name) {
  6358. return this.cameras[index];
  6359. }
  6360. }
  6361. return null;
  6362. };
  6363. Scene.prototype.getLightByName = function (name) {
  6364. for (var index = 0; index < this.lights.length; index++) {
  6365. if (this.lights[index].name === name) {
  6366. return this.lights[index];
  6367. }
  6368. }
  6369. return null;
  6370. };
  6371. Scene.prototype.getLightByID = function (id) {
  6372. for (var index = 0; index < this.lights.length; index++) {
  6373. if (this.lights[index].id === id) {
  6374. return this.lights[index];
  6375. }
  6376. }
  6377. return null;
  6378. };
  6379. Scene.prototype.getGeometryByID = function (id) {
  6380. for (var index = 0; index < this._geometries.length; index++) {
  6381. if (this._geometries[index].id === id) {
  6382. return this._geometries[index];
  6383. }
  6384. }
  6385. return null;
  6386. };
  6387. Scene.prototype.pushGeometry = function (geometry, force) {
  6388. if (!force && this.getGeometryByID(geometry.id)) {
  6389. return false;
  6390. }
  6391. this._geometries.push(geometry);
  6392. return true;
  6393. };
  6394. Scene.prototype.getGeometries = function () {
  6395. return this._geometries;
  6396. };
  6397. Scene.prototype.getMeshByID = function (id) {
  6398. for (var index = 0; index < this.meshes.length; index++) {
  6399. if (this.meshes[index].id === id) {
  6400. return this.meshes[index];
  6401. }
  6402. }
  6403. return null;
  6404. };
  6405. Scene.prototype.getLastMeshByID = function (id) {
  6406. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6407. if (this.meshes[index].id === id) {
  6408. return this.meshes[index];
  6409. }
  6410. }
  6411. return null;
  6412. };
  6413. Scene.prototype.getLastEntryByID = function (id) {
  6414. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6415. if (this.meshes[index].id === id) {
  6416. return this.meshes[index];
  6417. }
  6418. }
  6419. for (index = this.cameras.length - 1; index >= 0; index--) {
  6420. if (this.cameras[index].id === id) {
  6421. return this.cameras[index];
  6422. }
  6423. }
  6424. for (index = this.lights.length - 1; index >= 0; index--) {
  6425. if (this.lights[index].id === id) {
  6426. return this.lights[index];
  6427. }
  6428. }
  6429. return null;
  6430. };
  6431. Scene.prototype.getMeshByName = function (name) {
  6432. for (var index = 0; index < this.meshes.length; index++) {
  6433. if (this.meshes[index].name === name) {
  6434. return this.meshes[index];
  6435. }
  6436. }
  6437. return null;
  6438. };
  6439. Scene.prototype.getLastSkeletonByID = function (id) {
  6440. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  6441. if (this.skeletons[index].id === id) {
  6442. return this.skeletons[index];
  6443. }
  6444. }
  6445. return null;
  6446. };
  6447. Scene.prototype.getSkeletonById = function (id) {
  6448. for (var index = 0; index < this.skeletons.length; index++) {
  6449. if (this.skeletons[index].id === id) {
  6450. return this.skeletons[index];
  6451. }
  6452. }
  6453. return null;
  6454. };
  6455. Scene.prototype.getSkeletonByName = function (name) {
  6456. for (var index = 0; index < this.skeletons.length; index++) {
  6457. if (this.skeletons[index].name === name) {
  6458. return this.skeletons[index];
  6459. }
  6460. }
  6461. return null;
  6462. };
  6463. Scene.prototype.isActiveMesh = function (mesh) {
  6464. return (this._activeMeshes.indexOf(mesh) !== -1);
  6465. };
  6466. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  6467. if (mesh.subMeshes.length == 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  6468. var material = subMesh.getMaterial();
  6469. if (mesh.showSubMeshesBoundingBox) {
  6470. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  6471. }
  6472. if (material) {
  6473. if (material.getRenderTargetTextures) {
  6474. if (this._processedMaterials.indexOf(material) === -1) {
  6475. this._processedMaterials.push(material);
  6476. this._renderTargets.concat(material.getRenderTargetTextures());
  6477. }
  6478. }
  6479. this._activeVertices += subMesh.verticesCount;
  6480. this._renderingManager.dispatch(subMesh);
  6481. }
  6482. }
  6483. };
  6484. Scene.prototype._evaluateActiveMeshes = function () {
  6485. this._activeMeshes.reset();
  6486. this._renderingManager.reset();
  6487. this._processedMaterials.reset();
  6488. this._activeParticleSystems.reset();
  6489. this._activeSkeletons.reset();
  6490. this._boundingBoxRenderer.reset();
  6491. if (!this._frustumPlanes) {
  6492. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  6493. } else {
  6494. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  6495. }
  6496. var meshes;
  6497. var len;
  6498. if (this._selectionOctree) {
  6499. var selection = this._selectionOctree.select(this._frustumPlanes);
  6500. meshes = selection.data;
  6501. len = selection.length;
  6502. } else {
  6503. len = this.meshes.length;
  6504. meshes = this.meshes;
  6505. }
  6506. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  6507. var mesh = meshes[meshIndex];
  6508. this._totalVertices += mesh.getTotalVertices();
  6509. if (!mesh.isReady()) {
  6510. continue;
  6511. }
  6512. mesh.computeWorldMatrix();
  6513. mesh._preActivate();
  6514. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  6515. this._meshesForIntersections.pushNoDuplicate(mesh);
  6516. }
  6517. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) != 0) && mesh.isInFrustum(this._frustumPlanes)) {
  6518. this._activeMeshes.push(mesh);
  6519. mesh._activate(this._renderId);
  6520. this._activeMesh(mesh);
  6521. }
  6522. }
  6523. var beforeParticlesDate = new Date().getTime();
  6524. if (this.particlesEnabled) {
  6525. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  6526. var particleSystem = this.particleSystems[particleIndex];
  6527. if (!particleSystem.isStarted()) {
  6528. continue;
  6529. }
  6530. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  6531. this._activeParticleSystems.push(particleSystem);
  6532. particleSystem.animate();
  6533. }
  6534. }
  6535. }
  6536. this._particlesDuration += new Date().getTime() - beforeParticlesDate;
  6537. };
  6538. Scene.prototype._activeMesh = function (mesh) {
  6539. if (mesh.skeleton) {
  6540. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  6541. }
  6542. if (mesh.showBoundingBox) {
  6543. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  6544. }
  6545. if (mesh.subMeshes) {
  6546. var len;
  6547. var subMeshes;
  6548. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  6549. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  6550. len = intersections.length;
  6551. subMeshes = intersections.data;
  6552. } else {
  6553. subMeshes = mesh.subMeshes;
  6554. len = subMeshes.length;
  6555. }
  6556. for (var subIndex = 0; subIndex < len; subIndex++) {
  6557. var subMesh = subMeshes[subIndex];
  6558. this._evaluateSubMesh(subMesh, mesh);
  6559. }
  6560. }
  6561. };
  6562. Scene.prototype.updateTransformMatrix = function (force) {
  6563. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  6564. };
  6565. Scene.prototype._renderForCamera = function (camera) {
  6566. var engine = this._engine;
  6567. this.activeCamera = camera;
  6568. if (!this.activeCamera)
  6569. throw new Error("Active camera not set");
  6570. engine.setViewport(this.activeCamera.viewport);
  6571. this._renderId++;
  6572. this.updateTransformMatrix();
  6573. if (this.beforeCameraRender) {
  6574. this.beforeCameraRender(this.activeCamera);
  6575. }
  6576. var beforeEvaluateActiveMeshesDate = new Date().getTime();
  6577. this._evaluateActiveMeshes();
  6578. this._evaluateActiveMeshesDuration += new Date().getTime() - beforeEvaluateActiveMeshesDate;
  6579. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  6580. var skeleton = this._activeSkeletons.data[skeletonIndex];
  6581. skeleton.prepare();
  6582. }
  6583. var beforeRenderTargetDate = new Date().getTime();
  6584. if (this.renderTargetsEnabled) {
  6585. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  6586. var renderTarget = this._renderTargets.data[renderIndex];
  6587. if (renderTarget._shouldRender()) {
  6588. this._renderId++;
  6589. renderTarget.render();
  6590. }
  6591. }
  6592. this._renderId++;
  6593. }
  6594. if (this._renderTargets.length > 0) {
  6595. engine.restoreDefaultFramebuffer();
  6596. }
  6597. this._renderTargetsDuration += new Date().getTime() - beforeRenderTargetDate;
  6598. this.postProcessManager._prepareFrame();
  6599. var beforeRenderDate = new Date().getTime();
  6600. if (this.layers.length) {
  6601. engine.setDepthBuffer(false);
  6602. var layerIndex;
  6603. var layer;
  6604. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6605. layer = this.layers[layerIndex];
  6606. if (layer.isBackground) {
  6607. layer.render();
  6608. }
  6609. }
  6610. engine.setDepthBuffer(true);
  6611. }
  6612. this._renderingManager.render(null, null, true, true);
  6613. this._boundingBoxRenderer.render();
  6614. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  6615. this.lensFlareSystems[lensFlareSystemIndex].render();
  6616. }
  6617. if (this.layers.length) {
  6618. engine.setDepthBuffer(false);
  6619. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6620. layer = this.layers[layerIndex];
  6621. if (!layer.isBackground) {
  6622. layer.render();
  6623. }
  6624. }
  6625. engine.setDepthBuffer(true);
  6626. }
  6627. this._renderDuration += new Date().getTime() - beforeRenderDate;
  6628. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  6629. this.activeCamera._updateFromScene();
  6630. this._renderTargets.reset();
  6631. if (this.afterCameraRender) {
  6632. this.afterCameraRender(this.activeCamera);
  6633. }
  6634. };
  6635. Scene.prototype._processSubCameras = function (camera) {
  6636. if (camera.subCameras.length == 0) {
  6637. this._renderForCamera(camera);
  6638. return;
  6639. }
  6640. for (var index = 0; index < camera.subCameras.length; index++) {
  6641. this._renderForCamera(camera.subCameras[index]);
  6642. }
  6643. this.activeCamera = camera;
  6644. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  6645. this.activeCamera._updateFromScene();
  6646. };
  6647. Scene.prototype._checkIntersections = function () {
  6648. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  6649. var sourceMesh = this._meshesForIntersections.data[index];
  6650. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  6651. var action = sourceMesh.actionManager.actions[actionIndex];
  6652. if (action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6653. var otherMesh = action.getTriggerParameter();
  6654. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  6655. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6656. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  6657. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6658. sourceMesh._intersectionsInProgress.push(otherMesh);
  6659. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6660. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6661. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6662. if (indexOfOther > -1) {
  6663. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  6664. }
  6665. }
  6666. }
  6667. }
  6668. }
  6669. };
  6670. Scene.prototype.render = function () {
  6671. var startDate = new Date().getTime();
  6672. this._particlesDuration = 0;
  6673. this._spritesDuration = 0;
  6674. this._activeParticles = 0;
  6675. this._renderDuration = 0;
  6676. this._evaluateActiveMeshesDuration = 0;
  6677. this._totalVertices = 0;
  6678. this._activeVertices = 0;
  6679. this._meshesForIntersections.reset();
  6680. if (this.actionManager) {
  6681. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  6682. }
  6683. if (this.beforeRender) {
  6684. this.beforeRender();
  6685. }
  6686. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  6687. this._onBeforeRenderCallbacks[callbackIndex]();
  6688. }
  6689. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(BABYLON.Tools.GetDeltaTime(), Scene.MaxDeltaTime));
  6690. this._animationRatio = deltaTime * (60.0 / 1000.0);
  6691. this._animate();
  6692. if (this._physicsEngine) {
  6693. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  6694. }
  6695. var beforeRenderTargetDate = new Date().getTime();
  6696. var engine = this.getEngine();
  6697. if (this.renderTargetsEnabled) {
  6698. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  6699. var renderTarget = this.customRenderTargets[customIndex];
  6700. if (renderTarget._shouldRender()) {
  6701. this._renderId++;
  6702. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  6703. if (!this.activeCamera)
  6704. throw new Error("Active camera not set");
  6705. engine.setViewport(this.activeCamera.viewport);
  6706. this.updateTransformMatrix();
  6707. renderTarget.render();
  6708. }
  6709. }
  6710. this._renderId++;
  6711. }
  6712. if (this.customRenderTargets.length > 0) {
  6713. engine.restoreDefaultFramebuffer();
  6714. }
  6715. this._renderTargetsDuration += new Date().getTime() - beforeRenderTargetDate;
  6716. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe, true);
  6717. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  6718. var light = this.lights[lightIndex];
  6719. var shadowGenerator = light.getShadowGenerator();
  6720. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  6721. this._renderTargets.push(shadowGenerator.getShadowMap());
  6722. }
  6723. }
  6724. this.postProcessRenderPipelineManager.update();
  6725. if (this.activeCameras.length > 0) {
  6726. var currentRenderId = this._renderId;
  6727. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  6728. this._renderId = currentRenderId;
  6729. this._processSubCameras(this.activeCameras[cameraIndex]);
  6730. }
  6731. } else {
  6732. if (!this.activeCamera) {
  6733. throw new Error("No camera defined");
  6734. }
  6735. this._processSubCameras(this.activeCamera);
  6736. }
  6737. this._checkIntersections();
  6738. if (this.afterRender) {
  6739. this.afterRender();
  6740. }
  6741. for (var index = 0; index < this._toBeDisposed.length; index++) {
  6742. this._toBeDisposed.data[index].dispose();
  6743. this._toBeDisposed[index] = null;
  6744. }
  6745. this._toBeDisposed.reset();
  6746. this._lastFrameDuration = new Date().getTime() - startDate;
  6747. };
  6748. Scene.prototype.dispose = function () {
  6749. this.beforeRender = null;
  6750. this.afterRender = null;
  6751. this.skeletons = [];
  6752. this._boundingBoxRenderer.dispose();
  6753. if (this.onDispose) {
  6754. this.onDispose();
  6755. }
  6756. this.detachControl();
  6757. var canvas = this._engine.getRenderingCanvas();
  6758. var index;
  6759. for (index = 0; index < this.cameras.length; index++) {
  6760. this.cameras[index].detachControl(canvas);
  6761. }
  6762. while (this.lights.length) {
  6763. this.lights[0].dispose();
  6764. }
  6765. while (this.meshes.length) {
  6766. this.meshes[0].dispose(true);
  6767. }
  6768. while (this.cameras.length) {
  6769. this.cameras[0].dispose();
  6770. }
  6771. while (this.materials.length) {
  6772. this.materials[0].dispose();
  6773. }
  6774. while (this.particleSystems.length) {
  6775. this.particleSystems[0].dispose();
  6776. }
  6777. while (this.spriteManagers.length) {
  6778. this.spriteManagers[0].dispose();
  6779. }
  6780. while (this.layers.length) {
  6781. this.layers[0].dispose();
  6782. }
  6783. while (this.textures.length) {
  6784. this.textures[0].dispose();
  6785. }
  6786. this.postProcessManager.dispose();
  6787. if (this._physicsEngine) {
  6788. this.disablePhysicsEngine();
  6789. }
  6790. index = this._engine.scenes.indexOf(this);
  6791. if (index > -1) {
  6792. this._engine.scenes.splice(index, 1);
  6793. }
  6794. this._engine.wipeCaches();
  6795. };
  6796. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6797. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6798. position.divideToRef(collider.radius, this._scaledPosition);
  6799. velocity.divideToRef(collider.radius, this._scaledVelocity);
  6800. collider.retry = 0;
  6801. collider.initialVelocity = this._scaledVelocity;
  6802. collider.initialPosition = this._scaledPosition;
  6803. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  6804. finalPosition.multiplyInPlace(collider.radius);
  6805. };
  6806. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6807. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6808. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  6809. if (collider.retry >= maximumRetry) {
  6810. finalPosition.copyFrom(position);
  6811. return;
  6812. }
  6813. collider._initialize(position, velocity, closeDistance);
  6814. for (var index = 0; index < this.meshes.length; index++) {
  6815. var mesh = this.meshes[index];
  6816. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  6817. mesh._checkCollision(collider);
  6818. }
  6819. }
  6820. if (!collider.collisionFound) {
  6821. position.addToRef(velocity, finalPosition);
  6822. return;
  6823. }
  6824. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  6825. collider._getResponse(position, velocity);
  6826. }
  6827. if (velocity.length() <= closeDistance) {
  6828. finalPosition.copyFrom(position);
  6829. return;
  6830. }
  6831. collider.retry++;
  6832. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  6833. };
  6834. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  6835. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  6836. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  6837. if (!this._selectionOctree) {
  6838. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  6839. }
  6840. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6841. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6842. for (var index = 0; index < this.meshes.length; index++) {
  6843. var mesh = this.meshes[index];
  6844. mesh.computeWorldMatrix(true);
  6845. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  6846. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  6847. BABYLON.Tools.CheckExtends(minBox, min, max);
  6848. BABYLON.Tools.CheckExtends(maxBox, min, max);
  6849. }
  6850. this._selectionOctree.update(min, max, this.meshes);
  6851. return this._selectionOctree;
  6852. };
  6853. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  6854. var engine = this._engine;
  6855. if (!camera) {
  6856. if (!this.activeCamera)
  6857. throw new Error("Active camera not set");
  6858. camera = this.activeCamera;
  6859. }
  6860. var cameraViewport = camera.viewport;
  6861. var viewport = cameraViewport.toGlobal(engine);
  6862. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  6863. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  6864. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  6865. };
  6866. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  6867. var pickingInfo = null;
  6868. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  6869. var mesh = this.meshes[meshIndex];
  6870. if (predicate) {
  6871. if (!predicate(mesh)) {
  6872. continue;
  6873. }
  6874. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  6875. continue;
  6876. }
  6877. var world = mesh.getWorldMatrix();
  6878. var ray = rayFunction(world);
  6879. var result = mesh.intersects(ray, fastCheck);
  6880. if (!result || !result.hit)
  6881. continue;
  6882. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  6883. continue;
  6884. pickingInfo = result;
  6885. if (fastCheck) {
  6886. break;
  6887. }
  6888. }
  6889. return pickingInfo || new BABYLON.PickingInfo();
  6890. };
  6891. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  6892. var _this = this;
  6893. return this._internalPick(function (world) {
  6894. return _this.createPickingRay(x, y, world, camera);
  6895. }, predicate, fastCheck);
  6896. };
  6897. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  6898. var _this = this;
  6899. return this._internalPick(function (world) {
  6900. if (!_this._pickWithRayInverseMatrix) {
  6901. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  6902. }
  6903. world.invertToRef(_this._pickWithRayInverseMatrix);
  6904. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  6905. }, predicate, fastCheck);
  6906. };
  6907. Scene.prototype.setPointerOverMesh = function (mesh) {
  6908. if (this._pointerOverMesh === mesh) {
  6909. return;
  6910. }
  6911. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6912. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6913. }
  6914. this._pointerOverMesh = mesh;
  6915. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6916. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6917. }
  6918. };
  6919. Scene.prototype.getPointerOverMesh = function () {
  6920. return this._pointerOverMesh;
  6921. };
  6922. Scene.prototype.getPhysicsEngine = function () {
  6923. return this._physicsEngine;
  6924. };
  6925. Scene.prototype.enablePhysics = function (gravity, plugin) {
  6926. if (this._physicsEngine) {
  6927. return true;
  6928. }
  6929. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  6930. if (!this._physicsEngine.isSupported()) {
  6931. this._physicsEngine = null;
  6932. return false;
  6933. }
  6934. this._physicsEngine._initialize(gravity);
  6935. return true;
  6936. };
  6937. Scene.prototype.disablePhysicsEngine = function () {
  6938. if (!this._physicsEngine) {
  6939. return;
  6940. }
  6941. this._physicsEngine.dispose();
  6942. this._physicsEngine = undefined;
  6943. };
  6944. Scene.prototype.isPhysicsEnabled = function () {
  6945. return this._physicsEngine !== undefined;
  6946. };
  6947. Scene.prototype.setGravity = function (gravity) {
  6948. if (!this._physicsEngine) {
  6949. return;
  6950. }
  6951. this._physicsEngine._setGravity(gravity);
  6952. };
  6953. Scene.prototype.createCompoundImpostor = function (parts, options) {
  6954. if (parts.parts) {
  6955. options = parts;
  6956. parts = parts.parts;
  6957. }
  6958. if (!this._physicsEngine) {
  6959. return null;
  6960. }
  6961. for (var index = 0; index < parts.length; index++) {
  6962. var mesh = parts[index].mesh;
  6963. mesh._physicImpostor = parts[index].impostor;
  6964. mesh._physicsMass = options.mass / parts.length;
  6965. mesh._physicsFriction = options.friction;
  6966. mesh._physicRestitution = options.restitution;
  6967. }
  6968. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  6969. };
  6970. Scene.prototype.deleteCompoundImpostor = function (compound) {
  6971. for (var index = 0; index < compound.parts.length; index++) {
  6972. var mesh = compound.parts[index].mesh;
  6973. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  6974. this._physicsEngine._unregisterMesh(mesh);
  6975. }
  6976. };
  6977. Scene.prototype._getByTags = function (list, tagsQuery) {
  6978. if (tagsQuery === undefined) {
  6979. return list;
  6980. }
  6981. var listByTags = [];
  6982. for (var i in list) {
  6983. var item = list[i];
  6984. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  6985. listByTags.push(item);
  6986. }
  6987. }
  6988. return listByTags;
  6989. };
  6990. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  6991. return this._getByTags(this.meshes, tagsQuery);
  6992. };
  6993. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  6994. return this._getByTags(this.cameras, tagsQuery);
  6995. };
  6996. Scene.prototype.getLightsByTags = function (tagsQuery) {
  6997. return this._getByTags(this.lights, tagsQuery);
  6998. };
  6999. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  7000. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  7001. };
  7002. Scene.FOGMODE_NONE = 0;
  7003. Scene.FOGMODE_EXP = 1;
  7004. Scene.FOGMODE_EXP2 = 2;
  7005. Scene.FOGMODE_LINEAR = 3;
  7006. Scene.MinDeltaTime = 1.0;
  7007. Scene.MaxDeltaTime = 1000.0;
  7008. return Scene;
  7009. })();
  7010. BABYLON.Scene = Scene;
  7011. })(BABYLON || (BABYLON = {}));
  7012. var BABYLON;
  7013. (function (BABYLON) {
  7014. var VertexBuffer = (function () {
  7015. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation) {
  7016. if (engine instanceof BABYLON.Mesh) {
  7017. this._engine = engine.getScene().getEngine();
  7018. } else {
  7019. this._engine = engine;
  7020. }
  7021. this._updatable = updatable;
  7022. this._data = data;
  7023. if (!postponeInternalCreation) {
  7024. this.create();
  7025. }
  7026. this._kind = kind;
  7027. switch (kind) {
  7028. case VertexBuffer.PositionKind:
  7029. this._strideSize = 3;
  7030. break;
  7031. case VertexBuffer.NormalKind:
  7032. this._strideSize = 3;
  7033. break;
  7034. case VertexBuffer.UVKind:
  7035. this._strideSize = 2;
  7036. break;
  7037. case VertexBuffer.UV2Kind:
  7038. this._strideSize = 2;
  7039. break;
  7040. case VertexBuffer.ColorKind:
  7041. this._strideSize = 3;
  7042. break;
  7043. case VertexBuffer.MatricesIndicesKind:
  7044. this._strideSize = 4;
  7045. break;
  7046. case VertexBuffer.MatricesWeightsKind:
  7047. this._strideSize = 4;
  7048. break;
  7049. }
  7050. }
  7051. VertexBuffer.prototype.isUpdatable = function () {
  7052. return this._updatable;
  7053. };
  7054. VertexBuffer.prototype.getData = function () {
  7055. return this._data;
  7056. };
  7057. VertexBuffer.prototype.getBuffer = function () {
  7058. return this._buffer;
  7059. };
  7060. VertexBuffer.prototype.getStrideSize = function () {
  7061. return this._strideSize;
  7062. };
  7063. VertexBuffer.prototype.create = function (data) {
  7064. if (!data && this._buffer) {
  7065. return;
  7066. }
  7067. data = data || this._data;
  7068. if (!this._buffer) {
  7069. if (this._updatable) {
  7070. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  7071. } else {
  7072. this._buffer = this._engine.createVertexBuffer(data);
  7073. }
  7074. }
  7075. if (this._updatable) {
  7076. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7077. this._data = data;
  7078. }
  7079. };
  7080. VertexBuffer.prototype.update = function (data) {
  7081. this.create(data);
  7082. };
  7083. VertexBuffer.prototype.dispose = function () {
  7084. if (!this._buffer) {
  7085. return;
  7086. }
  7087. if (this._engine._releaseBuffer(this._buffer)) {
  7088. this._buffer = null;
  7089. }
  7090. };
  7091. Object.defineProperty(VertexBuffer, "PositionKind", {
  7092. get: function () {
  7093. return VertexBuffer._PositionKind;
  7094. },
  7095. enumerable: true,
  7096. configurable: true
  7097. });
  7098. Object.defineProperty(VertexBuffer, "NormalKind", {
  7099. get: function () {
  7100. return VertexBuffer._NormalKind;
  7101. },
  7102. enumerable: true,
  7103. configurable: true
  7104. });
  7105. Object.defineProperty(VertexBuffer, "UVKind", {
  7106. get: function () {
  7107. return VertexBuffer._UVKind;
  7108. },
  7109. enumerable: true,
  7110. configurable: true
  7111. });
  7112. Object.defineProperty(VertexBuffer, "UV2Kind", {
  7113. get: function () {
  7114. return VertexBuffer._UV2Kind;
  7115. },
  7116. enumerable: true,
  7117. configurable: true
  7118. });
  7119. Object.defineProperty(VertexBuffer, "ColorKind", {
  7120. get: function () {
  7121. return VertexBuffer._ColorKind;
  7122. },
  7123. enumerable: true,
  7124. configurable: true
  7125. });
  7126. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  7127. get: function () {
  7128. return VertexBuffer._MatricesIndicesKind;
  7129. },
  7130. enumerable: true,
  7131. configurable: true
  7132. });
  7133. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  7134. get: function () {
  7135. return VertexBuffer._MatricesWeightsKind;
  7136. },
  7137. enumerable: true,
  7138. configurable: true
  7139. });
  7140. VertexBuffer._PositionKind = "position";
  7141. VertexBuffer._NormalKind = "normal";
  7142. VertexBuffer._UVKind = "uv";
  7143. VertexBuffer._UV2Kind = "uv2";
  7144. VertexBuffer._ColorKind = "color";
  7145. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  7146. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  7147. return VertexBuffer;
  7148. })();
  7149. BABYLON.VertexBuffer = VertexBuffer;
  7150. })(BABYLON || (BABYLON = {}));
  7151. var __extends = this.__extends || function (d, b) {
  7152. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7153. function __() { this.constructor = d; }
  7154. __.prototype = b.prototype;
  7155. d.prototype = new __();
  7156. };
  7157. var BABYLON;
  7158. (function (BABYLON) {
  7159. var AbstractMesh = (function (_super) {
  7160. __extends(AbstractMesh, _super);
  7161. function AbstractMesh(name, scene) {
  7162. _super.call(this, name, scene);
  7163. this.position = new BABYLON.Vector3(0, 0, 0);
  7164. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7165. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7166. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  7167. this.visibility = 1.0;
  7168. this.infiniteDistance = false;
  7169. this.isVisible = true;
  7170. this.isPickable = true;
  7171. this.showBoundingBox = false;
  7172. this.showSubMeshesBoundingBox = false;
  7173. this.onDispose = null;
  7174. this.checkCollisions = false;
  7175. this.isBlocker = false;
  7176. this.renderingGroupId = 0;
  7177. this.receiveShadows = false;
  7178. this.renderOutline = false;
  7179. this.outlineColor = BABYLON.Color3.Red();
  7180. this.outlineWidth = 0.02;
  7181. this.useOctreeForRenderingSelection = true;
  7182. this.useOctreeForPicking = true;
  7183. this.useOctreeForCollisions = true;
  7184. this.layerMask = 0xFFFFFFFF;
  7185. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7186. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7187. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7188. this._collider = new BABYLON.Collider();
  7189. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7190. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7191. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7192. this._localScaling = BABYLON.Matrix.Zero();
  7193. this._localRotation = BABYLON.Matrix.Zero();
  7194. this._localTranslation = BABYLON.Matrix.Zero();
  7195. this._localBillboard = BABYLON.Matrix.Zero();
  7196. this._localPivotScaling = BABYLON.Matrix.Zero();
  7197. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7198. this._localWorld = BABYLON.Matrix.Zero();
  7199. this._worldMatrix = BABYLON.Matrix.Zero();
  7200. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7201. this._absolutePosition = BABYLON.Vector3.Zero();
  7202. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7203. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7204. this._isDirty = false;
  7205. this._pivotMatrix = BABYLON.Matrix.Identity();
  7206. this._isDisposed = false;
  7207. this._renderId = 0;
  7208. this._intersectionsInProgress = new Array();
  7209. scene.meshes.push(this);
  7210. }
  7211. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7212. get: function () {
  7213. return AbstractMesh._BILLBOARDMODE_NONE;
  7214. },
  7215. enumerable: true,
  7216. configurable: true
  7217. });
  7218. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7219. get: function () {
  7220. return AbstractMesh._BILLBOARDMODE_X;
  7221. },
  7222. enumerable: true,
  7223. configurable: true
  7224. });
  7225. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7226. get: function () {
  7227. return AbstractMesh._BILLBOARDMODE_Y;
  7228. },
  7229. enumerable: true,
  7230. configurable: true
  7231. });
  7232. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7233. get: function () {
  7234. return AbstractMesh._BILLBOARDMODE_Z;
  7235. },
  7236. enumerable: true,
  7237. configurable: true
  7238. });
  7239. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7240. get: function () {
  7241. return AbstractMesh._BILLBOARDMODE_ALL;
  7242. },
  7243. enumerable: true,
  7244. configurable: true
  7245. });
  7246. AbstractMesh.prototype.getTotalVertices = function () {
  7247. return 0;
  7248. };
  7249. AbstractMesh.prototype.getIndices = function () {
  7250. return null;
  7251. };
  7252. AbstractMesh.prototype.getVerticesData = function (kind) {
  7253. return null;
  7254. };
  7255. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7256. return false;
  7257. };
  7258. AbstractMesh.prototype.getBoundingInfo = function () {
  7259. if (!this._boundingInfo) {
  7260. this._updateBoundingInfo();
  7261. }
  7262. return this._boundingInfo;
  7263. };
  7264. AbstractMesh.prototype._preActivate = function () {
  7265. };
  7266. AbstractMesh.prototype._activate = function (renderId) {
  7267. this._renderId = renderId;
  7268. };
  7269. AbstractMesh.prototype.getWorldMatrix = function () {
  7270. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7271. this.computeWorldMatrix();
  7272. }
  7273. return this._worldMatrix;
  7274. };
  7275. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7276. get: function () {
  7277. return this._worldMatrix;
  7278. },
  7279. enumerable: true,
  7280. configurable: true
  7281. });
  7282. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7283. get: function () {
  7284. return this._absolutePosition;
  7285. },
  7286. enumerable: true,
  7287. configurable: true
  7288. });
  7289. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7290. if (!this.rotationQuaternion) {
  7291. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7292. this.rotation = BABYLON.Vector3.Zero();
  7293. }
  7294. if (!space || space == 0 /* LOCAL */) {
  7295. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7296. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7297. } else {
  7298. if (this.parent) {
  7299. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7300. invertParentWorldMatrix.invert();
  7301. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7302. }
  7303. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7304. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7305. }
  7306. };
  7307. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7308. var displacementVector = axis.scale(distance);
  7309. if (!space || space == 0 /* LOCAL */) {
  7310. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7311. this.setPositionWithLocalVector(tempV3);
  7312. } else {
  7313. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7314. }
  7315. };
  7316. AbstractMesh.prototype.getAbsolutePosition = function () {
  7317. this.computeWorldMatrix();
  7318. return this._absolutePosition;
  7319. };
  7320. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7321. if (!absolutePosition) {
  7322. return;
  7323. }
  7324. var absolutePositionX;
  7325. var absolutePositionY;
  7326. var absolutePositionZ;
  7327. if (absolutePosition.x === undefined) {
  7328. if (arguments.length < 3) {
  7329. return;
  7330. }
  7331. absolutePositionX = arguments[0];
  7332. absolutePositionY = arguments[1];
  7333. absolutePositionZ = arguments[2];
  7334. } else {
  7335. absolutePositionX = absolutePosition.x;
  7336. absolutePositionY = absolutePosition.y;
  7337. absolutePositionZ = absolutePosition.z;
  7338. }
  7339. if (this.parent) {
  7340. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7341. invertParentWorldMatrix.invert();
  7342. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7343. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7344. } else {
  7345. this.position.x = absolutePositionX;
  7346. this.position.y = absolutePositionY;
  7347. this.position.z = absolutePositionZ;
  7348. }
  7349. };
  7350. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7351. this._pivotMatrix = matrix;
  7352. this._cache.pivotMatrixUpdated = true;
  7353. };
  7354. AbstractMesh.prototype.getPivotMatrix = function () {
  7355. return this._pivotMatrix;
  7356. };
  7357. AbstractMesh.prototype._isSynchronized = function () {
  7358. if (this._isDirty) {
  7359. return false;
  7360. }
  7361. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7362. return false;
  7363. if (this._cache.pivotMatrixUpdated) {
  7364. return false;
  7365. }
  7366. if (this.infiniteDistance) {
  7367. return false;
  7368. }
  7369. if (!this._cache.position.equals(this.position))
  7370. return false;
  7371. if (this.rotationQuaternion) {
  7372. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7373. return false;
  7374. } else {
  7375. if (!this._cache.rotation.equals(this.rotation))
  7376. return false;
  7377. }
  7378. if (!this._cache.scaling.equals(this.scaling))
  7379. return false;
  7380. return true;
  7381. };
  7382. AbstractMesh.prototype._initCache = function () {
  7383. _super.prototype._initCache.call(this);
  7384. this._cache.localMatrixUpdated = false;
  7385. this._cache.position = BABYLON.Vector3.Zero();
  7386. this._cache.scaling = BABYLON.Vector3.Zero();
  7387. this._cache.rotation = BABYLON.Vector3.Zero();
  7388. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7389. };
  7390. AbstractMesh.prototype.markAsDirty = function (property) {
  7391. if (property === "rotation") {
  7392. this.rotationQuaternion = null;
  7393. }
  7394. this._currentRenderId = Number.MAX_VALUE;
  7395. this._isDirty = true;
  7396. };
  7397. AbstractMesh.prototype._updateBoundingInfo = function () {
  7398. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7399. this._boundingInfo._update(this.worldMatrixFromCache);
  7400. if (!this.subMeshes) {
  7401. return;
  7402. }
  7403. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7404. var subMesh = this.subMeshes[subIndex];
  7405. subMesh.updateBoundingInfo(this.worldMatrixFromCache);
  7406. }
  7407. };
  7408. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7409. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  7410. return this._worldMatrix;
  7411. }
  7412. this._cache.position.copyFrom(this.position);
  7413. this._cache.scaling.copyFrom(this.scaling);
  7414. this._cache.pivotMatrixUpdated = false;
  7415. this._currentRenderId = this.getScene().getRenderId();
  7416. this._isDirty = false;
  7417. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7418. if (this.rotationQuaternion) {
  7419. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7420. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7421. } else {
  7422. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7423. this._cache.rotation.copyFrom(this.rotation);
  7424. }
  7425. if (this.infiniteDistance && !this.parent) {
  7426. var camera = this.getScene().activeCamera;
  7427. var cameraWorldMatrix = camera.getWorldMatrix();
  7428. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7429. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7430. } else {
  7431. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7432. }
  7433. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7434. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7435. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  7436. var localPosition = this.position.clone();
  7437. var zero = this.getScene().activeCamera.position.clone();
  7438. if (this.parent && this.parent.position) {
  7439. localPosition.addInPlace(this.parent.position);
  7440. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7441. }
  7442. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  7443. zero = this.getScene().activeCamera.position;
  7444. } else {
  7445. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  7446. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7447. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  7448. zero.y = localPosition.y + 0.001;
  7449. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  7450. zero.z = localPosition.z + 0.001;
  7451. }
  7452. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7453. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7454. this._localBillboard.invert();
  7455. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7456. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7457. }
  7458. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7459. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  7460. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7461. } else {
  7462. this._worldMatrix.copyFrom(this._localWorld);
  7463. }
  7464. this._updateBoundingInfo();
  7465. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7466. return this._worldMatrix;
  7467. };
  7468. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7469. this.computeWorldMatrix();
  7470. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7471. };
  7472. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7473. this.computeWorldMatrix();
  7474. var invLocalWorldMatrix = this._localWorld.clone();
  7475. invLocalWorldMatrix.invert();
  7476. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7477. };
  7478. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7479. this.computeWorldMatrix();
  7480. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7481. };
  7482. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7483. yawCor = yawCor || 0;
  7484. pitchCor = pitchCor || 0;
  7485. rollCor = rollCor || 0;
  7486. var dv = targetPoint.subtract(this.position);
  7487. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7488. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7489. var pitch = Math.atan2(dv.y, len);
  7490. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7491. };
  7492. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7493. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  7494. return false;
  7495. }
  7496. return true;
  7497. };
  7498. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7499. if (!this._boundingInfo || !mesh._boundingInfo) {
  7500. return false;
  7501. }
  7502. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  7503. };
  7504. AbstractMesh.prototype.intersectsPoint = function (point) {
  7505. if (!this._boundingInfo) {
  7506. return false;
  7507. }
  7508. return this._boundingInfo.intersectsPoint(point);
  7509. };
  7510. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  7511. var physicsEngine = this.getScene().getPhysicsEngine();
  7512. if (!physicsEngine) {
  7513. return;
  7514. }
  7515. if (impostor.impostor) {
  7516. options = impostor;
  7517. impostor = impostor.impostor;
  7518. }
  7519. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  7520. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  7521. physicsEngine._unregisterMesh(this);
  7522. return;
  7523. }
  7524. options.mass = options.mass || 0;
  7525. options.friction = options.friction || 0.2;
  7526. options.restitution = options.restitution || 0.9;
  7527. this._physicImpostor = impostor;
  7528. this._physicsMass = options.mass;
  7529. this._physicsFriction = options.friction;
  7530. this._physicRestitution = options.restitution;
  7531. physicsEngine._registerMesh(this, impostor, options);
  7532. };
  7533. AbstractMesh.prototype.getPhysicsImpostor = function () {
  7534. if (!this._physicImpostor) {
  7535. return BABYLON.PhysicsEngine.NoImpostor;
  7536. }
  7537. return this._physicImpostor;
  7538. };
  7539. AbstractMesh.prototype.getPhysicsMass = function () {
  7540. if (!this._physicsMass) {
  7541. return 0;
  7542. }
  7543. return this._physicsMass;
  7544. };
  7545. AbstractMesh.prototype.getPhysicsFriction = function () {
  7546. if (!this._physicsFriction) {
  7547. return 0;
  7548. }
  7549. return this._physicsFriction;
  7550. };
  7551. AbstractMesh.prototype.getPhysicsRestitution = function () {
  7552. if (!this._physicRestitution) {
  7553. return 0;
  7554. }
  7555. return this._physicRestitution;
  7556. };
  7557. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  7558. if (!this._physicImpostor) {
  7559. return;
  7560. }
  7561. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  7562. };
  7563. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  7564. if (!this._physicImpostor) {
  7565. return;
  7566. }
  7567. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  7568. };
  7569. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  7570. if (!this._physicImpostor) {
  7571. return;
  7572. }
  7573. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  7574. };
  7575. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  7576. var globalPosition = this.getAbsolutePosition();
  7577. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  7578. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  7579. this._collider.radius = this.ellipsoid;
  7580. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  7581. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  7582. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7583. this.position.addInPlace(this._diffPositionForCollisions);
  7584. }
  7585. };
  7586. /**
  7587. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  7588. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  7589. */
  7590. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  7591. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7592. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7593. if (!this._submeshesOctree) {
  7594. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  7595. }
  7596. this.computeWorldMatrix(true);
  7597. var bbox = this.getBoundingInfo().boundingBox;
  7598. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  7599. return this._submeshesOctree;
  7600. };
  7601. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  7602. this._generatePointsArray();
  7603. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  7604. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  7605. subMesh._lastColliderWorldVertices = [];
  7606. subMesh._trianglePlanes = [];
  7607. var start = subMesh.verticesStart;
  7608. var end = (subMesh.verticesStart + subMesh.verticesCount);
  7609. for (var i = start; i < end; i++) {
  7610. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  7611. }
  7612. }
  7613. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  7614. };
  7615. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  7616. var subMeshes;
  7617. var len;
  7618. if (this._submeshesOctree && this.useOctreeForCollisions) {
  7619. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  7620. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  7621. len = intersections.length;
  7622. subMeshes = intersections.data;
  7623. } else {
  7624. subMeshes = this.subMeshes;
  7625. len = subMeshes.length;
  7626. }
  7627. for (var index = 0; index < len; index++) {
  7628. var subMesh = subMeshes[index];
  7629. if (len > 1 && !subMesh._checkCollision(collider))
  7630. continue;
  7631. this._collideForSubMesh(subMesh, transformMatrix, collider);
  7632. }
  7633. };
  7634. AbstractMesh.prototype._checkCollision = function (collider) {
  7635. if (!this._boundingInfo._checkCollision(collider))
  7636. return;
  7637. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  7638. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  7639. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  7640. };
  7641. AbstractMesh.prototype._generatePointsArray = function () {
  7642. return false;
  7643. };
  7644. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  7645. var pickingInfo = new BABYLON.PickingInfo();
  7646. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  7647. return pickingInfo;
  7648. }
  7649. if (!this._generatePointsArray()) {
  7650. return pickingInfo;
  7651. }
  7652. var intersectInfo = null;
  7653. var subMeshes;
  7654. var len;
  7655. if (this._submeshesOctree && this.useOctreeForPicking) {
  7656. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  7657. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  7658. len = intersections.length;
  7659. subMeshes = intersections.data;
  7660. } else {
  7661. subMeshes = this.subMeshes;
  7662. len = subMeshes.length;
  7663. }
  7664. for (var index = 0; index < len; index++) {
  7665. var subMesh = subMeshes[index];
  7666. if (len > 1 && !subMesh.canIntersects(ray))
  7667. continue;
  7668. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  7669. if (currentIntersectInfo) {
  7670. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  7671. intersectInfo = currentIntersectInfo;
  7672. if (fastCheck) {
  7673. break;
  7674. }
  7675. }
  7676. }
  7677. }
  7678. if (intersectInfo) {
  7679. var world = this.getWorldMatrix();
  7680. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  7681. var direction = ray.direction.clone();
  7682. direction.normalize();
  7683. direction = direction.scale(intersectInfo.distance);
  7684. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  7685. var pickedPoint = worldOrigin.add(worldDirection);
  7686. pickingInfo.hit = true;
  7687. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  7688. pickingInfo.pickedPoint = pickedPoint;
  7689. pickingInfo.pickedMesh = this;
  7690. pickingInfo.bu = intersectInfo.bu;
  7691. pickingInfo.bv = intersectInfo.bv;
  7692. pickingInfo.faceId = intersectInfo.faceId;
  7693. return pickingInfo;
  7694. }
  7695. return pickingInfo;
  7696. };
  7697. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  7698. return null;
  7699. };
  7700. AbstractMesh.prototype.releaseSubMeshes = function () {
  7701. if (this.subMeshes) {
  7702. while (this.subMeshes.length) {
  7703. this.subMeshes[0].dispose();
  7704. }
  7705. } else {
  7706. this.subMeshes = new Array();
  7707. }
  7708. };
  7709. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  7710. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  7711. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  7712. }
  7713. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  7714. var other = this._intersectionsInProgress[index];
  7715. var pos = other._intersectionsInProgress.indexOf(this);
  7716. other._intersectionsInProgress.splice(pos, 1);
  7717. }
  7718. this._intersectionsInProgress = [];
  7719. this.releaseSubMeshes();
  7720. var index = this.getScene().meshes.indexOf(this);
  7721. if (index != -1) {
  7722. this.getScene().meshes.splice(index, 1);
  7723. }
  7724. if (!doNotRecurse) {
  7725. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  7726. if (this.getScene().particleSystems[index].emitter == this) {
  7727. this.getScene().particleSystems[index].dispose();
  7728. index--;
  7729. }
  7730. }
  7731. var objects = this.getScene().meshes.slice(0);
  7732. for (index = 0; index < objects.length; index++) {
  7733. if (objects[index].parent == this) {
  7734. objects[index].dispose();
  7735. }
  7736. }
  7737. } else {
  7738. for (index = 0; index < this.getScene().meshes.length; index++) {
  7739. var obj = this.getScene().meshes[index];
  7740. if (obj.parent === this) {
  7741. obj.parent = null;
  7742. obj.computeWorldMatrix(true);
  7743. }
  7744. }
  7745. }
  7746. this._isDisposed = true;
  7747. if (this.onDispose) {
  7748. this.onDispose();
  7749. }
  7750. };
  7751. AbstractMesh._BILLBOARDMODE_NONE = 0;
  7752. AbstractMesh._BILLBOARDMODE_X = 1;
  7753. AbstractMesh._BILLBOARDMODE_Y = 2;
  7754. AbstractMesh._BILLBOARDMODE_Z = 4;
  7755. AbstractMesh._BILLBOARDMODE_ALL = 7;
  7756. return AbstractMesh;
  7757. })(BABYLON.Node);
  7758. BABYLON.AbstractMesh = AbstractMesh;
  7759. })(BABYLON || (BABYLON = {}));
  7760. var __extends = this.__extends || function (d, b) {
  7761. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7762. function __() { this.constructor = d; }
  7763. __.prototype = b.prototype;
  7764. d.prototype = new __();
  7765. };
  7766. var BABYLON;
  7767. (function (BABYLON) {
  7768. var _InstancesBatch = (function () {
  7769. function _InstancesBatch() {
  7770. this.mustReturn = false;
  7771. this.visibleInstances = new Array();
  7772. this.renderSelf = new Array();
  7773. }
  7774. return _InstancesBatch;
  7775. })();
  7776. BABYLON._InstancesBatch = _InstancesBatch;
  7777. var Mesh = (function (_super) {
  7778. __extends(Mesh, _super);
  7779. function Mesh(name, scene) {
  7780. _super.call(this, name, scene);
  7781. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  7782. this.instances = new Array();
  7783. this._onBeforeRenderCallbacks = new Array();
  7784. this._onAfterRenderCallbacks = new Array();
  7785. this._visibleInstances = {};
  7786. this._renderIdForInstances = new Array();
  7787. this._batchCache = new _InstancesBatch();
  7788. this._instancesBufferSize = 32 * 16 * 4;
  7789. }
  7790. Mesh.prototype.getTotalVertices = function () {
  7791. if (!this._geometry) {
  7792. return 0;
  7793. }
  7794. return this._geometry.getTotalVertices();
  7795. };
  7796. Mesh.prototype.getVerticesData = function (kind) {
  7797. if (!this._geometry) {
  7798. return null;
  7799. }
  7800. return this._geometry.getVerticesData(kind);
  7801. };
  7802. Mesh.prototype.getVertexBuffer = function (kind) {
  7803. if (!this._geometry) {
  7804. return undefined;
  7805. }
  7806. return this._geometry.getVertexBuffer(kind);
  7807. };
  7808. Mesh.prototype.isVerticesDataPresent = function (kind) {
  7809. if (!this._geometry) {
  7810. if (this._delayInfo) {
  7811. return this._delayInfo.indexOf(kind) !== -1;
  7812. }
  7813. return false;
  7814. }
  7815. return this._geometry.isVerticesDataPresent(kind);
  7816. };
  7817. Mesh.prototype.getVerticesDataKinds = function () {
  7818. if (!this._geometry) {
  7819. var result = [];
  7820. if (this._delayInfo) {
  7821. for (var kind in this._delayInfo) {
  7822. result.push(kind);
  7823. }
  7824. }
  7825. return result;
  7826. }
  7827. return this._geometry.getVerticesDataKinds();
  7828. };
  7829. Mesh.prototype.getTotalIndices = function () {
  7830. if (!this._geometry) {
  7831. return 0;
  7832. }
  7833. return this._geometry.getTotalIndices();
  7834. };
  7835. Mesh.prototype.getIndices = function () {
  7836. if (!this._geometry) {
  7837. return [];
  7838. }
  7839. return this._geometry.getIndices();
  7840. };
  7841. Mesh.prototype.isReady = function () {
  7842. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7843. return false;
  7844. }
  7845. return _super.prototype.isReady.call(this);
  7846. };
  7847. Mesh.prototype.isDisposed = function () {
  7848. return this._isDisposed;
  7849. };
  7850. Mesh.prototype._preActivate = function () {
  7851. var sceneRenderId = this.getScene().getRenderId();
  7852. if (this._preActivateId == sceneRenderId) {
  7853. return;
  7854. }
  7855. this._preActivateId = sceneRenderId;
  7856. this._visibleInstances = null;
  7857. };
  7858. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  7859. if (!this._visibleInstances) {
  7860. this._visibleInstances = {};
  7861. this._visibleInstances.defaultRenderId = renderId;
  7862. this._visibleInstances.selfDefaultRenderId = this._renderId;
  7863. }
  7864. if (!this._visibleInstances[renderId]) {
  7865. this._visibleInstances[renderId] = new Array();
  7866. }
  7867. this._visibleInstances[renderId].push(instance);
  7868. };
  7869. Mesh.prototype.refreshBoundingInfo = function () {
  7870. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7871. if (data) {
  7872. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  7873. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  7874. }
  7875. if (this.subMeshes) {
  7876. for (var index = 0; index < this.subMeshes.length; index++) {
  7877. this.subMeshes[index].refreshBoundingInfo();
  7878. }
  7879. }
  7880. this._updateBoundingInfo();
  7881. };
  7882. Mesh.prototype._createGlobalSubMesh = function () {
  7883. var totalVertices = this.getTotalVertices();
  7884. if (!totalVertices || !this.getIndices()) {
  7885. return null;
  7886. }
  7887. this.releaseSubMeshes();
  7888. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  7889. };
  7890. Mesh.prototype.subdivide = function (count) {
  7891. if (count < 1) {
  7892. return;
  7893. }
  7894. var totalIndices = this.getTotalIndices();
  7895. var subdivisionSize = (totalIndices / count) | 0;
  7896. var offset = 0;
  7897. while (subdivisionSize % 3 != 0) {
  7898. subdivisionSize++;
  7899. }
  7900. this.releaseSubMeshes();
  7901. for (var index = 0; index < count; index++) {
  7902. if (offset >= totalIndices) {
  7903. break;
  7904. }
  7905. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  7906. offset += subdivisionSize;
  7907. }
  7908. this.synchronizeInstances();
  7909. };
  7910. Mesh.prototype.setVerticesData = function (kind, data, updatable) {
  7911. if (kind instanceof Array) {
  7912. var temp = data;
  7913. data = kind;
  7914. kind = temp;
  7915. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  7916. }
  7917. if (!this._geometry) {
  7918. var vertexData = new BABYLON.VertexData();
  7919. vertexData.set(data, kind);
  7920. var scene = this.getScene();
  7921. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  7922. } else {
  7923. this._geometry.setVerticesData(kind, data, updatable);
  7924. }
  7925. };
  7926. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  7927. if (!this._geometry) {
  7928. return;
  7929. }
  7930. if (!makeItUnique) {
  7931. this._geometry.updateVerticesData(kind, data, updateExtends);
  7932. } else {
  7933. this.makeGeometryUnique();
  7934. this.updateVerticesData(kind, data, updateExtends, false);
  7935. }
  7936. };
  7937. Mesh.prototype.makeGeometryUnique = function () {
  7938. if (!this._geometry) {
  7939. return;
  7940. }
  7941. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  7942. geometry.applyToMesh(this);
  7943. };
  7944. Mesh.prototype.setIndices = function (indices) {
  7945. if (!this._geometry) {
  7946. var vertexData = new BABYLON.VertexData();
  7947. vertexData.indices = indices;
  7948. var scene = this.getScene();
  7949. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  7950. } else {
  7951. this._geometry.setIndices(indices);
  7952. }
  7953. };
  7954. Mesh.prototype._bind = function (subMesh, effect, wireframe) {
  7955. var engine = this.getScene().getEngine();
  7956. var indexToBind = this._geometry.getIndexBuffer();
  7957. if (wireframe) {
  7958. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  7959. }
  7960. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  7961. };
  7962. Mesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  7963. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  7964. return;
  7965. }
  7966. var engine = this.getScene().getEngine();
  7967. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  7968. };
  7969. Mesh.prototype._fullDraw = function (subMesh, useTriangles, instancesCount) {
  7970. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  7971. return;
  7972. }
  7973. var engine = this.getScene().getEngine();
  7974. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  7975. };
  7976. Mesh.prototype.registerBeforeRender = function (func) {
  7977. this._onBeforeRenderCallbacks.push(func);
  7978. };
  7979. Mesh.prototype.unregisterBeforeRender = function (func) {
  7980. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7981. if (index > -1) {
  7982. this._onBeforeRenderCallbacks.splice(index, 1);
  7983. }
  7984. };
  7985. Mesh.prototype.registerAfterRender = function (func) {
  7986. this._onAfterRenderCallbacks.push(func);
  7987. };
  7988. Mesh.prototype.unregisterAfterRender = function (func) {
  7989. var index = this._onAfterRenderCallbacks.indexOf(func);
  7990. if (index > -1) {
  7991. this._onAfterRenderCallbacks.splice(index, 1);
  7992. }
  7993. };
  7994. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  7995. var scene = this.getScene();
  7996. this._batchCache.mustReturn = false;
  7997. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  7998. this._batchCache.visibleInstances[subMeshId] = null;
  7999. if (this._visibleInstances) {
  8000. var currentRenderId = scene.getRenderId();
  8001. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  8002. var selfRenderId = this._renderId;
  8003. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  8004. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  8005. currentRenderId = this._visibleInstances.defaultRenderId;
  8006. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  8007. }
  8008. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  8009. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  8010. this._batchCache.mustReturn = true;
  8011. return this._batchCache;
  8012. }
  8013. if (currentRenderId !== selfRenderId) {
  8014. this._batchCache.renderSelf[subMeshId] = false;
  8015. }
  8016. }
  8017. this._renderIdForInstances[subMeshId] = currentRenderId;
  8018. }
  8019. return this._batchCache;
  8020. };
  8021. Mesh.prototype._renderWithInstances = function (subMesh, wireFrame, batch, effect, engine) {
  8022. var matricesCount = this.instances.length + 1;
  8023. var bufferSize = matricesCount * 16 * 4;
  8024. while (this._instancesBufferSize < bufferSize) {
  8025. this._instancesBufferSize *= 2;
  8026. }
  8027. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  8028. if (this._worldMatricesInstancesBuffer) {
  8029. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8030. }
  8031. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  8032. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  8033. }
  8034. var offset = 0;
  8035. var instancesCount = 0;
  8036. var world = this.getWorldMatrix();
  8037. if (batch.renderSelf[subMesh._id]) {
  8038. world.copyToArray(this._worldMatricesInstancesArray, offset);
  8039. offset += 16;
  8040. instancesCount++;
  8041. }
  8042. var visibleInstances = batch.visibleInstances[subMesh._id];
  8043. if (visibleInstances) {
  8044. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  8045. var instance = visibleInstances[instanceIndex];
  8046. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  8047. offset += 16;
  8048. instancesCount++;
  8049. }
  8050. }
  8051. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  8052. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  8053. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  8054. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  8055. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  8056. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  8057. this._draw(subMesh, !wireFrame, instancesCount);
  8058. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  8059. };
  8060. Mesh.prototype.render = function (subMesh) {
  8061. var scene = this.getScene();
  8062. var batch = this._getInstancesRenderList(subMesh._id);
  8063. if (batch.mustReturn) {
  8064. return;
  8065. }
  8066. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8067. return;
  8068. }
  8069. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8070. this._onBeforeRenderCallbacks[callbackIndex]();
  8071. }
  8072. var engine = scene.getEngine();
  8073. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8074. var effectiveMaterial = subMesh.getMaterial();
  8075. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  8076. return;
  8077. }
  8078. var savedDepthWrite = engine.getDepthWrite();
  8079. if (this.renderOutline) {
  8080. engine.setDepthWrite(false);
  8081. scene.getOutlineRenderer().render(subMesh, batch);
  8082. }
  8083. effectiveMaterial._preBind();
  8084. var effect = effectiveMaterial.getEffect();
  8085. var wireFrame = engine.forceWireframe || effectiveMaterial.wireframe;
  8086. this._bind(subMesh, effect, wireFrame);
  8087. var world = this.getWorldMatrix();
  8088. effectiveMaterial.bind(world, this);
  8089. if (hardwareInstancedRendering) {
  8090. this._renderWithInstances(subMesh, wireFrame, batch, effect, engine);
  8091. } else {
  8092. if (batch.renderSelf[subMesh._id]) {
  8093. this._draw(subMesh, !wireFrame);
  8094. }
  8095. if (batch.visibleInstances[subMesh._id]) {
  8096. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  8097. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  8098. world = instance.getWorldMatrix();
  8099. effectiveMaterial.bindOnlyWorldMatrix(world);
  8100. this._draw(subMesh, !wireFrame);
  8101. }
  8102. }
  8103. }
  8104. effectiveMaterial.unbind();
  8105. if (this.renderOutline && savedDepthWrite) {
  8106. engine.setDepthWrite(true);
  8107. engine.setColorWrite(false);
  8108. scene.getOutlineRenderer().render(subMesh, batch);
  8109. engine.setColorWrite(true);
  8110. }
  8111. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8112. this._onAfterRenderCallbacks[callbackIndex]();
  8113. }
  8114. };
  8115. Mesh.prototype.getEmittedParticleSystems = function () {
  8116. var results = new Array();
  8117. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8118. var particleSystem = this.getScene().particleSystems[index];
  8119. if (particleSystem.emitter === this) {
  8120. results.push(particleSystem);
  8121. }
  8122. }
  8123. return results;
  8124. };
  8125. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  8126. var results = new Array();
  8127. var descendants = this.getDescendants();
  8128. descendants.push(this);
  8129. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8130. var particleSystem = this.getScene().particleSystems[index];
  8131. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  8132. results.push(particleSystem);
  8133. }
  8134. }
  8135. return results;
  8136. };
  8137. Mesh.prototype.getChildren = function () {
  8138. var results = [];
  8139. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8140. var mesh = this.getScene().meshes[index];
  8141. if (mesh.parent == this) {
  8142. results.push(mesh);
  8143. }
  8144. }
  8145. return results;
  8146. };
  8147. Mesh.prototype._checkDelayState = function () {
  8148. var _this = this;
  8149. var that = this;
  8150. var scene = this.getScene();
  8151. if (this._geometry) {
  8152. this._geometry.load(scene);
  8153. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8154. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  8155. scene._addPendingData(that);
  8156. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  8157. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  8158. if (data instanceof ArrayBuffer) {
  8159. _this._delayLoadingFunction(data, _this);
  8160. } else {
  8161. _this._delayLoadingFunction(JSON.parse(data), _this);
  8162. }
  8163. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  8164. scene._removePendingData(_this);
  8165. }, function () {
  8166. }, scene.database, getBinaryData);
  8167. }
  8168. };
  8169. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  8170. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8171. return false;
  8172. }
  8173. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  8174. return false;
  8175. }
  8176. this._checkDelayState();
  8177. return true;
  8178. };
  8179. Mesh.prototype.setMaterialByID = function (id) {
  8180. var materials = this.getScene().materials;
  8181. for (var index = 0; index < materials.length; index++) {
  8182. if (materials[index].id == id) {
  8183. this.material = materials[index];
  8184. return;
  8185. }
  8186. }
  8187. var multiMaterials = this.getScene().multiMaterials;
  8188. for (index = 0; index < multiMaterials.length; index++) {
  8189. if (multiMaterials[index].id == id) {
  8190. this.material = multiMaterials[index];
  8191. return;
  8192. }
  8193. }
  8194. };
  8195. Mesh.prototype.getAnimatables = function () {
  8196. var results = [];
  8197. if (this.material) {
  8198. results.push(this.material);
  8199. }
  8200. return results;
  8201. };
  8202. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  8203. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  8204. return;
  8205. }
  8206. this._resetPointsArrayCache();
  8207. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8208. var temp = [];
  8209. for (var index = 0; index < data.length; index += 3) {
  8210. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8211. }
  8212. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  8213. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8214. return;
  8215. }
  8216. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8217. for (index = 0; index < data.length; index += 3) {
  8218. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8219. }
  8220. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  8221. };
  8222. Mesh.prototype._resetPointsArrayCache = function () {
  8223. this._positions = null;
  8224. };
  8225. Mesh.prototype._generatePointsArray = function () {
  8226. if (this._positions)
  8227. return true;
  8228. this._positions = [];
  8229. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8230. if (!data) {
  8231. return false;
  8232. }
  8233. for (var index = 0; index < data.length; index += 3) {
  8234. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  8235. }
  8236. return true;
  8237. };
  8238. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8239. var result = new BABYLON.Mesh(name, this.getScene());
  8240. this._geometry.applyToMesh(result);
  8241. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  8242. result.material = this.material;
  8243. if (newParent) {
  8244. result.parent = newParent;
  8245. }
  8246. if (!doNotCloneChildren) {
  8247. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8248. var mesh = this.getScene().meshes[index];
  8249. if (mesh.parent == this) {
  8250. mesh.clone(mesh.name, result);
  8251. }
  8252. }
  8253. }
  8254. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8255. var system = this.getScene().particleSystems[index];
  8256. if (system.emitter == this) {
  8257. system.clone(system.name, result);
  8258. }
  8259. }
  8260. result.computeWorldMatrix(true);
  8261. return result;
  8262. };
  8263. Mesh.prototype.dispose = function (doNotRecurse) {
  8264. if (this._geometry) {
  8265. this._geometry.releaseForMesh(this, true);
  8266. }
  8267. if (this._worldMatricesInstancesBuffer) {
  8268. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8269. this._worldMatricesInstancesBuffer = null;
  8270. }
  8271. while (this.instances.length) {
  8272. this.instances[0].dispose();
  8273. }
  8274. _super.prototype.dispose.call(this, doNotRecurse);
  8275. };
  8276. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  8277. var _this = this;
  8278. var scene = this.getScene();
  8279. var onload = function (img) {
  8280. var canvas = document.createElement("canvas");
  8281. var context = canvas.getContext("2d");
  8282. var heightMapWidth = img.width;
  8283. var heightMapHeight = img.height;
  8284. canvas.width = heightMapWidth;
  8285. canvas.height = heightMapHeight;
  8286. context.drawImage(img, 0, 0);
  8287. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8288. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  8289. };
  8290. BABYLON.Tools.LoadImage(url, onload, function () {
  8291. }, scene.database);
  8292. };
  8293. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  8294. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8295. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  8296. return;
  8297. }
  8298. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8299. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8300. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8301. var position = BABYLON.Vector3.Zero();
  8302. var normal = BABYLON.Vector3.Zero();
  8303. var uv = BABYLON.Vector2.Zero();
  8304. for (var index = 0; index < positions.length; index += 3) {
  8305. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  8306. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  8307. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  8308. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  8309. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  8310. var pos = (u + v * heightMapWidth) * 4;
  8311. var r = buffer[pos] / 255.0;
  8312. var g = buffer[pos + 1] / 255.0;
  8313. var b = buffer[pos + 2] / 255.0;
  8314. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  8315. normal.normalize();
  8316. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  8317. position = position.add(normal);
  8318. position.toArray(positions, index);
  8319. }
  8320. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  8321. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  8322. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  8323. };
  8324. Mesh.prototype.convertToFlatShadedMesh = function () {
  8325. var kinds = this.getVerticesDataKinds();
  8326. var vbs = [];
  8327. var data = [];
  8328. var newdata = [];
  8329. var updatableNormals = false;
  8330. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8331. var kind = kinds[kindIndex];
  8332. var vertexBuffer = this.getVertexBuffer(kind);
  8333. if (kind === BABYLON.VertexBuffer.NormalKind) {
  8334. updatableNormals = vertexBuffer.isUpdatable();
  8335. kinds.splice(kindIndex, 1);
  8336. kindIndex--;
  8337. continue;
  8338. }
  8339. vbs[kind] = vertexBuffer;
  8340. data[kind] = vbs[kind].getData();
  8341. newdata[kind] = [];
  8342. }
  8343. var previousSubmeshes = this.subMeshes.slice(0);
  8344. var indices = this.getIndices();
  8345. var totalIndices = this.getTotalIndices();
  8346. for (index = 0; index < totalIndices; index++) {
  8347. var vertexIndex = indices[index];
  8348. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8349. kind = kinds[kindIndex];
  8350. var stride = vbs[kind].getStrideSize();
  8351. for (var offset = 0; offset < stride; offset++) {
  8352. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  8353. }
  8354. }
  8355. }
  8356. var normals = [];
  8357. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  8358. for (var index = 0; index < totalIndices; index += 3) {
  8359. indices[index] = index;
  8360. indices[index + 1] = index + 1;
  8361. indices[index + 2] = index + 2;
  8362. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  8363. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  8364. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  8365. var p1p2 = p1.subtract(p2);
  8366. var p3p2 = p3.subtract(p2);
  8367. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  8368. for (var localIndex = 0; localIndex < 3; localIndex++) {
  8369. normals.push(normal.x);
  8370. normals.push(normal.y);
  8371. normals.push(normal.z);
  8372. }
  8373. }
  8374. this.setIndices(indices);
  8375. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  8376. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8377. kind = kinds[kindIndex];
  8378. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  8379. }
  8380. this.releaseSubMeshes();
  8381. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  8382. var previousOne = previousSubmeshes[submeshIndex];
  8383. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  8384. }
  8385. this.synchronizeInstances();
  8386. };
  8387. Mesh.prototype.createInstance = function (name) {
  8388. return new BABYLON.InstancedMesh(name, this);
  8389. };
  8390. Mesh.prototype.synchronizeInstances = function () {
  8391. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  8392. var instance = this.instances[instanceIndex];
  8393. instance._syncSubMeshes();
  8394. }
  8395. };
  8396. Mesh.CreateBox = function (name, size, scene, updatable) {
  8397. var box = new BABYLON.Mesh(name, scene);
  8398. var vertexData = BABYLON.VertexData.CreateBox(size);
  8399. vertexData.applyToMesh(box, updatable);
  8400. return box;
  8401. };
  8402. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  8403. var sphere = new BABYLON.Mesh(name, scene);
  8404. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  8405. vertexData.applyToMesh(sphere, updatable);
  8406. return sphere;
  8407. };
  8408. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  8409. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  8410. if (scene !== undefined) {
  8411. updatable = scene;
  8412. }
  8413. scene = subdivisions;
  8414. subdivisions = 1;
  8415. }
  8416. var cylinder = new BABYLON.Mesh(name, scene);
  8417. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  8418. vertexData.applyToMesh(cylinder, updatable);
  8419. return cylinder;
  8420. };
  8421. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  8422. var torus = new BABYLON.Mesh(name, scene);
  8423. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  8424. vertexData.applyToMesh(torus, updatable);
  8425. return torus;
  8426. };
  8427. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  8428. var torusKnot = new BABYLON.Mesh(name, scene);
  8429. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  8430. vertexData.applyToMesh(torusKnot, updatable);
  8431. return torusKnot;
  8432. };
  8433. Mesh.CreateLines = function (name, points, scene, updatable) {
  8434. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  8435. var vertexData = BABYLON.VertexData.CreateLines(points);
  8436. vertexData.applyToMesh(lines, updatable);
  8437. return lines;
  8438. };
  8439. Mesh.CreatePlane = function (name, size, scene, updatable) {
  8440. var plane = new BABYLON.Mesh(name, scene);
  8441. var vertexData = BABYLON.VertexData.CreatePlane(size);
  8442. vertexData.applyToMesh(plane, updatable);
  8443. return plane;
  8444. };
  8445. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  8446. var ground = new BABYLON.GroundMesh(name, scene);
  8447. ground._setReady(false);
  8448. ground._subdivisions = subdivisions;
  8449. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  8450. vertexData.applyToMesh(ground, updatable);
  8451. ground._setReady(true);
  8452. return ground;
  8453. };
  8454. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  8455. var tiledGround = new BABYLON.Mesh(name, scene);
  8456. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  8457. vertexData.applyToMesh(tiledGround, updatable);
  8458. return tiledGround;
  8459. };
  8460. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  8461. var ground = new BABYLON.GroundMesh(name, scene);
  8462. ground._subdivisions = subdivisions;
  8463. ground._setReady(false);
  8464. var onload = function (img) {
  8465. var canvas = document.createElement("canvas");
  8466. var context = canvas.getContext("2d");
  8467. var heightMapWidth = img.width;
  8468. var heightMapHeight = img.height;
  8469. canvas.width = heightMapWidth;
  8470. canvas.height = heightMapHeight;
  8471. context.drawImage(img, 0, 0);
  8472. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8473. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  8474. vertexData.applyToMesh(ground, updatable);
  8475. ground._setReady(true);
  8476. };
  8477. BABYLON.Tools.LoadImage(url, onload, function () {
  8478. }, scene.database);
  8479. return ground;
  8480. };
  8481. Mesh.MinMax = function (meshes) {
  8482. var minVector = null;
  8483. var maxVector = null;
  8484. for (var i in meshes) {
  8485. var mesh = meshes[i];
  8486. var boundingBox = mesh.getBoundingInfo().boundingBox;
  8487. if (!minVector) {
  8488. minVector = boundingBox.minimumWorld;
  8489. maxVector = boundingBox.maximumWorld;
  8490. continue;
  8491. }
  8492. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  8493. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  8494. }
  8495. return {
  8496. min: minVector,
  8497. max: maxVector
  8498. };
  8499. };
  8500. Mesh.Center = function (meshesOrMinMaxVector) {
  8501. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8502. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  8503. };
  8504. return Mesh;
  8505. })(BABYLON.AbstractMesh);
  8506. BABYLON.Mesh = Mesh;
  8507. })(BABYLON || (BABYLON = {}));
  8508. var __extends = this.__extends || function (d, b) {
  8509. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8510. function __() { this.constructor = d; }
  8511. __.prototype = b.prototype;
  8512. d.prototype = new __();
  8513. };
  8514. var BABYLON;
  8515. (function (BABYLON) {
  8516. var GroundMesh = (function (_super) {
  8517. __extends(GroundMesh, _super);
  8518. function GroundMesh(name, scene) {
  8519. _super.call(this, name, scene);
  8520. this.generateOctree = false;
  8521. this._worldInverse = new BABYLON.Matrix();
  8522. }
  8523. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  8524. get: function () {
  8525. return this._subdivisions;
  8526. },
  8527. enumerable: true,
  8528. configurable: true
  8529. });
  8530. GroundMesh.prototype.optimize = function (chunksCount) {
  8531. this.subdivide(this._subdivisions);
  8532. this.createOrUpdateSubmeshesOctree(32);
  8533. };
  8534. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  8535. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  8536. this.getWorldMatrix().invertToRef(this._worldInverse);
  8537. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  8538. var pickInfo = this.intersects(ray);
  8539. if (pickInfo.hit) {
  8540. return pickInfo.pickedPoint.y;
  8541. }
  8542. return 0;
  8543. };
  8544. return GroundMesh;
  8545. })(BABYLON.Mesh);
  8546. BABYLON.GroundMesh = GroundMesh;
  8547. })(BABYLON || (BABYLON = {}));
  8548. var __extends = this.__extends || function (d, b) {
  8549. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8550. function __() { this.constructor = d; }
  8551. __.prototype = b.prototype;
  8552. d.prototype = new __();
  8553. };
  8554. var BABYLON;
  8555. (function (BABYLON) {
  8556. var InstancedMesh = (function (_super) {
  8557. __extends(InstancedMesh, _super);
  8558. function InstancedMesh(name, source) {
  8559. _super.call(this, name, source.getScene());
  8560. source.instances.push(this);
  8561. this._sourceMesh = source;
  8562. this.position.copyFrom(source.position);
  8563. this.rotation.copyFrom(source.rotation);
  8564. this.scaling.copyFrom(source.scaling);
  8565. if (source.rotationQuaternion) {
  8566. this.rotationQuaternion = source.rotationQuaternion.clone();
  8567. }
  8568. this.infiniteDistance = source.infiniteDistance;
  8569. this.setPivotMatrix(source.getPivotMatrix());
  8570. this.refreshBoundingInfo();
  8571. this._syncSubMeshes();
  8572. }
  8573. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  8574. get: function () {
  8575. return this._sourceMesh.receiveShadows;
  8576. },
  8577. enumerable: true,
  8578. configurable: true
  8579. });
  8580. Object.defineProperty(InstancedMesh.prototype, "material", {
  8581. get: function () {
  8582. return this._sourceMesh.material;
  8583. },
  8584. enumerable: true,
  8585. configurable: true
  8586. });
  8587. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  8588. get: function () {
  8589. return this._sourceMesh.visibility;
  8590. },
  8591. enumerable: true,
  8592. configurable: true
  8593. });
  8594. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  8595. get: function () {
  8596. return this._sourceMesh.skeleton;
  8597. },
  8598. enumerable: true,
  8599. configurable: true
  8600. });
  8601. InstancedMesh.prototype.getTotalVertices = function () {
  8602. return this._sourceMesh.getTotalVertices();
  8603. };
  8604. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  8605. get: function () {
  8606. return this._sourceMesh;
  8607. },
  8608. enumerable: true,
  8609. configurable: true
  8610. });
  8611. InstancedMesh.prototype.getVerticesData = function (kind) {
  8612. return this._sourceMesh.getVerticesData(kind);
  8613. };
  8614. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  8615. return this._sourceMesh.isVerticesDataPresent(kind);
  8616. };
  8617. InstancedMesh.prototype.getIndices = function () {
  8618. return this._sourceMesh.getIndices();
  8619. };
  8620. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  8621. get: function () {
  8622. return this._sourceMesh._positions;
  8623. },
  8624. enumerable: true,
  8625. configurable: true
  8626. });
  8627. InstancedMesh.prototype.refreshBoundingInfo = function () {
  8628. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8629. if (data) {
  8630. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  8631. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8632. }
  8633. this._updateBoundingInfo();
  8634. };
  8635. InstancedMesh.prototype._preActivate = function () {
  8636. this.sourceMesh._preActivate();
  8637. };
  8638. InstancedMesh.prototype._activate = function (renderId) {
  8639. this.sourceMesh._registerInstanceForRenderId(this, renderId);
  8640. };
  8641. InstancedMesh.prototype._syncSubMeshes = function () {
  8642. this.releaseSubMeshes();
  8643. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  8644. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  8645. }
  8646. };
  8647. InstancedMesh.prototype._generatePointsArray = function () {
  8648. return this._sourceMesh._generatePointsArray();
  8649. };
  8650. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8651. var result = this._sourceMesh.createInstance(name);
  8652. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  8653. this.refreshBoundingInfo();
  8654. if (newParent) {
  8655. result.parent = newParent;
  8656. }
  8657. if (!doNotCloneChildren) {
  8658. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8659. var mesh = this.getScene().meshes[index];
  8660. if (mesh.parent == this) {
  8661. mesh.clone(mesh.name, result);
  8662. }
  8663. }
  8664. }
  8665. result.computeWorldMatrix(true);
  8666. return result;
  8667. };
  8668. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  8669. var index = this._sourceMesh.instances.indexOf(this);
  8670. this._sourceMesh.instances.splice(index, 1);
  8671. _super.prototype.dispose.call(this, doNotRecurse);
  8672. };
  8673. return InstancedMesh;
  8674. })(BABYLON.AbstractMesh);
  8675. BABYLON.InstancedMesh = InstancedMesh;
  8676. })(BABYLON || (BABYLON = {}));
  8677. var BABYLON;
  8678. (function (BABYLON) {
  8679. var SubMesh = (function () {
  8680. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  8681. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  8682. this.materialIndex = materialIndex;
  8683. this.verticesStart = verticesStart;
  8684. this.verticesCount = verticesCount;
  8685. this.indexStart = indexStart;
  8686. this.indexCount = indexCount;
  8687. this._renderId = 0;
  8688. this._mesh = mesh;
  8689. this._renderingMesh = renderingMesh || mesh;
  8690. mesh.subMeshes.push(this);
  8691. this._id = mesh.subMeshes.length - 1;
  8692. if (createBoundingBox) {
  8693. this.refreshBoundingInfo();
  8694. }
  8695. }
  8696. SubMesh.prototype.getBoundingInfo = function () {
  8697. return this._boundingInfo;
  8698. };
  8699. SubMesh.prototype.getMesh = function () {
  8700. return this._mesh;
  8701. };
  8702. SubMesh.prototype.getRenderingMesh = function () {
  8703. return this._renderingMesh;
  8704. };
  8705. SubMesh.prototype.getMaterial = function () {
  8706. var rootMaterial = this._renderingMesh.material;
  8707. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  8708. var multiMaterial = rootMaterial;
  8709. return multiMaterial.getSubMaterial(this.materialIndex);
  8710. }
  8711. if (!rootMaterial) {
  8712. return this._mesh.getScene().defaultMaterial;
  8713. }
  8714. return rootMaterial;
  8715. };
  8716. SubMesh.prototype.refreshBoundingInfo = function () {
  8717. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8718. if (!data) {
  8719. this._boundingInfo = this._mesh._boundingInfo;
  8720. return;
  8721. }
  8722. var indices = this._renderingMesh.getIndices();
  8723. var extend;
  8724. if (this.indexStart === 0 && this.indexCount === indices.length) {
  8725. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  8726. } else {
  8727. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  8728. }
  8729. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8730. };
  8731. SubMesh.prototype._checkCollision = function (collider) {
  8732. return this._boundingInfo._checkCollision(collider);
  8733. };
  8734. SubMesh.prototype.updateBoundingInfo = function (world) {
  8735. if (!this._boundingInfo) {
  8736. this.refreshBoundingInfo();
  8737. }
  8738. this._boundingInfo._update(world);
  8739. };
  8740. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  8741. return this._boundingInfo.isInFrustum(frustumPlanes);
  8742. };
  8743. SubMesh.prototype.render = function () {
  8744. this._renderingMesh.render(this);
  8745. };
  8746. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  8747. if (!this._linesIndexBuffer) {
  8748. var linesIndices = [];
  8749. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8750. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  8751. }
  8752. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  8753. this.linesIndexCount = linesIndices.length;
  8754. }
  8755. return this._linesIndexBuffer;
  8756. };
  8757. SubMesh.prototype.canIntersects = function (ray) {
  8758. return ray.intersectsBox(this._boundingInfo.boundingBox);
  8759. };
  8760. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  8761. var intersectInfo = null;
  8762. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8763. var p0 = positions[indices[index]];
  8764. var p1 = positions[indices[index + 1]];
  8765. var p2 = positions[indices[index + 2]];
  8766. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  8767. if (currentIntersectInfo) {
  8768. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8769. intersectInfo = currentIntersectInfo;
  8770. intersectInfo.faceId = index / 3;
  8771. if (fastCheck) {
  8772. break;
  8773. }
  8774. }
  8775. }
  8776. }
  8777. return intersectInfo;
  8778. };
  8779. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  8780. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  8781. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  8782. return result;
  8783. };
  8784. SubMesh.prototype.dispose = function () {
  8785. if (this._linesIndexBuffer) {
  8786. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  8787. this._linesIndexBuffer = null;
  8788. }
  8789. var index = this._mesh.subMeshes.indexOf(this);
  8790. this._mesh.subMeshes.splice(index, 1);
  8791. };
  8792. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  8793. var minVertexIndex = Number.MAX_VALUE;
  8794. var maxVertexIndex = -Number.MAX_VALUE;
  8795. renderingMesh = renderingMesh || mesh;
  8796. var indices = renderingMesh.getIndices();
  8797. for (var index = startIndex; index < startIndex + indexCount; index++) {
  8798. var vertexIndex = indices[index];
  8799. if (vertexIndex < minVertexIndex)
  8800. minVertexIndex = vertexIndex;
  8801. if (vertexIndex > maxVertexIndex)
  8802. maxVertexIndex = vertexIndex;
  8803. }
  8804. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  8805. };
  8806. return SubMesh;
  8807. })();
  8808. BABYLON.SubMesh = SubMesh;
  8809. })(BABYLON || (BABYLON = {}));
  8810. var BABYLON;
  8811. (function (BABYLON) {
  8812. var BaseTexture = (function () {
  8813. function BaseTexture(scene) {
  8814. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  8815. this.hasAlpha = false;
  8816. this.getAlphaFromRGB = false;
  8817. this.level = 1;
  8818. this.isCube = false;
  8819. this.isRenderTarget = false;
  8820. this.animations = new Array();
  8821. this.coordinatesIndex = 0;
  8822. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  8823. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  8824. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  8825. this.anisotropicFilteringLevel = 4;
  8826. this._scene = scene;
  8827. this._scene.textures.push(this);
  8828. }
  8829. BaseTexture.prototype.getScene = function () {
  8830. return this._scene;
  8831. };
  8832. BaseTexture.prototype.getTextureMatrix = function () {
  8833. return null;
  8834. };
  8835. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  8836. return null;
  8837. };
  8838. BaseTexture.prototype.getInternalTexture = function () {
  8839. return this._texture;
  8840. };
  8841. BaseTexture.prototype.isReady = function () {
  8842. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8843. return true;
  8844. }
  8845. if (this._texture) {
  8846. return this._texture.isReady;
  8847. }
  8848. return false;
  8849. };
  8850. BaseTexture.prototype.getSize = function () {
  8851. if (this._texture._width) {
  8852. return { width: this._texture._width, height: this._texture._height };
  8853. }
  8854. if (this._texture._size) {
  8855. return { width: this._texture._size, height: this._texture._size };
  8856. }
  8857. return { width: 0, height: 0 };
  8858. };
  8859. BaseTexture.prototype.getBaseSize = function () {
  8860. if (!this.isReady())
  8861. return { width: 0, height: 0 };
  8862. if (this._texture._size) {
  8863. return { width: this._texture._size, height: this._texture._size };
  8864. }
  8865. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  8866. };
  8867. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  8868. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8869. for (var index = 0; index < texturesCache.length; index++) {
  8870. var texturesCacheEntry = texturesCache[index];
  8871. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  8872. texturesCacheEntry.references++;
  8873. return texturesCacheEntry;
  8874. }
  8875. }
  8876. return null;
  8877. };
  8878. BaseTexture.prototype.delayLoad = function () {
  8879. };
  8880. BaseTexture.prototype.releaseInternalTexture = function () {
  8881. if (!this._texture) {
  8882. return;
  8883. }
  8884. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8885. this._texture.references--;
  8886. if (this._texture.references == 0) {
  8887. var index = texturesCache.indexOf(this._texture);
  8888. texturesCache.splice(index, 1);
  8889. this._scene.getEngine()._releaseTexture(this._texture);
  8890. delete this._texture;
  8891. }
  8892. };
  8893. BaseTexture.prototype.clone = function () {
  8894. return null;
  8895. };
  8896. BaseTexture.prototype.dispose = function () {
  8897. var index = this._scene.textures.indexOf(this);
  8898. if (index >= 0) {
  8899. this._scene.textures.splice(index, 1);
  8900. }
  8901. if (this._texture === undefined) {
  8902. return;
  8903. }
  8904. this.releaseInternalTexture();
  8905. if (this.onDispose) {
  8906. this.onDispose();
  8907. }
  8908. };
  8909. return BaseTexture;
  8910. })();
  8911. BABYLON.BaseTexture = BaseTexture;
  8912. })(BABYLON || (BABYLON = {}));
  8913. var BABYLON;
  8914. (function (BABYLON) {
  8915. var RenderingGroup = (function () {
  8916. function RenderingGroup(index, scene) {
  8917. this.index = index;
  8918. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  8919. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  8920. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  8921. this._scene = scene;
  8922. }
  8923. RenderingGroup.prototype.render = function (customRenderFunction, beforeTransparents) {
  8924. if (customRenderFunction) {
  8925. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
  8926. return true;
  8927. }
  8928. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  8929. return false;
  8930. }
  8931. var engine = this._scene.getEngine();
  8932. var subIndex;
  8933. var submesh;
  8934. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  8935. submesh = this._opaqueSubMeshes.data[subIndex];
  8936. this._activeVertices += submesh.verticesCount;
  8937. submesh.render();
  8938. }
  8939. engine.setAlphaTesting(true);
  8940. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  8941. submesh = this._alphaTestSubMeshes.data[subIndex];
  8942. this._activeVertices += submesh.verticesCount;
  8943. submesh.render();
  8944. }
  8945. engine.setAlphaTesting(false);
  8946. if (beforeTransparents) {
  8947. beforeTransparents();
  8948. }
  8949. if (this._transparentSubMeshes.length) {
  8950. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  8951. submesh = this._transparentSubMeshes.data[subIndex];
  8952. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  8953. }
  8954. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  8955. sortedArray.sort(function (a, b) {
  8956. if (a._distanceToCamera < b._distanceToCamera) {
  8957. return 1;
  8958. }
  8959. if (a._distanceToCamera > b._distanceToCamera) {
  8960. return -1;
  8961. }
  8962. return 0;
  8963. });
  8964. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  8965. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  8966. submesh = sortedArray[subIndex];
  8967. this._activeVertices += submesh.verticesCount;
  8968. submesh.render();
  8969. }
  8970. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  8971. }
  8972. return true;
  8973. };
  8974. RenderingGroup.prototype.prepare = function () {
  8975. this._opaqueSubMeshes.reset();
  8976. this._transparentSubMeshes.reset();
  8977. this._alphaTestSubMeshes.reset();
  8978. };
  8979. RenderingGroup.prototype.dispatch = function (subMesh) {
  8980. var material = subMesh.getMaterial();
  8981. var mesh = subMesh.getMesh();
  8982. if (material.needAlphaBlending() || mesh.visibility < 1.0) {
  8983. if (material.alpha > 0 || mesh.visibility < 1.0) {
  8984. this._transparentSubMeshes.push(subMesh);
  8985. }
  8986. } else if (material.needAlphaTesting()) {
  8987. this._alphaTestSubMeshes.push(subMesh);
  8988. } else {
  8989. this._opaqueSubMeshes.push(subMesh);
  8990. }
  8991. };
  8992. return RenderingGroup;
  8993. })();
  8994. BABYLON.RenderingGroup = RenderingGroup;
  8995. })(BABYLON || (BABYLON = {}));
  8996. var BABYLON;
  8997. (function (BABYLON) {
  8998. var RenderingManager = (function () {
  8999. function RenderingManager(scene) {
  9000. this._renderingGroups = new Array();
  9001. this._scene = scene;
  9002. }
  9003. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  9004. if (this._scene._activeParticleSystems.length === 0) {
  9005. return;
  9006. }
  9007. var beforeParticlesDate = new Date().getTime();
  9008. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  9009. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  9010. if (particleSystem.renderingGroupId !== index) {
  9011. continue;
  9012. }
  9013. this._clearDepthBuffer();
  9014. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  9015. this._scene._activeParticles += particleSystem.render();
  9016. }
  9017. }
  9018. this._scene._particlesDuration += new Date().getTime() - beforeParticlesDate;
  9019. };
  9020. RenderingManager.prototype._renderSprites = function (index) {
  9021. if (this._scene.spriteManagers.length === 0) {
  9022. return;
  9023. }
  9024. var beforeSpritessDate = new Date().getTime();
  9025. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  9026. var spriteManager = this._scene.spriteManagers[id];
  9027. if (spriteManager.renderingGroupId === index) {
  9028. this._clearDepthBuffer();
  9029. spriteManager.render();
  9030. }
  9031. }
  9032. this._scene._spritesDuration += new Date().getTime() - beforeSpritessDate;
  9033. };
  9034. RenderingManager.prototype._clearDepthBuffer = function () {
  9035. if (this._depthBufferAlreadyCleaned) {
  9036. return;
  9037. }
  9038. this._scene.getEngine().clear(0, false, true);
  9039. this._depthBufferAlreadyCleaned = true;
  9040. };
  9041. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  9042. var _this = this;
  9043. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  9044. this._depthBufferAlreadyCleaned = false;
  9045. var renderingGroup = this._renderingGroups[index];
  9046. if (renderingGroup) {
  9047. this._clearDepthBuffer();
  9048. if (!renderingGroup.render(customRenderFunction, function () {
  9049. if (renderSprites) {
  9050. _this._renderSprites(index);
  9051. }
  9052. })) {
  9053. this._renderingGroups.splice(index, 1);
  9054. }
  9055. } else if (renderSprites) {
  9056. this._renderSprites(index);
  9057. }
  9058. if (renderParticles) {
  9059. this._renderParticles(index, activeMeshes);
  9060. }
  9061. }
  9062. };
  9063. RenderingManager.prototype.reset = function () {
  9064. for (var index in this._renderingGroups) {
  9065. var renderingGroup = this._renderingGroups[index];
  9066. renderingGroup.prepare();
  9067. }
  9068. };
  9069. RenderingManager.prototype.dispatch = function (subMesh) {
  9070. var mesh = subMesh.getMesh();
  9071. var renderingGroupId = mesh.renderingGroupId || 0;
  9072. if (!this._renderingGroups[renderingGroupId]) {
  9073. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  9074. }
  9075. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  9076. };
  9077. RenderingManager.MAX_RENDERINGGROUPS = 4;
  9078. return RenderingManager;
  9079. })();
  9080. BABYLON.RenderingManager = RenderingManager;
  9081. })(BABYLON || (BABYLON = {}));
  9082. var __extends = this.__extends || function (d, b) {
  9083. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9084. function __() { this.constructor = d; }
  9085. __.prototype = b.prototype;
  9086. d.prototype = new __();
  9087. };
  9088. var BABYLON;
  9089. (function (BABYLON) {
  9090. var Texture = (function (_super) {
  9091. __extends(Texture, _super);
  9092. function Texture(url, scene, noMipmap, invertY, samplingMode) {
  9093. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  9094. _super.call(this, scene);
  9095. this.uOffset = 0;
  9096. this.vOffset = 0;
  9097. this.uScale = 1.0;
  9098. this.vScale = 1.0;
  9099. this.uAng = 0;
  9100. this.vAng = 0;
  9101. this.wAng = 0;
  9102. this.name = url;
  9103. this.url = url;
  9104. this._noMipmap = noMipmap;
  9105. this._invertY = invertY;
  9106. this._samplingMode = samplingMode;
  9107. if (!url) {
  9108. return;
  9109. }
  9110. this._texture = this._getFromCache(url, noMipmap);
  9111. if (!this._texture) {
  9112. if (!scene.useDelayedTextureLoading) {
  9113. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode);
  9114. } else {
  9115. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9116. }
  9117. }
  9118. }
  9119. Texture.prototype.delayLoad = function () {
  9120. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9121. return;
  9122. }
  9123. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9124. this._texture = this._getFromCache(this.url, this._noMipmap);
  9125. if (!this._texture) {
  9126. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode);
  9127. }
  9128. };
  9129. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  9130. x -= this.uOffset + 0.5;
  9131. y -= this.vOffset + 0.5;
  9132. z -= 0.5;
  9133. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  9134. t.x *= this.uScale;
  9135. t.y *= this.vScale;
  9136. t.x += 0.5;
  9137. t.y += 0.5;
  9138. t.z += 0.5;
  9139. };
  9140. Texture.prototype.getTextureMatrix = function () {
  9141. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.uAng === this._cachedUAng && this.vAng === this._cachedVAng && this.wAng === this._cachedWAng) {
  9142. return this._cachedTextureMatrix;
  9143. }
  9144. this._cachedUOffset = this.uOffset;
  9145. this._cachedVOffset = this.vOffset;
  9146. this._cachedUScale = this.uScale;
  9147. this._cachedVScale = this.vScale;
  9148. this._cachedUAng = this.uAng;
  9149. this._cachedVAng = this.vAng;
  9150. this._cachedWAng = this.wAng;
  9151. if (!this._cachedTextureMatrix) {
  9152. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9153. this._rowGenerationMatrix = new BABYLON.Matrix();
  9154. this._t0 = BABYLON.Vector3.Zero();
  9155. this._t1 = BABYLON.Vector3.Zero();
  9156. this._t2 = BABYLON.Vector3.Zero();
  9157. }
  9158. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  9159. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  9160. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  9161. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  9162. this._t1.subtractInPlace(this._t0);
  9163. this._t2.subtractInPlace(this._t0);
  9164. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9165. this._cachedTextureMatrix.m[0] = this._t1.x;
  9166. this._cachedTextureMatrix.m[1] = this._t1.y;
  9167. this._cachedTextureMatrix.m[2] = this._t1.z;
  9168. this._cachedTextureMatrix.m[4] = this._t2.x;
  9169. this._cachedTextureMatrix.m[5] = this._t2.y;
  9170. this._cachedTextureMatrix.m[6] = this._t2.z;
  9171. this._cachedTextureMatrix.m[8] = this._t0.x;
  9172. this._cachedTextureMatrix.m[9] = this._t0.y;
  9173. this._cachedTextureMatrix.m[10] = this._t0.z;
  9174. return this._cachedTextureMatrix;
  9175. };
  9176. Texture.prototype.getReflectionTextureMatrix = function () {
  9177. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  9178. return this._cachedTextureMatrix;
  9179. }
  9180. if (!this._cachedTextureMatrix) {
  9181. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9182. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  9183. }
  9184. switch (this.coordinatesMode) {
  9185. case BABYLON.Texture.SPHERICAL_MODE:
  9186. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9187. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  9188. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  9189. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  9190. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  9191. break;
  9192. case BABYLON.Texture.PLANAR_MODE:
  9193. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9194. this._cachedTextureMatrix[0] = this.uScale;
  9195. this._cachedTextureMatrix[5] = this.vScale;
  9196. this._cachedTextureMatrix[12] = this.uOffset;
  9197. this._cachedTextureMatrix[13] = this.vOffset;
  9198. break;
  9199. case BABYLON.Texture.PROJECTION_MODE:
  9200. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  9201. this._projectionModeMatrix.m[0] = 0.5;
  9202. this._projectionModeMatrix.m[5] = -0.5;
  9203. this._projectionModeMatrix.m[10] = 0.0;
  9204. this._projectionModeMatrix.m[12] = 0.5;
  9205. this._projectionModeMatrix.m[13] = 0.5;
  9206. this._projectionModeMatrix.m[14] = 1.0;
  9207. this._projectionModeMatrix.m[15] = 1.0;
  9208. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  9209. break;
  9210. default:
  9211. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9212. break;
  9213. }
  9214. return this._cachedTextureMatrix;
  9215. };
  9216. Texture.prototype.clone = function () {
  9217. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  9218. newTexture.hasAlpha = this.hasAlpha;
  9219. newTexture.level = this.level;
  9220. newTexture.wrapU = this.wrapU;
  9221. newTexture.wrapV = this.wrapV;
  9222. newTexture.coordinatesIndex = this.coordinatesIndex;
  9223. newTexture.coordinatesMode = this.coordinatesMode;
  9224. newTexture.uOffset = this.uOffset;
  9225. newTexture.vOffset = this.vOffset;
  9226. newTexture.uScale = this.uScale;
  9227. newTexture.vScale = this.vScale;
  9228. newTexture.uAng = this.uAng;
  9229. newTexture.vAng = this.vAng;
  9230. newTexture.wAng = this.wAng;
  9231. return newTexture;
  9232. };
  9233. Texture.NEAREST_SAMPLINGMODE = 1;
  9234. Texture.BILINEAR_SAMPLINGMODE = 2;
  9235. Texture.TRILINEAR_SAMPLINGMODE = 3;
  9236. Texture.EXPLICIT_MODE = 0;
  9237. Texture.SPHERICAL_MODE = 1;
  9238. Texture.PLANAR_MODE = 2;
  9239. Texture.CUBIC_MODE = 3;
  9240. Texture.PROJECTION_MODE = 4;
  9241. Texture.SKYBOX_MODE = 5;
  9242. Texture.CLAMP_ADDRESSMODE = 0;
  9243. Texture.WRAP_ADDRESSMODE = 1;
  9244. Texture.MIRROR_ADDRESSMODE = 2;
  9245. return Texture;
  9246. })(BABYLON.BaseTexture);
  9247. BABYLON.Texture = Texture;
  9248. })(BABYLON || (BABYLON = {}));
  9249. var __extends = this.__extends || function (d, b) {
  9250. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9251. function __() { this.constructor = d; }
  9252. __.prototype = b.prototype;
  9253. d.prototype = new __();
  9254. };
  9255. var BABYLON;
  9256. (function (BABYLON) {
  9257. var CubeTexture = (function (_super) {
  9258. __extends(CubeTexture, _super);
  9259. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  9260. _super.call(this, scene);
  9261. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  9262. this.name = rootUrl;
  9263. this.url = rootUrl;
  9264. this._noMipmap = noMipmap;
  9265. this.hasAlpha = false;
  9266. this._texture = this._getFromCache(rootUrl, noMipmap);
  9267. if (!extensions) {
  9268. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  9269. }
  9270. this._extensions = extensions;
  9271. if (!this._texture) {
  9272. if (!scene.useDelayedTextureLoading) {
  9273. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  9274. } else {
  9275. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9276. }
  9277. }
  9278. this.isCube = true;
  9279. this._textureMatrix = BABYLON.Matrix.Identity();
  9280. }
  9281. CubeTexture.prototype.clone = function () {
  9282. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  9283. newTexture.level = this.level;
  9284. newTexture.wrapU = this.wrapU;
  9285. newTexture.wrapV = this.wrapV;
  9286. newTexture.coordinatesIndex = this.coordinatesIndex;
  9287. newTexture.coordinatesMode = this.coordinatesMode;
  9288. return newTexture;
  9289. };
  9290. CubeTexture.prototype.delayLoad = function () {
  9291. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9292. return;
  9293. }
  9294. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9295. this._texture = this._getFromCache(this.url, this._noMipmap);
  9296. if (!this._texture) {
  9297. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  9298. }
  9299. };
  9300. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  9301. return this._textureMatrix;
  9302. };
  9303. return CubeTexture;
  9304. })(BABYLON.BaseTexture);
  9305. BABYLON.CubeTexture = CubeTexture;
  9306. })(BABYLON || (BABYLON = {}));
  9307. var __extends = this.__extends || function (d, b) {
  9308. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9309. function __() { this.constructor = d; }
  9310. __.prototype = b.prototype;
  9311. d.prototype = new __();
  9312. };
  9313. var BABYLON;
  9314. (function (BABYLON) {
  9315. var RenderTargetTexture = (function (_super) {
  9316. __extends(RenderTargetTexture, _super);
  9317. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  9318. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  9319. _super.call(this, null, scene, !generateMipMaps);
  9320. this.renderList = new Array();
  9321. this.renderParticles = true;
  9322. this.renderSprites = false;
  9323. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  9324. this._currentRefreshId = -1;
  9325. this._refreshRate = 1;
  9326. this.name = name;
  9327. this.isRenderTarget = true;
  9328. this._size = size;
  9329. this._generateMipMaps = generateMipMaps;
  9330. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  9331. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  9332. this._renderingManager = new BABYLON.RenderingManager(scene);
  9333. }
  9334. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  9335. this._currentRefreshId = -1;
  9336. };
  9337. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  9338. get: function () {
  9339. return this._refreshRate;
  9340. },
  9341. set: function (value) {
  9342. this._refreshRate = value;
  9343. this.resetRefreshCounter();
  9344. },
  9345. enumerable: true,
  9346. configurable: true
  9347. });
  9348. RenderTargetTexture.prototype._shouldRender = function () {
  9349. if (this._currentRefreshId === -1) {
  9350. this._currentRefreshId = 1;
  9351. return true;
  9352. }
  9353. if (this.refreshRate == this._currentRefreshId) {
  9354. this._currentRefreshId = 1;
  9355. return true;
  9356. }
  9357. this._currentRefreshId++;
  9358. return false;
  9359. };
  9360. RenderTargetTexture.prototype.getRenderSize = function () {
  9361. return this._size;
  9362. };
  9363. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  9364. this.releaseInternalTexture();
  9365. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  9366. };
  9367. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  9368. var scene = this.getScene();
  9369. var engine = scene.getEngine();
  9370. if (this._waitingRenderList) {
  9371. this.renderList = [];
  9372. for (var index = 0; index < this._waitingRenderList.length; index++) {
  9373. var id = this._waitingRenderList[index];
  9374. this.renderList.push(scene.getMeshByID(id));
  9375. }
  9376. delete this._waitingRenderList;
  9377. }
  9378. if (!this.renderList) {
  9379. return;
  9380. }
  9381. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  9382. engine.bindFramebuffer(this._texture);
  9383. }
  9384. engine.clear(scene.clearColor, true, true);
  9385. this._renderingManager.reset();
  9386. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  9387. var mesh = this.renderList[meshIndex];
  9388. if (mesh) {
  9389. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  9390. this.resetRefreshCounter();
  9391. continue;
  9392. }
  9393. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  9394. mesh._activate(scene.getRenderId());
  9395. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  9396. var subMesh = mesh.subMeshes[subIndex];
  9397. scene._activeVertices += subMesh.verticesCount;
  9398. this._renderingManager.dispatch(subMesh);
  9399. }
  9400. }
  9401. }
  9402. }
  9403. if (!this._doNotChangeAspectRatio) {
  9404. scene.updateTransformMatrix(true);
  9405. }
  9406. if (this.onBeforeRender) {
  9407. this.onBeforeRender();
  9408. }
  9409. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  9410. if (useCameraPostProcess) {
  9411. scene.postProcessManager._finalizeFrame(false, this._texture);
  9412. }
  9413. if (this.onAfterRender) {
  9414. this.onAfterRender();
  9415. }
  9416. engine.unBindFramebuffer(this._texture);
  9417. if (!this._doNotChangeAspectRatio) {
  9418. scene.updateTransformMatrix(true);
  9419. }
  9420. };
  9421. RenderTargetTexture.prototype.clone = function () {
  9422. var textureSize = this.getSize();
  9423. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9424. newTexture.hasAlpha = this.hasAlpha;
  9425. newTexture.level = this.level;
  9426. newTexture.coordinatesMode = this.coordinatesMode;
  9427. newTexture.renderList = this.renderList.slice(0);
  9428. return newTexture;
  9429. };
  9430. return RenderTargetTexture;
  9431. })(BABYLON.Texture);
  9432. BABYLON.RenderTargetTexture = RenderTargetTexture;
  9433. })(BABYLON || (BABYLON = {}));
  9434. var __extends = this.__extends || function (d, b) {
  9435. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9436. function __() { this.constructor = d; }
  9437. __.prototype = b.prototype;
  9438. d.prototype = new __();
  9439. };
  9440. var BABYLON;
  9441. (function (BABYLON) {
  9442. var MirrorTexture = (function (_super) {
  9443. __extends(MirrorTexture, _super);
  9444. function MirrorTexture(name, size, scene, generateMipMaps) {
  9445. var _this = this;
  9446. _super.call(this, name, size, scene, generateMipMaps, true);
  9447. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  9448. this._transformMatrix = BABYLON.Matrix.Zero();
  9449. this._mirrorMatrix = BABYLON.Matrix.Zero();
  9450. this.onBeforeRender = function () {
  9451. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  9452. _this._savedViewMatrix = scene.getViewMatrix();
  9453. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  9454. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  9455. scene.clipPlane = _this.mirrorPlane;
  9456. scene.getEngine().cullBackFaces = false;
  9457. };
  9458. this.onAfterRender = function () {
  9459. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  9460. scene.getEngine().cullBackFaces = true;
  9461. delete scene.clipPlane;
  9462. };
  9463. }
  9464. MirrorTexture.prototype.clone = function () {
  9465. var textureSize = this.getSize();
  9466. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9467. newTexture.hasAlpha = this.hasAlpha;
  9468. newTexture.level = this.level;
  9469. newTexture.mirrorPlane = this.mirrorPlane.clone();
  9470. newTexture.renderList = this.renderList.slice(0);
  9471. return newTexture;
  9472. };
  9473. return MirrorTexture;
  9474. })(BABYLON.RenderTargetTexture);
  9475. BABYLON.MirrorTexture = MirrorTexture;
  9476. })(BABYLON || (BABYLON = {}));
  9477. var __extends = this.__extends || function (d, b) {
  9478. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9479. function __() { this.constructor = d; }
  9480. __.prototype = b.prototype;
  9481. d.prototype = new __();
  9482. };
  9483. var BABYLON;
  9484. (function (BABYLON) {
  9485. var DynamicTexture = (function (_super) {
  9486. __extends(DynamicTexture, _super);
  9487. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  9488. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9489. _super.call(this, null, scene, !generateMipMaps);
  9490. this.name = name;
  9491. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9492. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9493. this._generateMipMaps = generateMipMaps;
  9494. if (options.getContext) {
  9495. this._canvas = options;
  9496. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  9497. } else {
  9498. this._canvas = document.createElement("canvas");
  9499. if (options.width) {
  9500. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  9501. } else {
  9502. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  9503. }
  9504. }
  9505. var textureSize = this.getSize();
  9506. this._canvas.width = textureSize.width;
  9507. this._canvas.height = textureSize.height;
  9508. this._context = this._canvas.getContext("2d");
  9509. }
  9510. DynamicTexture.prototype.getContext = function () {
  9511. return this._context;
  9512. };
  9513. DynamicTexture.prototype.update = function (invertY) {
  9514. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  9515. };
  9516. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  9517. var size = this.getSize();
  9518. if (clearColor) {
  9519. this._context.fillStyle = clearColor;
  9520. this._context.fillRect(0, 0, size.width, size.height);
  9521. }
  9522. this._context.font = font;
  9523. if (x === null) {
  9524. var textSize = this._context.measureText(text);
  9525. x = (size.width - textSize.width) / 2;
  9526. }
  9527. this._context.fillStyle = color;
  9528. this._context.fillText(text, x, y);
  9529. this.update(invertY);
  9530. };
  9531. DynamicTexture.prototype.clone = function () {
  9532. var textureSize = this.getSize();
  9533. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9534. newTexture.hasAlpha = this.hasAlpha;
  9535. newTexture.level = this.level;
  9536. newTexture.wrapU = this.wrapU;
  9537. newTexture.wrapV = this.wrapV;
  9538. return newTexture;
  9539. };
  9540. return DynamicTexture;
  9541. })(BABYLON.Texture);
  9542. BABYLON.DynamicTexture = DynamicTexture;
  9543. })(BABYLON || (BABYLON = {}));
  9544. var __extends = this.__extends || function (d, b) {
  9545. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9546. function __() { this.constructor = d; }
  9547. __.prototype = b.prototype;
  9548. d.prototype = new __();
  9549. };
  9550. var BABYLON;
  9551. (function (BABYLON) {
  9552. var VideoTexture = (function (_super) {
  9553. __extends(VideoTexture, _super);
  9554. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  9555. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9556. var _this = this;
  9557. _super.call(this, null, scene, !generateMipMaps, invertY);
  9558. this._autoLaunch = true;
  9559. this.name = name;
  9560. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  9561. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  9562. var requiredWidth = size.width || size;
  9563. var requiredHeight = size.height || size;
  9564. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  9565. var textureSize = this.getSize();
  9566. this.video = document.createElement("video");
  9567. this.video.width = textureSize.width;
  9568. this.video.height = textureSize.height;
  9569. this.video.autoplay = false;
  9570. this.video.loop = true;
  9571. this.video.addEventListener("canplaythrough", function () {
  9572. if (_this._texture) {
  9573. _this._texture.isReady = true;
  9574. }
  9575. });
  9576. urls.forEach(function (url) {
  9577. var source = document.createElement("source");
  9578. source.src = url;
  9579. _this.video.appendChild(source);
  9580. });
  9581. this._lastUpdate = new Date().getTime();
  9582. }
  9583. VideoTexture.prototype.update = function () {
  9584. if (this._autoLaunch) {
  9585. this._autoLaunch = false;
  9586. this.video.play();
  9587. }
  9588. var now = new Date().getTime();
  9589. if (now - this._lastUpdate < 15) {
  9590. return false;
  9591. }
  9592. this._lastUpdate = now;
  9593. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  9594. return true;
  9595. };
  9596. return VideoTexture;
  9597. })(BABYLON.Texture);
  9598. BABYLON.VideoTexture = VideoTexture;
  9599. })(BABYLON || (BABYLON = {}));
  9600. var BABYLON;
  9601. (function (BABYLON) {
  9602. var EffectFallbacks = (function () {
  9603. function EffectFallbacks() {
  9604. this._defines = {};
  9605. this._currentRank = 32;
  9606. this._maxRank = -1;
  9607. }
  9608. EffectFallbacks.prototype.addFallback = function (rank, define) {
  9609. if (!this._defines[rank]) {
  9610. if (rank < this._currentRank) {
  9611. this._currentRank = rank;
  9612. }
  9613. if (rank > this._maxRank) {
  9614. this._maxRank = rank;
  9615. }
  9616. this._defines[rank] = new Array();
  9617. }
  9618. this._defines[rank].push(define);
  9619. };
  9620. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  9621. get: function () {
  9622. return this._currentRank <= this._maxRank;
  9623. },
  9624. enumerable: true,
  9625. configurable: true
  9626. });
  9627. EffectFallbacks.prototype.reduce = function (currentDefines) {
  9628. var currentFallbacks = this._defines[this._currentRank];
  9629. for (var index = 0; index < currentFallbacks.length; index++) {
  9630. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  9631. }
  9632. this._currentRank++;
  9633. return currentDefines;
  9634. };
  9635. return EffectFallbacks;
  9636. })();
  9637. BABYLON.EffectFallbacks = EffectFallbacks;
  9638. var Effect = (function () {
  9639. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  9640. var _this = this;
  9641. this._isReady = false;
  9642. this._compilationError = "";
  9643. this._valueCache = [];
  9644. this._engine = engine;
  9645. this.name = baseName;
  9646. this.defines = defines;
  9647. this._uniformsNames = uniformsNames.concat(samplers);
  9648. this._samplers = samplers;
  9649. this._attributesNames = attributesNames;
  9650. this.onError = onError;
  9651. this.onCompiled = onCompiled;
  9652. var vertexSource;
  9653. var fragmentSource;
  9654. if (baseName.vertexElement) {
  9655. vertexSource = document.getElementById(baseName.vertexElement);
  9656. if (!vertexSource) {
  9657. vertexSource = baseName.vertexElement;
  9658. }
  9659. } else {
  9660. vertexSource = baseName.vertex || baseName;
  9661. }
  9662. if (baseName.fragmentElement) {
  9663. fragmentSource = document.getElementById(baseName.fragmentElement);
  9664. if (!fragmentSource) {
  9665. fragmentSource = baseName.fragmentElement;
  9666. }
  9667. } else {
  9668. fragmentSource = baseName.fragment || baseName;
  9669. }
  9670. this._loadVertexShader(vertexSource, function (vertexCode) {
  9671. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  9672. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  9673. });
  9674. });
  9675. }
  9676. Effect.prototype.isReady = function () {
  9677. return this._isReady;
  9678. };
  9679. Effect.prototype.getProgram = function () {
  9680. return this._program;
  9681. };
  9682. Effect.prototype.getAttributesNames = function () {
  9683. return this._attributesNames;
  9684. };
  9685. Effect.prototype.getAttributeLocation = function (index) {
  9686. return this._attributes[index];
  9687. };
  9688. Effect.prototype.getAttributeLocationByName = function (name) {
  9689. var index = this._attributesNames.indexOf(name);
  9690. return this._attributes[index];
  9691. };
  9692. Effect.prototype.getAttributesCount = function () {
  9693. return this._attributes.length;
  9694. };
  9695. Effect.prototype.getUniformIndex = function (uniformName) {
  9696. return this._uniformsNames.indexOf(uniformName);
  9697. };
  9698. Effect.prototype.getUniform = function (uniformName) {
  9699. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  9700. };
  9701. Effect.prototype.getSamplers = function () {
  9702. return this._samplers;
  9703. };
  9704. Effect.prototype.getCompilationError = function () {
  9705. return this._compilationError;
  9706. };
  9707. Effect.prototype._loadVertexShader = function (vertex, callback) {
  9708. if (vertex instanceof HTMLElement) {
  9709. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  9710. callback(vertexCode);
  9711. return;
  9712. }
  9713. if (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
  9714. callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
  9715. return;
  9716. }
  9717. var vertexShaderUrl;
  9718. if (vertex[0] === ".") {
  9719. vertexShaderUrl = vertex;
  9720. } else {
  9721. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  9722. }
  9723. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  9724. };
  9725. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  9726. if (fragment instanceof HTMLElement) {
  9727. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  9728. callback(fragmentCode);
  9729. return;
  9730. }
  9731. if (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
  9732. callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
  9733. return;
  9734. }
  9735. if (BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]) {
  9736. callback(BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]);
  9737. return;
  9738. }
  9739. var fragmentShaderUrl;
  9740. if (fragment[0] === ".") {
  9741. fragmentShaderUrl = fragment;
  9742. } else {
  9743. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  9744. }
  9745. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  9746. };
  9747. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  9748. try {
  9749. var engine = this._engine;
  9750. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  9751. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  9752. this._attributes = engine.getAttributes(this._program, attributesNames);
  9753. for (var index = 0; index < this._samplers.length; index++) {
  9754. var sampler = this.getUniform(this._samplers[index]);
  9755. if (sampler == null) {
  9756. this._samplers.splice(index, 1);
  9757. index--;
  9758. }
  9759. }
  9760. engine.bindSamplers(this);
  9761. this._isReady = true;
  9762. if (this.onCompiled) {
  9763. this.onCompiled(this);
  9764. }
  9765. } catch (e) {
  9766. if (fallbacks && fallbacks.isMoreFallbacks) {
  9767. defines = fallbacks.reduce(defines);
  9768. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  9769. } else {
  9770. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  9771. BABYLON.Tools.Error("Defines: " + defines);
  9772. BABYLON.Tools.Error("Error: " + e.message);
  9773. this._compilationError = e.message;
  9774. if (this.onError) {
  9775. this.onError(this, this._compilationError);
  9776. }
  9777. }
  9778. }
  9779. };
  9780. Effect.prototype._bindTexture = function (channel, texture) {
  9781. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  9782. };
  9783. Effect.prototype.setTexture = function (channel, texture) {
  9784. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  9785. };
  9786. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  9787. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  9788. };
  9789. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  9790. if (!this._valueCache[uniformName]) {
  9791. this._valueCache[uniformName] = [x, y];
  9792. return;
  9793. }
  9794. this._valueCache[uniformName][0] = x;
  9795. this._valueCache[uniformName][1] = y;
  9796. };
  9797. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  9798. if (!this._valueCache[uniformName]) {
  9799. this._valueCache[uniformName] = [x, y, z];
  9800. return;
  9801. }
  9802. this._valueCache[uniformName][0] = x;
  9803. this._valueCache[uniformName][1] = y;
  9804. this._valueCache[uniformName][2] = z;
  9805. };
  9806. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  9807. if (!this._valueCache[uniformName]) {
  9808. this._valueCache[uniformName] = [x, y, z, w];
  9809. return;
  9810. }
  9811. this._valueCache[uniformName][0] = x;
  9812. this._valueCache[uniformName][1] = y;
  9813. this._valueCache[uniformName][2] = z;
  9814. this._valueCache[uniformName][3] = w;
  9815. };
  9816. Effect.prototype.setArray = function (uniformName, array) {
  9817. this._engine.setArray(this.getUniform(uniformName), array);
  9818. return this;
  9819. };
  9820. Effect.prototype.setMatrices = function (uniformName, matrices) {
  9821. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  9822. return this;
  9823. };
  9824. Effect.prototype.setMatrix = function (uniformName, matrix) {
  9825. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  9826. return this;
  9827. };
  9828. Effect.prototype.setFloat = function (uniformName, value) {
  9829. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  9830. return this;
  9831. this._valueCache[uniformName] = value;
  9832. this._engine.setFloat(this.getUniform(uniformName), value);
  9833. return this;
  9834. };
  9835. Effect.prototype.setBool = function (uniformName, bool) {
  9836. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  9837. return this;
  9838. this._valueCache[uniformName] = bool;
  9839. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  9840. return this;
  9841. };
  9842. Effect.prototype.setVector2 = function (uniformName, vector2) {
  9843. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector2.x && this._valueCache[uniformName][1] == vector2.y)
  9844. return this;
  9845. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  9846. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  9847. return this;
  9848. };
  9849. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  9850. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y)
  9851. return this;
  9852. this._cacheFloat2(uniformName, x, y);
  9853. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  9854. return this;
  9855. };
  9856. Effect.prototype.setVector3 = function (uniformName, vector3) {
  9857. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector3.x && this._valueCache[uniformName][1] == vector3.y && this._valueCache[uniformName][2] == vector3.z)
  9858. return this;
  9859. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  9860. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  9861. return this;
  9862. };
  9863. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  9864. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z)
  9865. return this;
  9866. this._cacheFloat3(uniformName, x, y, z);
  9867. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  9868. return this;
  9869. };
  9870. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  9871. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z && this._valueCache[uniformName][3] == w)
  9872. return this;
  9873. this._cacheFloat4(uniformName, x, y, z, w);
  9874. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  9875. return this;
  9876. };
  9877. Effect.prototype.setColor3 = function (uniformName, color3) {
  9878. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b)
  9879. return this;
  9880. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  9881. this._engine.setColor3(this.getUniform(uniformName), color3);
  9882. return this;
  9883. };
  9884. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  9885. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b && this._valueCache[uniformName][3] == alpha)
  9886. return this;
  9887. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  9888. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  9889. return this;
  9890. };
  9891. Effect.ShadersStore={anaglyphPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\n\nvoid main(void)\n{\n vec4 leftFrag = texture2D(leftSampler, vUV);\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\n\n vec4 rightFrag = texture2D(textureSampler, vUV);\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\n\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\n}",
  9892. blackAndWhitePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void) \n{\n float luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\n gl_FragColor = vec4(luminance, luminance, luminance, 1.0);\n}",
  9893. blurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Parameters\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nvoid main(void)\n{\n float weights[7];\n weights[0] = 0.05;\n weights[1] = 0.1;\n weights[2] = 0.2;\n weights[3] = 0.3;\n weights[4] = 0.2;\n weights[5] = 0.1;\n weights[6] = 0.05;\n\n vec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\n vec2 texelStep = texelSize * direction * blurWidth;\n vec2 start = vUV - 3.0 * texelStep;\n\n vec4 baseColor = vec4(0., 0., 0., 0.);\n vec2 texelOffset = vec2(0., 0.);\n\n for (int i = 0; i < 7; i++)\n {\n baseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\n texelOffset += texelStep;\n }\n\n gl_FragColor = baseColor;\n}",
  9894. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  9895. colorVertexShader:"precision highp float;\n\n// Attributes\nattribute vec3 position;\n\n// Uniforms\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\n gl_Position = worldViewProjection * vec4(position, 1.0);\n}",
  9896. convolutionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform float kernel[9];\n\nvoid main(void)\n{\n vec2 onePixel = vec2(1.0, 1.0) / screenSize;\n vec4 colorSum =\n texture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\n texture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\n texture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\n\n float kernelWeight =\n kernel[0] +\n kernel[1] +\n kernel[2] +\n kernel[3] +\n kernel[4] +\n kernel[5] +\n kernel[6] +\n kernel[7] +\n kernel[8];\n\n if (kernelWeight <= 0.0) {\n kernelWeight = 1.0;\n }\n\n gl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\n}",
  9897. defaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform float darkness0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform float darkness1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform float darkness2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform float darkness3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n for (int i = 0; i<4; i++){\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[i] / 1500.0)) < depth.z){\n visibility -= 0.2;\n }\n }\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz * vBumpInfos.y;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\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\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n diffuseColor *= vColor;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, darkness0);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, darkness1);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, darkness2);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, darkness3);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  9898. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\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 vec3 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef REFLECTION\n vPositionUVW = position;\n#endif \n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n#ifdef INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n finalWorld = world;\n#endif\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}",
  9899. displayPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(passSampler, vUV);\n}",
  9900. filterPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform mat4 kernelMatrix;\n\nvoid main(void)\n{\n vec3 baseColor = texture2D(textureSampler, vUV).rgb;\n vec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\n\n gl_FragColor = vec4(updatedColor, 1.0);\n}",
  9901. fxaaPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\n\nvoid main(){\n vec2 localTexelSize = texelSize;\n vec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\n vec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\n vec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\n vec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\n vec4 rgbM = texture2D(textureSampler, vUV);\n vec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\n vec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\n\n float dirReduce = max(\n (lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\n FXAA_REDUCE_MIN);\n\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * localTexelSize;\n\n vec4 rgbA = 0.5 * (\n texture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\n texture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\n\n vec4 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(textureSampler, vUV + dir * -0.5) +\n texture2D(textureSampler, vUV + dir * 0.5));\n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax)) {\n gl_FragColor = rgbA;\n }\n else {\n gl_FragColor = rgbB;\n }\n}",
  9902. layerPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Color\nuniform vec4 color;\n\nvoid main(void) {\n vec4 baseColor = texture2D(textureSampler, vUV);\n\n gl_FragColor = baseColor * color;\n}",
  9903. layerVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Uniforms\nuniform mat4 textureMatrix;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  9904. legacydefaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_PROJECTION 4.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return 0.;\n }\n return 1.;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\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\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW;\n if (lightData.w == 0.)\n {\n lightVectorW = normalize(lightData.xyz - vPositionW);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\n result[0] = ndl * diffuseColor.rgb;\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = ndl * spotAtten * diffuseColor.rgb;\n result[1] = specComp * specularColor * spotAtten;\n result[2] = vec3(0.);\n\n return result;\n }\n\n result[0] = vec3(0.);\n result[1] = vec3(0.);\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\n mat3 result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = mix(groundColor, diffuseColor.rgb, ndl);\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\n diffuseColor *= vColor;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n mat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\n mat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n mat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  9905. legacydefaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Attributes\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 vec3 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return position;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n finalWorld = world;\n#endif\n\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef REFLECTION\n vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}",
  9906. lensFlarePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Color\nuniform vec4 color;\n\nvoid main(void) {\n vec4 baseColor = texture2D(textureSampler, vUV);\n\n gl_FragColor = baseColor * color;\n}",
  9907. lensFlareVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Uniforms\nuniform mat4 viewportMatrix;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = position * madd + madd;\n gl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\n}",
  9908. oculusDistortionCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\n\nvec2 HmdWarp(vec2 in01) {\n\n vec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\n float rSq = theta.x * theta.x + theta.y * theta.y;\n vec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\n return LensCenter + Scale * rvector;\n}\n\n\n\nvoid main(void)\n{\n vec2 tc = HmdWarp(vUV);\n if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n else{\n gl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\n }\n}",
  9909. outlinePixelShader:"precision highp float;\n\nuniform vec3 color;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void) {\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n gl_FragColor = vec4(color, 1.);\n}",
  9910. outlineVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\nattribute vec3 normal;\n\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\nuniform float offset;\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\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\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n vec3 offsetPosition = position + normal * offset;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#else\n gl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  9911. particlesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\nvoid main(void) {\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n vec4 baseColor = texture2D(diffuseSampler, vUV);\n\n gl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\n}",
  9912. particlesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\n// Uniforms\nuniform mat4 view;\nuniform mat4 projection;\n\n// Output\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n\nvoid main(void) { \n vec3 viewPos = (view * vec4(position, 1.0)).xyz; \n vec3 cornerPos;\n float size = options.y;\n float angle = options.x;\n vec2 offset = options.zw;\n\n cornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\n // Rotate\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n\n // Position\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n \n vColor = color;\n vUV = offset;\n\n // Clip plane\n#ifdef CLIPPLANE\n vec4 worldPos = invView * vec4(viewPos, 1.0);\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n}",
  9913. passPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void) \n{\n gl_FragColor = texture2D(textureSampler, vUV);\n}",
  9914. postprocessVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = position * madd + madd;\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  9915. refractionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\n// Parameters\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\n\nvoid main() {\n float ref = 1.0 - texture2D(refractionSampler, vUV).r;\n\n vec2 uv = vUV - vec2(0.5);\n vec2 offset = uv * depth * ref;\n vec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\n\n gl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\n}",
  9916. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\n const vec4 bitOffset = vec4(255. * 255. * 255., 255. * 255., 255., 1.);\n const vec4 bitMask = vec4(0., 1. / 255., 1. / 255., 1. / 255.);\n \n vec4 comp = mod(depth * bitOffset * vec4(254.), vec4(255.)) / vec4(254.);\n comp -= comp.xxyz * bitMask;\n \n return comp;\n}\n\n// Thanks to http://devmaster.net/\nvec2 packHalf(float depth) \n{ \n const vec2 bitOffset = vec2(1.0 / 255., 0.);\n vec2 color = vec2(depth, fract(depth * 255.));\n\n return color - (color.yy * bitOffset);\n}\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n#ifdef VSM\n float moment1 = gl_FragCoord.z / gl_FragCoord.w;\n float moment2 = moment1 * moment1;\n gl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\n gl_FragColor = pack(vPosition.z / vPosition.w);\n#endif\n}",
  9917. shadowMapVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\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\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n#ifndef VSM\n vPosition = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  9918. spritesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform bool alphaTest;\n\nvarying vec4 vColor;\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n// Fog\n#ifdef FOG\n\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\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return min(1., max(0., fogCoeff));\n}\n#endif\n\n\nvoid main(void) {\n vec4 baseColor = texture2D(diffuseSampler, vUV);\n\n if (alphaTest) \n {\n if (baseColor.a < 0.95)\n discard;\n }\n\n baseColor *= vColor;\n\n#ifdef FOG\n float fog = CalcFogFactor();\n baseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = baseColor;\n}",
  9919. spritesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\n// Uniforms\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\n// Output\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\nvoid main(void) { \n vec3 viewPos = (view * vec4(position, 1.0)).xyz; \n vec3 cornerPos;\n \n float angle = options.x;\n float size = options.y;\n vec2 offset = options.zw;\n vec2 uvScale = textureInfos.xy;\n\n cornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\n // Rotate\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n\n // Position\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n\n // Color\n vColor = color;\n \n // Texture\n vec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\n\n vUV = (uvOffset + cellInfo.zw) * uvScale;\n\n // Fog\n#ifdef FOG\n fFogDistance = viewPos.z;\n#endif\n}",
  9920. };
  9921. return Effect;
  9922. })();
  9923. BABYLON.Effect = Effect;
  9924. })(BABYLON || (BABYLON = {}));
  9925. var BABYLON;
  9926. (function (BABYLON) {
  9927. var Material = (function () {
  9928. function Material(name, scene, doNotAdd) {
  9929. this.name = name;
  9930. this.checkReadyOnEveryCall = true;
  9931. this.checkReadyOnlyOnce = false;
  9932. this.state = "";
  9933. this.alpha = 1.0;
  9934. this.wireframe = false;
  9935. this.backFaceCulling = true;
  9936. this._wasPreviouslyReady = false;
  9937. this.id = name;
  9938. this._scene = scene;
  9939. if (!doNotAdd) {
  9940. scene.materials.push(this);
  9941. }
  9942. }
  9943. Material.prototype.isReady = function (mesh, useInstances) {
  9944. return true;
  9945. };
  9946. Material.prototype.getEffect = function () {
  9947. return this._effect;
  9948. };
  9949. Material.prototype.getScene = function () {
  9950. return this._scene;
  9951. };
  9952. Material.prototype.needAlphaBlending = function () {
  9953. return (this.alpha < 1.0);
  9954. };
  9955. Material.prototype.needAlphaTesting = function () {
  9956. return false;
  9957. };
  9958. Material.prototype.getAlphaTestTexture = function () {
  9959. return null;
  9960. };
  9961. Material.prototype.trackCreation = function (onCompiled, onError) {
  9962. };
  9963. Material.prototype._preBind = function () {
  9964. var engine = this._scene.getEngine();
  9965. engine.enableEffect(this._effect);
  9966. engine.setState(this.backFaceCulling);
  9967. };
  9968. Material.prototype.bind = function (world, mesh) {
  9969. };
  9970. Material.prototype.bindOnlyWorldMatrix = function (world) {
  9971. };
  9972. Material.prototype.unbind = function () {
  9973. };
  9974. Material.prototype.dispose = function (forceDisposeEffect) {
  9975. var index = this._scene.materials.indexOf(this);
  9976. this._scene.materials.splice(index, 1);
  9977. if (forceDisposeEffect && this._effect) {
  9978. this._scene.getEngine()._releaseEffect(this._effect);
  9979. this._effect = null;
  9980. }
  9981. if (this.onDispose) {
  9982. this.onDispose();
  9983. }
  9984. };
  9985. return Material;
  9986. })();
  9987. BABYLON.Material = Material;
  9988. })(BABYLON || (BABYLON = {}));
  9989. var __extends = this.__extends || function (d, b) {
  9990. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9991. function __() { this.constructor = d; }
  9992. __.prototype = b.prototype;
  9993. d.prototype = new __();
  9994. };
  9995. var BABYLON;
  9996. (function (BABYLON) {
  9997. var maxSimultaneousLights = 4;
  9998. var FresnelParameters = (function () {
  9999. function FresnelParameters() {
  10000. this.isEnabled = true;
  10001. this.leftColor = BABYLON.Color3.White();
  10002. this.rightColor = BABYLON.Color3.Black();
  10003. this.bias = 0;
  10004. this.power = 1;
  10005. }
  10006. return FresnelParameters;
  10007. })();
  10008. BABYLON.FresnelParameters = FresnelParameters;
  10009. var StandardMaterial = (function (_super) {
  10010. __extends(StandardMaterial, _super);
  10011. function StandardMaterial(name, scene) {
  10012. var _this = this;
  10013. _super.call(this, name, scene);
  10014. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  10015. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  10016. this.specularColor = new BABYLON.Color3(1, 1, 1);
  10017. this.specularPower = 64;
  10018. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  10019. this.useAlphaFromDiffuseTexture = false;
  10020. this.useSpecularOverAlpha = true;
  10021. this._cachedDefines = null;
  10022. this._renderTargets = new BABYLON.SmartArray(16);
  10023. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  10024. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  10025. this._scaledDiffuse = new BABYLON.Color3();
  10026. this._scaledSpecular = new BABYLON.Color3();
  10027. this.getRenderTargetTextures = function () {
  10028. _this._renderTargets.reset();
  10029. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  10030. _this._renderTargets.push(_this.reflectionTexture);
  10031. }
  10032. return _this._renderTargets;
  10033. };
  10034. }
  10035. StandardMaterial.prototype.needAlphaBlending = function () {
  10036. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  10037. };
  10038. StandardMaterial.prototype.needAlphaTesting = function () {
  10039. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  10040. };
  10041. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  10042. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  10043. };
  10044. StandardMaterial.prototype.getAlphaTestTexture = function () {
  10045. return this.diffuseTexture;
  10046. };
  10047. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  10048. if (this.checkReadyOnlyOnce) {
  10049. if (this._wasPreviouslyReady) {
  10050. return true;
  10051. }
  10052. }
  10053. var scene = this.getScene();
  10054. if (!this.checkReadyOnEveryCall) {
  10055. if (this._renderId === scene.getRenderId()) {
  10056. return true;
  10057. }
  10058. }
  10059. var engine = scene.getEngine();
  10060. var defines = [];
  10061. var fallbacks = new BABYLON.EffectFallbacks();
  10062. if (scene.texturesEnabled) {
  10063. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  10064. if (!this.diffuseTexture.isReady()) {
  10065. return false;
  10066. } else {
  10067. defines.push("#define DIFFUSE");
  10068. }
  10069. }
  10070. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  10071. if (!this.ambientTexture.isReady()) {
  10072. return false;
  10073. } else {
  10074. defines.push("#define AMBIENT");
  10075. }
  10076. }
  10077. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  10078. if (!this.opacityTexture.isReady()) {
  10079. return false;
  10080. } else {
  10081. defines.push("#define OPACITY");
  10082. if (this.opacityTexture.getAlphaFromRGB) {
  10083. defines.push("#define OPACITYRGB");
  10084. }
  10085. }
  10086. }
  10087. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  10088. if (!this.reflectionTexture.isReady()) {
  10089. return false;
  10090. } else {
  10091. defines.push("#define REFLECTION");
  10092. fallbacks.addFallback(0, "REFLECTION");
  10093. }
  10094. }
  10095. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10096. if (!this.emissiveTexture.isReady()) {
  10097. return false;
  10098. } else {
  10099. defines.push("#define EMISSIVE");
  10100. }
  10101. }
  10102. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10103. if (!this.specularTexture.isReady()) {
  10104. return false;
  10105. } else {
  10106. defines.push("#define SPECULAR");
  10107. fallbacks.addFallback(0, "SPECULAR");
  10108. }
  10109. }
  10110. }
  10111. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10112. if (!this.bumpTexture.isReady()) {
  10113. return false;
  10114. } else {
  10115. defines.push("#define BUMP");
  10116. fallbacks.addFallback(0, "BUMP");
  10117. }
  10118. }
  10119. if (this.useSpecularOverAlpha) {
  10120. defines.push("#define SPECULAROVERALPHA");
  10121. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  10122. }
  10123. if (scene.clipPlane) {
  10124. defines.push("#define CLIPPLANE");
  10125. }
  10126. if (engine.getAlphaTesting()) {
  10127. defines.push("#define ALPHATEST");
  10128. }
  10129. if (this._shouldUseAlphaFromDiffuseTexture()) {
  10130. defines.push("#define ALPHAFROMDIFFUSE");
  10131. }
  10132. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10133. defines.push("#define FOG");
  10134. fallbacks.addFallback(1, "FOG");
  10135. }
  10136. var shadowsActivated = false;
  10137. var lightIndex = 0;
  10138. if (scene.lightsEnabled) {
  10139. for (var index = 0; index < scene.lights.length; index++) {
  10140. var light = scene.lights[index];
  10141. if (!light.isEnabled()) {
  10142. continue;
  10143. }
  10144. if (light._excludedMeshesIds.length > 0) {
  10145. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  10146. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  10147. if (excludedMesh) {
  10148. light.excludedMeshes.push(excludedMesh);
  10149. }
  10150. }
  10151. light._excludedMeshesIds = [];
  10152. }
  10153. if (light._includedOnlyMeshesIds.length > 0) {
  10154. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  10155. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  10156. if (includedOnlyMesh) {
  10157. light.includedOnlyMeshes.push(includedOnlyMesh);
  10158. }
  10159. }
  10160. light._includedOnlyMeshesIds = [];
  10161. }
  10162. if (!light.canAffectMesh(mesh)) {
  10163. continue;
  10164. }
  10165. defines.push("#define LIGHT" + lightIndex);
  10166. if (lightIndex > 0) {
  10167. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  10168. }
  10169. var type;
  10170. if (light instanceof BABYLON.SpotLight) {
  10171. type = "#define SPOTLIGHT" + lightIndex;
  10172. } else if (light instanceof BABYLON.HemisphericLight) {
  10173. type = "#define HEMILIGHT" + lightIndex;
  10174. } else {
  10175. type = "#define POINTDIRLIGHT" + lightIndex;
  10176. }
  10177. defines.push(type);
  10178. if (lightIndex > 0) {
  10179. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  10180. }
  10181. var shadowGenerator = light.getShadowGenerator();
  10182. if (mesh && mesh.receiveShadows && shadowGenerator) {
  10183. defines.push("#define SHADOW" + lightIndex);
  10184. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  10185. if (!shadowsActivated) {
  10186. defines.push("#define SHADOWS");
  10187. shadowsActivated = true;
  10188. }
  10189. if (shadowGenerator.useVarianceShadowMap) {
  10190. defines.push("#define SHADOWVSM" + lightIndex);
  10191. if (lightIndex > 0) {
  10192. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  10193. }
  10194. }
  10195. if (shadowGenerator.usePoissonSampling) {
  10196. defines.push("#define SHADOWPCF" + lightIndex);
  10197. if (lightIndex > 0) {
  10198. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  10199. }
  10200. }
  10201. }
  10202. lightIndex++;
  10203. if (lightIndex == maxSimultaneousLights)
  10204. break;
  10205. }
  10206. }
  10207. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10208. var fresnelRank = 1;
  10209. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10210. defines.push("#define DIFFUSEFRESNEL");
  10211. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  10212. fresnelRank++;
  10213. }
  10214. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10215. defines.push("#define OPACITYFRESNEL");
  10216. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  10217. fresnelRank++;
  10218. }
  10219. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10220. defines.push("#define REFLECTIONFRESNEL");
  10221. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  10222. fresnelRank++;
  10223. }
  10224. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10225. defines.push("#define EMISSIVEFRESNEL");
  10226. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  10227. fresnelRank++;
  10228. }
  10229. defines.push("#define FRESNEL");
  10230. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  10231. }
  10232. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  10233. if (mesh) {
  10234. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10235. attribs.push(BABYLON.VertexBuffer.UVKind);
  10236. defines.push("#define UV1");
  10237. }
  10238. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10239. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10240. defines.push("#define UV2");
  10241. }
  10242. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  10243. attribs.push(BABYLON.VertexBuffer.ColorKind);
  10244. defines.push("#define VERTEXCOLOR");
  10245. }
  10246. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10247. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10248. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10249. defines.push("#define BONES");
  10250. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10251. defines.push("#define BONES4");
  10252. fallbacks.addFallback(0, "BONES4");
  10253. }
  10254. if (useInstances) {
  10255. defines.push("#define INSTANCES");
  10256. attribs.push("world0");
  10257. attribs.push("world1");
  10258. attribs.push("world2");
  10259. attribs.push("world3");
  10260. }
  10261. }
  10262. var join = defines.join("\n");
  10263. if (this._cachedDefines != join) {
  10264. this._cachedDefines = join;
  10265. var shaderName = "default";
  10266. if (!scene.getEngine().getCaps().standardDerivatives) {
  10267. shaderName = "legacydefault";
  10268. }
  10269. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  10270. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  10271. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  10272. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  10273. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  10274. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  10275. "vFogInfos", "vFogColor",
  10276. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  10277. "mBones",
  10278. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  10279. "darkness0", "darkness1", "darkness2", "darkness3",
  10280. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  10281. ], [
  10282. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  10283. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  10284. ], join, fallbacks, this.onCompiled, this.onError);
  10285. }
  10286. if (!this._effect.isReady()) {
  10287. return false;
  10288. }
  10289. this._renderId = scene.getRenderId();
  10290. this._wasPreviouslyReady = true;
  10291. return true;
  10292. };
  10293. StandardMaterial.prototype.unbind = function () {
  10294. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  10295. this._effect.setTexture("reflection2DSampler", null);
  10296. }
  10297. };
  10298. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  10299. this._effect.setMatrix("world", world);
  10300. };
  10301. StandardMaterial.prototype.bind = function (world, mesh) {
  10302. var scene = this.getScene();
  10303. this.bindOnlyWorldMatrix(world);
  10304. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  10305. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10306. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  10307. }
  10308. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10309. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  10310. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  10311. }
  10312. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10313. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  10314. }
  10315. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10316. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  10317. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  10318. }
  10319. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10320. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  10321. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  10322. }
  10323. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  10324. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  10325. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  10326. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  10327. }
  10328. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  10329. this._effect.setTexture("ambientSampler", this.ambientTexture);
  10330. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  10331. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  10332. }
  10333. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  10334. this._effect.setTexture("opacitySampler", this.opacityTexture);
  10335. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  10336. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  10337. }
  10338. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  10339. if (this.reflectionTexture.isCube) {
  10340. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  10341. } else {
  10342. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  10343. }
  10344. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  10345. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  10346. }
  10347. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10348. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  10349. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  10350. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  10351. }
  10352. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10353. this._effect.setTexture("specularSampler", this.specularTexture);
  10354. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  10355. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  10356. }
  10357. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10358. this._effect.setTexture("bumpSampler", this.bumpTexture);
  10359. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
  10360. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  10361. }
  10362. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  10363. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  10364. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  10365. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  10366. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  10367. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  10368. if (scene.lightsEnabled) {
  10369. var lightIndex = 0;
  10370. for (var index = 0; index < scene.lights.length; index++) {
  10371. var light = scene.lights[index];
  10372. if (!light.isEnabled()) {
  10373. continue;
  10374. }
  10375. if (!light.canAffectMesh(mesh)) {
  10376. continue;
  10377. }
  10378. if (light instanceof BABYLON.PointLight) {
  10379. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10380. } else if (light instanceof BABYLON.DirectionalLight) {
  10381. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10382. } else if (light instanceof BABYLON.SpotLight) {
  10383. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  10384. } else if (light instanceof BABYLON.HemisphericLight) {
  10385. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  10386. }
  10387. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  10388. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  10389. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  10390. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  10391. var shadowGenerator = light.getShadowGenerator();
  10392. if (mesh.receiveShadows && shadowGenerator) {
  10393. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  10394. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  10395. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  10396. }
  10397. lightIndex++;
  10398. if (lightIndex == maxSimultaneousLights)
  10399. break;
  10400. }
  10401. }
  10402. if (scene.clipPlane) {
  10403. var clipPlane = scene.clipPlane;
  10404. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  10405. }
  10406. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  10407. this._effect.setMatrix("view", scene.getViewMatrix());
  10408. }
  10409. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10410. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  10411. this._effect.setColor3("vFogColor", scene.fogColor);
  10412. }
  10413. };
  10414. StandardMaterial.prototype.getAnimatables = function () {
  10415. var results = [];
  10416. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  10417. results.push(this.diffuseTexture);
  10418. }
  10419. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  10420. results.push(this.ambientTexture);
  10421. }
  10422. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  10423. results.push(this.opacityTexture);
  10424. }
  10425. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  10426. results.push(this.reflectionTexture);
  10427. }
  10428. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  10429. results.push(this.emissiveTexture);
  10430. }
  10431. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  10432. results.push(this.specularTexture);
  10433. }
  10434. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  10435. results.push(this.bumpTexture);
  10436. }
  10437. return results;
  10438. };
  10439. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  10440. if (this.diffuseTexture) {
  10441. this.diffuseTexture.dispose();
  10442. }
  10443. if (this.ambientTexture) {
  10444. this.ambientTexture.dispose();
  10445. }
  10446. if (this.opacityTexture) {
  10447. this.opacityTexture.dispose();
  10448. }
  10449. if (this.reflectionTexture) {
  10450. this.reflectionTexture.dispose();
  10451. }
  10452. if (this.emissiveTexture) {
  10453. this.emissiveTexture.dispose();
  10454. }
  10455. if (this.specularTexture) {
  10456. this.specularTexture.dispose();
  10457. }
  10458. if (this.bumpTexture) {
  10459. this.bumpTexture.dispose();
  10460. }
  10461. _super.prototype.dispose.call(this, forceDisposeEffect);
  10462. };
  10463. StandardMaterial.prototype.clone = function (name) {
  10464. var newStandardMaterial = new BABYLON.StandardMaterial(name, this.getScene());
  10465. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  10466. newStandardMaterial.alpha = this.alpha;
  10467. newStandardMaterial.wireframe = this.wireframe;
  10468. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  10469. if (this.diffuseTexture && this.diffuseTexture.clone) {
  10470. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  10471. }
  10472. if (this.ambientTexture && this.ambientTexture.clone) {
  10473. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  10474. }
  10475. if (this.opacityTexture && this.opacityTexture.clone) {
  10476. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  10477. }
  10478. if (this.reflectionTexture && this.reflectionTexture.clone) {
  10479. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  10480. }
  10481. if (this.emissiveTexture && this.emissiveTexture.clone) {
  10482. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  10483. }
  10484. if (this.specularTexture && this.specularTexture.clone) {
  10485. newStandardMaterial.specularTexture = this.specularTexture.clone();
  10486. }
  10487. if (this.bumpTexture && this.bumpTexture.clone) {
  10488. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  10489. }
  10490. newStandardMaterial.ambientColor = this.ambientColor.clone();
  10491. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  10492. newStandardMaterial.specularColor = this.specularColor.clone();
  10493. newStandardMaterial.specularPower = this.specularPower;
  10494. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  10495. return newStandardMaterial;
  10496. };
  10497. StandardMaterial.DiffuseTextureEnabled = true;
  10498. StandardMaterial.AmbientTextureEnabled = true;
  10499. StandardMaterial.OpacityTextureEnabled = true;
  10500. StandardMaterial.ReflectionTextureEnabled = true;
  10501. StandardMaterial.EmissiveTextureEnabled = true;
  10502. StandardMaterial.SpecularTextureEnabled = true;
  10503. StandardMaterial.BumpTextureEnabled = true;
  10504. return StandardMaterial;
  10505. })(BABYLON.Material);
  10506. BABYLON.StandardMaterial = StandardMaterial;
  10507. })(BABYLON || (BABYLON = {}));
  10508. var __extends = this.__extends || function (d, b) {
  10509. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10510. function __() { this.constructor = d; }
  10511. __.prototype = b.prototype;
  10512. d.prototype = new __();
  10513. };
  10514. var BABYLON;
  10515. (function (BABYLON) {
  10516. var MultiMaterial = (function (_super) {
  10517. __extends(MultiMaterial, _super);
  10518. function MultiMaterial(name, scene) {
  10519. _super.call(this, name, scene, true);
  10520. this.subMaterials = new Array();
  10521. scene.multiMaterials.push(this);
  10522. }
  10523. MultiMaterial.prototype.getSubMaterial = function (index) {
  10524. if (index < 0 || index >= this.subMaterials.length) {
  10525. return this.getScene().defaultMaterial;
  10526. }
  10527. return this.subMaterials[index];
  10528. };
  10529. MultiMaterial.prototype.isReady = function (mesh) {
  10530. for (var index = 0; index < this.subMaterials.length; index++) {
  10531. var subMaterial = this.subMaterials[index];
  10532. if (subMaterial) {
  10533. if (!this.subMaterials[index].isReady(mesh)) {
  10534. return false;
  10535. }
  10536. }
  10537. }
  10538. return true;
  10539. };
  10540. return MultiMaterial;
  10541. })(BABYLON.Material);
  10542. BABYLON.MultiMaterial = MultiMaterial;
  10543. })(BABYLON || (BABYLON = {}));
  10544. var BABYLON;
  10545. (function (BABYLON) {
  10546. var Database = (function () {
  10547. function Database(urlToScene, callbackManifestChecked) {
  10548. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  10549. this.callbackManifestChecked = callbackManifestChecked;
  10550. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  10551. this.db = null;
  10552. this.enableSceneOffline = false;
  10553. this.enableTexturesOffline = false;
  10554. this.manifestVersionFound = 0;
  10555. this.mustUpdateRessources = false;
  10556. this.hasReachedQuota = false;
  10557. this.checkManifestFile();
  10558. }
  10559. Database.prototype.checkManifestFile = function () {
  10560. var _this = this;
  10561. function noManifestFile() {
  10562. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  10563. that.enableSceneOffline = false;
  10564. that.enableTexturesOffline = false;
  10565. that.callbackManifestChecked(false);
  10566. }
  10567. var that = this;
  10568. var manifestURL = this.currentSceneUrl + ".manifest";
  10569. var xhr = new XMLHttpRequest();
  10570. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  10571. xhr.open("GET", manifestURLTimeStamped, true);
  10572. xhr.addEventListener("load", function () {
  10573. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  10574. try {
  10575. var manifestFile = JSON.parse(xhr.response);
  10576. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  10577. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  10578. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  10579. _this.manifestVersionFound = manifestFile.version;
  10580. }
  10581. if (_this.callbackManifestChecked) {
  10582. _this.callbackManifestChecked(true);
  10583. }
  10584. } catch (ex) {
  10585. noManifestFile();
  10586. }
  10587. } else {
  10588. noManifestFile();
  10589. }
  10590. }, false);
  10591. xhr.addEventListener("error", function (event) {
  10592. noManifestFile();
  10593. }, false);
  10594. try {
  10595. xhr.send();
  10596. } catch (ex) {
  10597. BABYLON.Tools.Error("Error on XHR send request.");
  10598. that.callbackManifestChecked(false);
  10599. }
  10600. };
  10601. Database.prototype.openAsync = function (successCallback, errorCallback) {
  10602. var _this = this;
  10603. function handleError() {
  10604. that.isSupported = false;
  10605. if (errorCallback)
  10606. errorCallback();
  10607. }
  10608. var that = this;
  10609. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  10610. this.isSupported = false;
  10611. if (errorCallback)
  10612. errorCallback();
  10613. } else {
  10614. if (!this.db) {
  10615. this.hasReachedQuota = false;
  10616. this.isSupported = true;
  10617. var request = this.idbFactory.open("babylonjs", 1);
  10618. request.onerror = function (event) {
  10619. handleError();
  10620. };
  10621. request.onblocked = function (event) {
  10622. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  10623. handleError();
  10624. };
  10625. request.onsuccess = function (event) {
  10626. _this.db = request.result;
  10627. successCallback();
  10628. };
  10629. request.onupgradeneeded = function (event) {
  10630. _this.db = (event.target).result;
  10631. try {
  10632. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  10633. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  10634. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  10635. } catch (ex) {
  10636. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  10637. handleError();
  10638. }
  10639. };
  10640. } else {
  10641. if (successCallback)
  10642. successCallback();
  10643. }
  10644. }
  10645. };
  10646. Database.prototype.loadImageFromDB = function (url, image) {
  10647. var _this = this;
  10648. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  10649. var saveAndLoadImage = function () {
  10650. if (!_this.hasReachedQuota && _this.db !== null) {
  10651. _this._saveImageIntoDBAsync(completeURL, image);
  10652. } else {
  10653. image.src = url;
  10654. }
  10655. };
  10656. if (!this.mustUpdateRessources) {
  10657. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  10658. } else {
  10659. saveAndLoadImage();
  10660. }
  10661. };
  10662. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  10663. if (this.isSupported && this.db !== null) {
  10664. var texture;
  10665. var transaction = this.db.transaction(["textures"]);
  10666. transaction.onabort = function (event) {
  10667. image.src = url;
  10668. };
  10669. transaction.oncomplete = function (event) {
  10670. var blobTextureURL;
  10671. if (texture) {
  10672. var URL = window.URL || window.webkitURL;
  10673. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  10674. image.onerror = function () {
  10675. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  10676. image.src = url;
  10677. };
  10678. image.src = blobTextureURL;
  10679. } else {
  10680. notInDBCallback();
  10681. }
  10682. };
  10683. var getRequest = transaction.objectStore("textures").get(url);
  10684. getRequest.onsuccess = function (event) {
  10685. texture = (event.target).result;
  10686. };
  10687. getRequest.onerror = function (event) {
  10688. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  10689. image.src = url;
  10690. };
  10691. } else {
  10692. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10693. image.src = url;
  10694. }
  10695. };
  10696. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  10697. var _this = this;
  10698. if (this.isSupported) {
  10699. var generateBlobUrl = function () {
  10700. var blobTextureURL;
  10701. if (blob) {
  10702. var URL = window.URL || window.webkitURL;
  10703. try {
  10704. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  10705. } catch (ex) {
  10706. blobTextureURL = URL.createObjectURL(blob);
  10707. }
  10708. }
  10709. image.src = blobTextureURL;
  10710. };
  10711. if (BABYLON.Database.isUASupportingBlobStorage) {
  10712. var xhr = new XMLHttpRequest(), blob;
  10713. xhr.open("GET", url, true);
  10714. xhr.responseType = "blob";
  10715. xhr.addEventListener("load", function () {
  10716. if (xhr.status === 200) {
  10717. blob = xhr.response;
  10718. var transaction = _this.db.transaction(["textures"], "readwrite");
  10719. transaction.onabort = function (event) {
  10720. try {
  10721. if (event.srcElement.error.name === "QuotaExceededError") {
  10722. this.hasReachedQuota = true;
  10723. }
  10724. } catch (ex) {
  10725. }
  10726. generateBlobUrl();
  10727. };
  10728. transaction.oncomplete = function (event) {
  10729. generateBlobUrl();
  10730. };
  10731. var newTexture = { textureUrl: url, data: blob };
  10732. try {
  10733. var addRequest = transaction.objectStore("textures").put(newTexture);
  10734. addRequest.onsuccess = function (event) {
  10735. };
  10736. addRequest.onerror = function (event) {
  10737. generateBlobUrl();
  10738. };
  10739. } catch (ex) {
  10740. if (ex.code === 25) {
  10741. BABYLON.Database.isUASupportingBlobStorage = false;
  10742. }
  10743. image.src = url;
  10744. }
  10745. } else {
  10746. image.src = url;
  10747. }
  10748. }, false);
  10749. xhr.addEventListener("error", function (event) {
  10750. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  10751. image.src = url;
  10752. }, false);
  10753. xhr.send();
  10754. } else {
  10755. image.src = url;
  10756. }
  10757. } else {
  10758. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10759. image.src = url;
  10760. }
  10761. };
  10762. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  10763. var _this = this;
  10764. var updateVersion = function (event) {
  10765. _this._saveVersionIntoDBAsync(url, versionLoaded);
  10766. };
  10767. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  10768. };
  10769. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  10770. var _this = this;
  10771. if (this.isSupported) {
  10772. var version;
  10773. try {
  10774. var transaction = this.db.transaction(["versions"]);
  10775. transaction.oncomplete = function (event) {
  10776. if (version) {
  10777. if (_this.manifestVersionFound > version.data) {
  10778. _this.mustUpdateRessources = true;
  10779. updateInDBCallback();
  10780. } else {
  10781. callback(version.data);
  10782. }
  10783. } else {
  10784. _this.mustUpdateRessources = true;
  10785. updateInDBCallback();
  10786. }
  10787. };
  10788. transaction.onabort = function (event) {
  10789. callback(-1);
  10790. };
  10791. var getRequest = transaction.objectStore("versions").get(url);
  10792. getRequest.onsuccess = function (event) {
  10793. version = (event.target).result;
  10794. };
  10795. getRequest.onerror = function (event) {
  10796. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  10797. callback(-1);
  10798. };
  10799. } catch (ex) {
  10800. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  10801. callback(-1);
  10802. }
  10803. } else {
  10804. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10805. callback(-1);
  10806. }
  10807. };
  10808. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  10809. var _this = this;
  10810. if (this.isSupported && !this.hasReachedQuota) {
  10811. try {
  10812. var transaction = this.db.transaction(["versions"], "readwrite");
  10813. transaction.onabort = function (event) {
  10814. try {
  10815. if (event.srcElement.error.name === "QuotaExceededError") {
  10816. _this.hasReachedQuota = true;
  10817. }
  10818. } catch (ex) {
  10819. }
  10820. callback(-1);
  10821. };
  10822. transaction.oncomplete = function (event) {
  10823. callback(_this.manifestVersionFound);
  10824. };
  10825. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  10826. var addRequest = transaction.objectStore("versions").put(newVersion);
  10827. addRequest.onsuccess = function (event) {
  10828. };
  10829. addRequest.onerror = function (event) {
  10830. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  10831. };
  10832. } catch (ex) {
  10833. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  10834. callback(-1);
  10835. }
  10836. } else {
  10837. callback(-1);
  10838. }
  10839. };
  10840. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  10841. var _this = this;
  10842. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  10843. var saveAndLoadFile = function (event) {
  10844. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  10845. };
  10846. this._checkVersionFromDB(completeUrl, function (version) {
  10847. if (version !== -1) {
  10848. if (!_this.mustUpdateRessources) {
  10849. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  10850. } else {
  10851. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  10852. }
  10853. } else {
  10854. errorCallback();
  10855. }
  10856. });
  10857. };
  10858. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  10859. if (this.isSupported) {
  10860. var targetStore;
  10861. if (url.indexOf(".babylon") !== -1) {
  10862. targetStore = "scenes";
  10863. } else {
  10864. targetStore = "textures";
  10865. }
  10866. var file;
  10867. var transaction = this.db.transaction([targetStore]);
  10868. transaction.oncomplete = function (event) {
  10869. if (file) {
  10870. callback(file.data);
  10871. } else {
  10872. notInDBCallback();
  10873. }
  10874. };
  10875. transaction.onabort = function (event) {
  10876. notInDBCallback();
  10877. };
  10878. var getRequest = transaction.objectStore(targetStore).get(url);
  10879. getRequest.onsuccess = function (event) {
  10880. file = (event.target).result;
  10881. };
  10882. getRequest.onerror = function (event) {
  10883. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  10884. notInDBCallback();
  10885. };
  10886. } else {
  10887. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10888. callback();
  10889. }
  10890. };
  10891. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  10892. var _this = this;
  10893. if (this.isSupported) {
  10894. var targetStore;
  10895. if (url.indexOf(".babylon") !== -1) {
  10896. targetStore = "scenes";
  10897. } else {
  10898. targetStore = "textures";
  10899. }
  10900. var xhr = new XMLHttpRequest(), fileData;
  10901. xhr.open("GET", url, true);
  10902. if (useArrayBuffer) {
  10903. xhr.responseType = "arraybuffer";
  10904. }
  10905. xhr.onprogress = progressCallback;
  10906. xhr.addEventListener("load", function () {
  10907. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  10908. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  10909. if (!_this.hasReachedQuota) {
  10910. var transaction = _this.db.transaction([targetStore], "readwrite");
  10911. transaction.onabort = function (event) {
  10912. try {
  10913. if (event.srcElement.error.name === "QuotaExceededError") {
  10914. this.hasReachedQuota = true;
  10915. }
  10916. } catch (ex) {
  10917. }
  10918. callback(fileData);
  10919. };
  10920. transaction.oncomplete = function (event) {
  10921. callback(fileData);
  10922. };
  10923. var newFile;
  10924. if (targetStore === "scenes") {
  10925. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  10926. } else {
  10927. newFile = { textureUrl: url, data: fileData };
  10928. }
  10929. try {
  10930. var addRequest = transaction.objectStore(targetStore).put(newFile);
  10931. addRequest.onsuccess = function (event) {
  10932. };
  10933. addRequest.onerror = function (event) {
  10934. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  10935. };
  10936. } catch (ex) {
  10937. callback(fileData);
  10938. }
  10939. } else {
  10940. callback(fileData);
  10941. }
  10942. } else {
  10943. callback();
  10944. }
  10945. }, false);
  10946. xhr.addEventListener("error", function (event) {
  10947. BABYLON.Tools.Error("error on XHR request.");
  10948. callback();
  10949. }, false);
  10950. xhr.send();
  10951. } else {
  10952. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10953. callback();
  10954. }
  10955. };
  10956. Database.isUASupportingBlobStorage = true;
  10957. Database.parseURL = function (url) {
  10958. var a = document.createElement('a');
  10959. a.href = url;
  10960. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  10961. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  10962. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  10963. return absLocation;
  10964. };
  10965. Database.ReturnFullUrlLocation = function (url) {
  10966. if (url.indexOf("http:/") === -1) {
  10967. return (BABYLON.Database.parseURL(window.location.href) + url);
  10968. } else {
  10969. return url;
  10970. }
  10971. };
  10972. return Database;
  10973. })();
  10974. BABYLON.Database = Database;
  10975. })(BABYLON || (BABYLON = {}));
  10976. var BABYLON;
  10977. (function (BABYLON) {
  10978. var SpriteManager = (function () {
  10979. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  10980. this.name = name;
  10981. this.cellSize = cellSize;
  10982. this.sprites = new Array();
  10983. this.renderingGroupId = 0;
  10984. this._vertexDeclaration = [3, 4, 4, 4];
  10985. this._vertexStrideSize = 15 * 4;
  10986. this._capacity = capacity;
  10987. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  10988. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10989. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10990. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  10991. this._scene = scene;
  10992. this._scene.spriteManagers.push(this);
  10993. this._vertexDeclaration = [3, 4, 4, 4];
  10994. this._vertexStrideSize = 15 * 4;
  10995. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  10996. var indices = [];
  10997. var index = 0;
  10998. for (var count = 0; count < capacity; count++) {
  10999. indices.push(index);
  11000. indices.push(index + 1);
  11001. indices.push(index + 2);
  11002. indices.push(index);
  11003. indices.push(index + 2);
  11004. indices.push(index + 3);
  11005. index += 4;
  11006. }
  11007. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11008. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  11009. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  11010. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  11011. }
  11012. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  11013. var arrayOffset = index * 15;
  11014. if (offsetX == 0)
  11015. offsetX = this._epsilon;
  11016. else if (offsetX == 1)
  11017. offsetX = 1 - this._epsilon;
  11018. if (offsetY == 0)
  11019. offsetY = this._epsilon;
  11020. else if (offsetY == 1)
  11021. offsetY = 1 - this._epsilon;
  11022. this._vertices[arrayOffset] = sprite.position.x;
  11023. this._vertices[arrayOffset + 1] = sprite.position.y;
  11024. this._vertices[arrayOffset + 2] = sprite.position.z;
  11025. this._vertices[arrayOffset + 3] = sprite.angle;
  11026. this._vertices[arrayOffset + 4] = sprite.size;
  11027. this._vertices[arrayOffset + 5] = offsetX;
  11028. this._vertices[arrayOffset + 6] = offsetY;
  11029. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  11030. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  11031. var offset = (sprite.cellIndex / rowSize) >> 0;
  11032. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  11033. this._vertices[arrayOffset + 10] = offset;
  11034. this._vertices[arrayOffset + 11] = sprite.color.r;
  11035. this._vertices[arrayOffset + 12] = sprite.color.g;
  11036. this._vertices[arrayOffset + 13] = sprite.color.b;
  11037. this._vertices[arrayOffset + 14] = sprite.color.a;
  11038. };
  11039. SpriteManager.prototype.render = function () {
  11040. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  11041. return;
  11042. var engine = this._scene.getEngine();
  11043. var baseSize = this._spriteTexture.getBaseSize();
  11044. var deltaTime = BABYLON.Tools.GetDeltaTime();
  11045. var max = Math.min(this._capacity, this.sprites.length);
  11046. var rowSize = baseSize.width / this.cellSize;
  11047. var offset = 0;
  11048. for (var index = 0; index < max; index++) {
  11049. var sprite = this.sprites[index];
  11050. if (!sprite) {
  11051. continue;
  11052. }
  11053. sprite._animate(deltaTime);
  11054. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  11055. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  11056. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  11057. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  11058. }
  11059. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
  11060. var effect = this._effectBase;
  11061. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  11062. effect = this._effectFog;
  11063. }
  11064. engine.enableEffect(effect);
  11065. var viewMatrix = this._scene.getViewMatrix();
  11066. effect.setTexture("diffuseSampler", this._spriteTexture);
  11067. effect.setMatrix("view", viewMatrix);
  11068. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  11069. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  11070. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  11071. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  11072. effect.setColor3("vFogColor", this._scene.fogColor);
  11073. }
  11074. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  11075. effect.setBool("alphaTest", true);
  11076. engine.setColorWrite(false);
  11077. engine.draw(true, 0, max * 6);
  11078. engine.setColorWrite(true);
  11079. effect.setBool("alphaTest", false);
  11080. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11081. engine.draw(true, 0, max * 6);
  11082. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11083. };
  11084. SpriteManager.prototype.dispose = function () {
  11085. if (this._vertexBuffer) {
  11086. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11087. this._vertexBuffer = null;
  11088. }
  11089. if (this._indexBuffer) {
  11090. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11091. this._indexBuffer = null;
  11092. }
  11093. if (this._spriteTexture) {
  11094. this._spriteTexture.dispose();
  11095. this._spriteTexture = null;
  11096. }
  11097. var index = this._scene.spriteManagers.indexOf(this);
  11098. this._scene.spriteManagers.splice(index, 1);
  11099. if (this.onDispose) {
  11100. this.onDispose();
  11101. }
  11102. };
  11103. return SpriteManager;
  11104. })();
  11105. BABYLON.SpriteManager = SpriteManager;
  11106. })(BABYLON || (BABYLON = {}));
  11107. var BABYLON;
  11108. (function (BABYLON) {
  11109. var Sprite = (function () {
  11110. function Sprite(name, manager) {
  11111. this.name = name;
  11112. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11113. this.size = 1.0;
  11114. this.angle = 0;
  11115. this.cellIndex = 0;
  11116. this.invertU = 0;
  11117. this.invertV = 0;
  11118. this.animations = new Array();
  11119. this._animationStarted = false;
  11120. this._loopAnimation = false;
  11121. this._fromIndex = 0;
  11122. this._toIndex = 0;
  11123. this._delay = 0;
  11124. this._direction = 1;
  11125. this._frameCount = 0;
  11126. this._time = 0;
  11127. this._manager = manager;
  11128. this._manager.sprites.push(this);
  11129. this.position = BABYLON.Vector3.Zero();
  11130. }
  11131. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  11132. this._fromIndex = from;
  11133. this._toIndex = to;
  11134. this._loopAnimation = loop;
  11135. this._delay = delay;
  11136. this._animationStarted = true;
  11137. this._direction = from < to ? 1 : -1;
  11138. this.cellIndex = from;
  11139. this._time = 0;
  11140. };
  11141. Sprite.prototype.stopAnimation = function () {
  11142. this._animationStarted = false;
  11143. };
  11144. Sprite.prototype._animate = function (deltaTime) {
  11145. if (!this._animationStarted)
  11146. return;
  11147. this._time += deltaTime;
  11148. if (this._time > this._delay) {
  11149. this._time = this._time % this._delay;
  11150. this.cellIndex += this._direction;
  11151. if (this.cellIndex == this._toIndex) {
  11152. if (this._loopAnimation) {
  11153. this.cellIndex = this._fromIndex;
  11154. } else {
  11155. this._animationStarted = false;
  11156. if (this.disposeWhenFinishedAnimating) {
  11157. this.dispose();
  11158. }
  11159. }
  11160. }
  11161. }
  11162. };
  11163. Sprite.prototype.dispose = function () {
  11164. for (var i = 0; i < this._manager.sprites.length; i++) {
  11165. if (this._manager.sprites[i] == this) {
  11166. this._manager.sprites.splice(i, 1);
  11167. }
  11168. }
  11169. };
  11170. return Sprite;
  11171. })();
  11172. BABYLON.Sprite = Sprite;
  11173. })(BABYLON || (BABYLON = {}));
  11174. var BABYLON;
  11175. (function (BABYLON) {
  11176. var Layer = (function () {
  11177. function Layer(name, imgUrl, scene, isBackground, color) {
  11178. this.name = name;
  11179. this._vertexDeclaration = [2];
  11180. this._vertexStrideSize = 2 * 4;
  11181. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  11182. this.isBackground = isBackground === undefined ? true : isBackground;
  11183. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  11184. this._scene = scene;
  11185. this._scene.layers.push(this);
  11186. var vertices = [];
  11187. vertices.push(1, 1);
  11188. vertices.push(-1, 1);
  11189. vertices.push(-1, -1);
  11190. vertices.push(1, -1);
  11191. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11192. var indices = [];
  11193. indices.push(0);
  11194. indices.push(1);
  11195. indices.push(2);
  11196. indices.push(0);
  11197. indices.push(2);
  11198. indices.push(3);
  11199. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11200. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  11201. }
  11202. Layer.prototype.render = function () {
  11203. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  11204. return;
  11205. var engine = this._scene.getEngine();
  11206. engine.enableEffect(this._effect);
  11207. engine.setState(false);
  11208. this._effect.setTexture("textureSampler", this.texture);
  11209. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  11210. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  11211. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11212. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11213. engine.draw(true, 0, 6);
  11214. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11215. };
  11216. Layer.prototype.dispose = function () {
  11217. if (this._vertexBuffer) {
  11218. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11219. this._vertexBuffer = null;
  11220. }
  11221. if (this._indexBuffer) {
  11222. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11223. this._indexBuffer = null;
  11224. }
  11225. if (this.texture) {
  11226. this.texture.dispose();
  11227. this.texture = null;
  11228. }
  11229. var index = this._scene.layers.indexOf(this);
  11230. this._scene.layers.splice(index, 1);
  11231. if (this.onDispose) {
  11232. this.onDispose();
  11233. }
  11234. };
  11235. return Layer;
  11236. })();
  11237. BABYLON.Layer = Layer;
  11238. })(BABYLON || (BABYLON = {}));
  11239. var BABYLON;
  11240. (function (BABYLON) {
  11241. var Particle = (function () {
  11242. function Particle() {
  11243. this.position = BABYLON.Vector3.Zero();
  11244. this.direction = BABYLON.Vector3.Zero();
  11245. this.color = new BABYLON.Color4(0, 0, 0, 0);
  11246. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  11247. this.lifeTime = 1.0;
  11248. this.age = 0;
  11249. this.size = 0;
  11250. this.angle = 0;
  11251. this.angularSpeed = 0;
  11252. }
  11253. return Particle;
  11254. })();
  11255. BABYLON.Particle = Particle;
  11256. })(BABYLON || (BABYLON = {}));
  11257. var BABYLON;
  11258. (function (BABYLON) {
  11259. var randomNumber = function (min, max) {
  11260. if (min == max) {
  11261. return (min);
  11262. }
  11263. var random = Math.random();
  11264. return ((random * (max - min)) + min);
  11265. };
  11266. var ParticleSystem = (function () {
  11267. function ParticleSystem(name, capacity, scene, customEffect) {
  11268. var _this = this;
  11269. this.name = name;
  11270. this.renderingGroupId = 0;
  11271. this.emitter = null;
  11272. this.emitRate = 10;
  11273. this.manualEmitCount = -1;
  11274. this.updateSpeed = 0.01;
  11275. this.targetStopDuration = 0;
  11276. this.disposeOnStop = false;
  11277. this.minEmitPower = 1;
  11278. this.maxEmitPower = 1;
  11279. this.minLifeTime = 1;
  11280. this.maxLifeTime = 1;
  11281. this.minSize = 1;
  11282. this.maxSize = 1;
  11283. this.minAngularSpeed = 0;
  11284. this.maxAngularSpeed = 0;
  11285. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  11286. this.forceDepthWrite = false;
  11287. this.gravity = BABYLON.Vector3.Zero();
  11288. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  11289. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  11290. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  11291. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11292. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11293. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11294. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  11295. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11296. this.particles = new Array();
  11297. this._vertexDeclaration = [3, 4, 4];
  11298. this._vertexStrideSize = 11 * 4;
  11299. this._stockParticles = new Array();
  11300. this._newPartsExcess = 0;
  11301. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  11302. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  11303. this._scaledDirection = BABYLON.Vector3.Zero();
  11304. this._scaledGravity = BABYLON.Vector3.Zero();
  11305. this._currentRenderId = -1;
  11306. this._started = false;
  11307. this._stopped = false;
  11308. this._actualFrame = 0;
  11309. this.id = name;
  11310. this._capacity = capacity;
  11311. this._scene = scene;
  11312. this._customEffect = customEffect;
  11313. scene.particleSystems.push(this);
  11314. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  11315. var indices = [];
  11316. var index = 0;
  11317. for (var count = 0; count < capacity; count++) {
  11318. indices.push(index);
  11319. indices.push(index + 1);
  11320. indices.push(index + 2);
  11321. indices.push(index);
  11322. indices.push(index + 2);
  11323. indices.push(index + 3);
  11324. index += 4;
  11325. }
  11326. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11327. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  11328. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  11329. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  11330. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  11331. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  11332. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  11333. };
  11334. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  11335. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  11336. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  11337. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  11338. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  11339. };
  11340. }
  11341. ParticleSystem.prototype.getCapacity = function () {
  11342. return this._capacity;
  11343. };
  11344. ParticleSystem.prototype.isAlive = function () {
  11345. return this._alive;
  11346. };
  11347. ParticleSystem.prototype.isStarted = function () {
  11348. return this._started;
  11349. };
  11350. ParticleSystem.prototype.start = function () {
  11351. this._started = true;
  11352. this._stopped = false;
  11353. this._actualFrame = 0;
  11354. };
  11355. ParticleSystem.prototype.stop = function () {
  11356. this._stopped = true;
  11357. };
  11358. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  11359. var offset = index * 11;
  11360. this._vertices[offset] = particle.position.x;
  11361. this._vertices[offset + 1] = particle.position.y;
  11362. this._vertices[offset + 2] = particle.position.z;
  11363. this._vertices[offset + 3] = particle.color.r;
  11364. this._vertices[offset + 4] = particle.color.g;
  11365. this._vertices[offset + 5] = particle.color.b;
  11366. this._vertices[offset + 6] = particle.color.a;
  11367. this._vertices[offset + 7] = particle.angle;
  11368. this._vertices[offset + 8] = particle.size;
  11369. this._vertices[offset + 9] = offsetX;
  11370. this._vertices[offset + 10] = offsetY;
  11371. };
  11372. ParticleSystem.prototype._update = function (newParticles) {
  11373. this._alive = this.particles.length > 0;
  11374. for (var index = 0; index < this.particles.length; index++) {
  11375. var particle = this.particles[index];
  11376. particle.age += this._scaledUpdateSpeed;
  11377. if (particle.age >= particle.lifeTime) {
  11378. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  11379. index--;
  11380. continue;
  11381. } else {
  11382. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  11383. particle.color.addInPlace(this._scaledColorStep);
  11384. if (particle.color.a < 0)
  11385. particle.color.a = 0;
  11386. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  11387. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  11388. particle.position.addInPlace(this._scaledDirection);
  11389. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  11390. particle.direction.addInPlace(this._scaledGravity);
  11391. }
  11392. }
  11393. var worldMatrix;
  11394. if (this.emitter.position) {
  11395. worldMatrix = this.emitter.getWorldMatrix();
  11396. } else {
  11397. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  11398. }
  11399. for (index = 0; index < newParticles; index++) {
  11400. if (this.particles.length == this._capacity) {
  11401. break;
  11402. }
  11403. if (this._stockParticles.length !== 0) {
  11404. particle = this._stockParticles.pop();
  11405. particle.age = 0;
  11406. } else {
  11407. particle = new BABYLON.Particle();
  11408. }
  11409. this.particles.push(particle);
  11410. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  11411. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  11412. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  11413. particle.size = randomNumber(this.minSize, this.maxSize);
  11414. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  11415. this.startPositionFunction(worldMatrix, particle.position);
  11416. var step = randomNumber(0, 1.0);
  11417. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  11418. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  11419. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  11420. }
  11421. };
  11422. ParticleSystem.prototype._getEffect = function () {
  11423. if (this._customEffect) {
  11424. return this._customEffect;
  11425. }
  11426. ;
  11427. var defines = [];
  11428. if (this._scene.clipPlane) {
  11429. defines.push("#define CLIPPLANE");
  11430. }
  11431. var join = defines.join("\n");
  11432. if (this._cachedDefines != join) {
  11433. this._cachedDefines = join;
  11434. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  11435. }
  11436. return this._effect;
  11437. };
  11438. ParticleSystem.prototype.animate = function () {
  11439. if (!this._started)
  11440. return;
  11441. var effect = this._getEffect();
  11442. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  11443. return;
  11444. if (this._currentRenderId === this._scene.getRenderId()) {
  11445. return;
  11446. }
  11447. this._currentRenderId = this._scene.getRenderId();
  11448. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  11449. var emitCout;
  11450. if (this.manualEmitCount > -1) {
  11451. emitCout = this.manualEmitCount;
  11452. this.manualEmitCount = 0;
  11453. } else {
  11454. emitCout = this.emitRate;
  11455. }
  11456. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  11457. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  11458. if (this._newPartsExcess > 1.0) {
  11459. newParticles += this._newPartsExcess >> 0;
  11460. this._newPartsExcess -= this._newPartsExcess >> 0;
  11461. }
  11462. this._alive = false;
  11463. if (!this._stopped) {
  11464. this._actualFrame += this._scaledUpdateSpeed;
  11465. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  11466. this.stop();
  11467. } else {
  11468. newParticles = 0;
  11469. }
  11470. this._update(newParticles);
  11471. if (this._stopped) {
  11472. if (!this._alive) {
  11473. this._started = false;
  11474. if (this.disposeOnStop) {
  11475. this._scene._toBeDisposed.push(this);
  11476. }
  11477. }
  11478. }
  11479. var offset = 0;
  11480. for (var index = 0; index < this.particles.length; index++) {
  11481. var particle = this.particles[index];
  11482. this._appendParticleVertex(offset++, particle, 0, 0);
  11483. this._appendParticleVertex(offset++, particle, 1, 0);
  11484. this._appendParticleVertex(offset++, particle, 1, 1);
  11485. this._appendParticleVertex(offset++, particle, 0, 1);
  11486. }
  11487. var engine = this._scene.getEngine();
  11488. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
  11489. };
  11490. ParticleSystem.prototype.render = function () {
  11491. var effect = this._getEffect();
  11492. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  11493. return 0;
  11494. var engine = this._scene.getEngine();
  11495. engine.enableEffect(effect);
  11496. var viewMatrix = this._scene.getViewMatrix();
  11497. effect.setTexture("diffuseSampler", this.particleTexture);
  11498. effect.setMatrix("view", viewMatrix);
  11499. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  11500. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  11501. if (this._scene.clipPlane) {
  11502. var clipPlane = this._scene.clipPlane;
  11503. var invView = viewMatrix.clone();
  11504. invView.invert();
  11505. effect.setMatrix("invView", invView);
  11506. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  11507. }
  11508. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  11509. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  11510. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  11511. } else {
  11512. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11513. }
  11514. if (this.forceDepthWrite) {
  11515. engine.setDepthWrite(true);
  11516. }
  11517. engine.draw(true, 0, this.particles.length * 6);
  11518. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11519. return this.particles.length;
  11520. };
  11521. ParticleSystem.prototype.dispose = function () {
  11522. if (this._vertexBuffer) {
  11523. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11524. this._vertexBuffer = null;
  11525. }
  11526. if (this._indexBuffer) {
  11527. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11528. this._indexBuffer = null;
  11529. }
  11530. if (this.particleTexture) {
  11531. this.particleTexture.dispose();
  11532. this.particleTexture = null;
  11533. }
  11534. var index = this._scene.particleSystems.indexOf(this);
  11535. this._scene.particleSystems.splice(index, 1);
  11536. if (this.onDispose) {
  11537. this.onDispose();
  11538. }
  11539. };
  11540. ParticleSystem.prototype.clone = function (name, newEmitter) {
  11541. var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
  11542. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  11543. if (newEmitter === undefined) {
  11544. newEmitter = this.emitter;
  11545. }
  11546. result.emitter = newEmitter;
  11547. if (this.particleTexture) {
  11548. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  11549. }
  11550. result.start();
  11551. return result;
  11552. };
  11553. ParticleSystem.BLENDMODE_ONEONE = 0;
  11554. ParticleSystem.BLENDMODE_STANDARD = 1;
  11555. return ParticleSystem;
  11556. })();
  11557. BABYLON.ParticleSystem = ParticleSystem;
  11558. })(BABYLON || (BABYLON = {}));
  11559. var BABYLON;
  11560. (function (BABYLON) {
  11561. var Animation = (function () {
  11562. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  11563. this.name = name;
  11564. this.targetProperty = targetProperty;
  11565. this.framePerSecond = framePerSecond;
  11566. this.dataType = dataType;
  11567. this.loopMode = loopMode;
  11568. this._offsetsCache = {};
  11569. this._highLimitsCache = {};
  11570. this._stopped = false;
  11571. this.targetPropertyPath = targetProperty.split(".");
  11572. this.dataType = dataType;
  11573. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  11574. }
  11575. Animation.prototype.isStopped = function () {
  11576. return this._stopped;
  11577. };
  11578. Animation.prototype.getKeys = function () {
  11579. return this._keys;
  11580. };
  11581. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  11582. return startValue + (endValue - startValue) * gradient;
  11583. };
  11584. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  11585. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  11586. };
  11587. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  11588. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  11589. };
  11590. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  11591. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  11592. };
  11593. Animation.prototype.clone = function () {
  11594. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  11595. clone.setKeys(this._keys);
  11596. return clone;
  11597. };
  11598. Animation.prototype.setKeys = function (values) {
  11599. this._keys = values.slice(0);
  11600. this._offsetsCache = {};
  11601. this._highLimitsCache = {};
  11602. };
  11603. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  11604. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  11605. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  11606. }
  11607. this.currentFrame = currentFrame;
  11608. for (var key = 0; key < this._keys.length; key++) {
  11609. if (this._keys[key + 1].frame >= currentFrame) {
  11610. var startValue = this._keys[key].value;
  11611. var endValue = this._keys[key + 1].value;
  11612. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  11613. switch (this.dataType) {
  11614. case Animation.ANIMATIONTYPE_FLOAT:
  11615. switch (loopMode) {
  11616. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11617. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11618. return this.floatInterpolateFunction(startValue, endValue, gradient);
  11619. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11620. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  11621. }
  11622. break;
  11623. case Animation.ANIMATIONTYPE_QUATERNION:
  11624. var quaternion = null;
  11625. switch (loopMode) {
  11626. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11627. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11628. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  11629. break;
  11630. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11631. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11632. break;
  11633. }
  11634. return quaternion;
  11635. case Animation.ANIMATIONTYPE_VECTOR3:
  11636. switch (loopMode) {
  11637. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11638. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11639. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  11640. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11641. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11642. }
  11643. case Animation.ANIMATIONTYPE_COLOR3:
  11644. switch (loopMode) {
  11645. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11646. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11647. return this.color3InterpolateFunction(startValue, endValue, gradient);
  11648. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11649. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11650. }
  11651. case Animation.ANIMATIONTYPE_MATRIX:
  11652. switch (loopMode) {
  11653. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11654. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11655. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11656. return startValue;
  11657. }
  11658. default:
  11659. break;
  11660. }
  11661. break;
  11662. }
  11663. }
  11664. return this._keys[this._keys.length - 1].value;
  11665. };
  11666. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  11667. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  11668. this._stopped = true;
  11669. return false;
  11670. }
  11671. var returnValue = true;
  11672. if (this._keys[0].frame != 0) {
  11673. var newKey = {
  11674. frame: 0,
  11675. value: this._keys[0].value
  11676. };
  11677. this._keys.splice(0, 0, newKey);
  11678. }
  11679. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  11680. from = this._keys[0].frame;
  11681. }
  11682. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  11683. to = this._keys[this._keys.length - 1].frame;
  11684. }
  11685. var range = to - from;
  11686. var offsetValue;
  11687. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  11688. if (ratio > range && !loop) {
  11689. returnValue = false;
  11690. highLimitValue = this._keys[this._keys.length - 1].value;
  11691. } else {
  11692. var highLimitValue = 0;
  11693. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  11694. var keyOffset = to.toString() + from.toString();
  11695. if (!this._offsetsCache[keyOffset]) {
  11696. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  11697. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  11698. switch (this.dataType) {
  11699. case Animation.ANIMATIONTYPE_FLOAT:
  11700. this._offsetsCache[keyOffset] = toValue - fromValue;
  11701. break;
  11702. case Animation.ANIMATIONTYPE_QUATERNION:
  11703. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11704. break;
  11705. case Animation.ANIMATIONTYPE_VECTOR3:
  11706. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11707. case Animation.ANIMATIONTYPE_COLOR3:
  11708. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11709. default:
  11710. break;
  11711. }
  11712. this._highLimitsCache[keyOffset] = toValue;
  11713. }
  11714. highLimitValue = this._highLimitsCache[keyOffset];
  11715. offsetValue = this._offsetsCache[keyOffset];
  11716. }
  11717. }
  11718. if (offsetValue === undefined) {
  11719. switch (this.dataType) {
  11720. case Animation.ANIMATIONTYPE_FLOAT:
  11721. offsetValue = 0;
  11722. break;
  11723. case Animation.ANIMATIONTYPE_QUATERNION:
  11724. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  11725. break;
  11726. case Animation.ANIMATIONTYPE_VECTOR3:
  11727. offsetValue = BABYLON.Vector3.Zero();
  11728. break;
  11729. case Animation.ANIMATIONTYPE_COLOR3:
  11730. offsetValue = BABYLON.Color3.Black();
  11731. }
  11732. }
  11733. var repeatCount = (ratio / range) >> 0;
  11734. var currentFrame = returnValue ? from + ratio % range : to;
  11735. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  11736. if (this.targetPropertyPath.length > 1) {
  11737. var property = this._target[this.targetPropertyPath[0]];
  11738. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  11739. property = property[this.targetPropertyPath[index]];
  11740. }
  11741. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  11742. } else {
  11743. this._target[this.targetPropertyPath[0]] = currentValue;
  11744. }
  11745. if (this._target.markAsDirty) {
  11746. this._target.markAsDirty(this.targetProperty);
  11747. }
  11748. if (!returnValue) {
  11749. this._stopped = true;
  11750. }
  11751. return returnValue;
  11752. };
  11753. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  11754. get: function () {
  11755. return Animation._ANIMATIONTYPE_FLOAT;
  11756. },
  11757. enumerable: true,
  11758. configurable: true
  11759. });
  11760. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  11761. get: function () {
  11762. return Animation._ANIMATIONTYPE_VECTOR3;
  11763. },
  11764. enumerable: true,
  11765. configurable: true
  11766. });
  11767. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  11768. get: function () {
  11769. return Animation._ANIMATIONTYPE_QUATERNION;
  11770. },
  11771. enumerable: true,
  11772. configurable: true
  11773. });
  11774. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  11775. get: function () {
  11776. return Animation._ANIMATIONTYPE_MATRIX;
  11777. },
  11778. enumerable: true,
  11779. configurable: true
  11780. });
  11781. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  11782. get: function () {
  11783. return Animation._ANIMATIONTYPE_COLOR3;
  11784. },
  11785. enumerable: true,
  11786. configurable: true
  11787. });
  11788. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  11789. get: function () {
  11790. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  11791. },
  11792. enumerable: true,
  11793. configurable: true
  11794. });
  11795. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  11796. get: function () {
  11797. return Animation._ANIMATIONLOOPMODE_CYCLE;
  11798. },
  11799. enumerable: true,
  11800. configurable: true
  11801. });
  11802. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  11803. get: function () {
  11804. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  11805. },
  11806. enumerable: true,
  11807. configurable: true
  11808. });
  11809. Animation._ANIMATIONTYPE_FLOAT = 0;
  11810. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  11811. Animation._ANIMATIONTYPE_QUATERNION = 2;
  11812. Animation._ANIMATIONTYPE_MATRIX = 3;
  11813. Animation._ANIMATIONTYPE_COLOR3 = 4;
  11814. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  11815. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  11816. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  11817. return Animation;
  11818. })();
  11819. BABYLON.Animation = Animation;
  11820. })(BABYLON || (BABYLON = {}));
  11821. var BABYLON;
  11822. (function (BABYLON) {
  11823. var Animatable = (function () {
  11824. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  11825. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  11826. if (typeof toFrame === "undefined") { toFrame = 100; }
  11827. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  11828. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  11829. this.target = target;
  11830. this.fromFrame = fromFrame;
  11831. this.toFrame = toFrame;
  11832. this.loopAnimation = loopAnimation;
  11833. this.speedRatio = speedRatio;
  11834. this.onAnimationEnd = onAnimationEnd;
  11835. this._animations = new Array();
  11836. this._paused = false;
  11837. this.animationStarted = false;
  11838. if (animations) {
  11839. this.appendAnimations(target, animations);
  11840. }
  11841. this._scene = scene;
  11842. scene._activeAnimatables.push(this);
  11843. }
  11844. Animatable.prototype.appendAnimations = function (target, animations) {
  11845. for (var index = 0; index < animations.length; index++) {
  11846. var animation = animations[index];
  11847. animation._target = target;
  11848. this._animations.push(animation);
  11849. }
  11850. };
  11851. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  11852. var animations = this._animations;
  11853. for (var index = 0; index < animations.length; index++) {
  11854. if (animations[index].targetProperty === property) {
  11855. return animations[index];
  11856. }
  11857. }
  11858. return null;
  11859. };
  11860. Animatable.prototype.pause = function () {
  11861. this._paused = true;
  11862. };
  11863. Animatable.prototype.restart = function () {
  11864. this._paused = false;
  11865. };
  11866. Animatable.prototype.stop = function () {
  11867. var index = this._scene._activeAnimatables.indexOf(this);
  11868. if (index > -1) {
  11869. this._scene._activeAnimatables.splice(index, 1);
  11870. }
  11871. if (this.onAnimationEnd) {
  11872. this.onAnimationEnd();
  11873. }
  11874. };
  11875. Animatable.prototype._animate = function (delay) {
  11876. if (this._paused) {
  11877. return true;
  11878. }
  11879. if (!this._localDelayOffset) {
  11880. this._localDelayOffset = delay;
  11881. }
  11882. var running = false;
  11883. var animations = this._animations;
  11884. for (var index = 0; index < animations.length; index++) {
  11885. var animation = animations[index];
  11886. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  11887. running = running || isRunning;
  11888. }
  11889. if (!running && this.onAnimationEnd) {
  11890. this.onAnimationEnd();
  11891. }
  11892. return running;
  11893. };
  11894. return Animatable;
  11895. })();
  11896. BABYLON.Animatable = Animatable;
  11897. })(BABYLON || (BABYLON = {}));
  11898. var BABYLON;
  11899. (function (BABYLON) {
  11900. var Octree = (function () {
  11901. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  11902. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  11903. this.maxDepth = maxDepth;
  11904. this.dynamicContent = new Array();
  11905. this._maxBlockCapacity = maxBlockCapacity || 64;
  11906. this._selectionContent = new BABYLON.SmartArray(1024);
  11907. this._creationFunc = creationFunc;
  11908. }
  11909. Octree.prototype.update = function (worldMin, worldMax, entries) {
  11910. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  11911. };
  11912. Octree.prototype.addMesh = function (entry) {
  11913. for (var index = 0; index < this.blocks.length; index++) {
  11914. var block = this.blocks[index];
  11915. block.addEntry(entry);
  11916. }
  11917. };
  11918. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  11919. this._selectionContent.reset();
  11920. for (var index = 0; index < this.blocks.length; index++) {
  11921. var block = this.blocks[index];
  11922. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  11923. }
  11924. if (allowDuplicate) {
  11925. this._selectionContent.concat(this.dynamicContent);
  11926. } else {
  11927. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11928. }
  11929. return this._selectionContent;
  11930. };
  11931. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  11932. this._selectionContent.reset();
  11933. for (var index = 0; index < this.blocks.length; index++) {
  11934. var block = this.blocks[index];
  11935. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  11936. }
  11937. if (allowDuplicate) {
  11938. this._selectionContent.concat(this.dynamicContent);
  11939. } else {
  11940. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11941. }
  11942. return this._selectionContent;
  11943. };
  11944. Octree.prototype.intersectsRay = function (ray) {
  11945. this._selectionContent.reset();
  11946. for (var index = 0; index < this.blocks.length; index++) {
  11947. var block = this.blocks[index];
  11948. block.intersectsRay(ray, this._selectionContent);
  11949. }
  11950. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11951. return this._selectionContent;
  11952. };
  11953. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  11954. target.blocks = new Array();
  11955. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  11956. for (var x = 0; x < 2; x++) {
  11957. for (var y = 0; y < 2; y++) {
  11958. for (var z = 0; z < 2; z++) {
  11959. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  11960. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  11961. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  11962. block.addEntries(entries);
  11963. target.blocks.push(block);
  11964. }
  11965. }
  11966. }
  11967. };
  11968. Octree.CreationFuncForMeshes = function (entry, block) {
  11969. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  11970. block.entries.push(entry);
  11971. }
  11972. };
  11973. Octree.CreationFuncForSubMeshes = function (entry, block) {
  11974. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  11975. block.entries.push(entry);
  11976. }
  11977. };
  11978. return Octree;
  11979. })();
  11980. BABYLON.Octree = Octree;
  11981. })(BABYLON || (BABYLON = {}));
  11982. var BABYLON;
  11983. (function (BABYLON) {
  11984. var OctreeBlock = (function () {
  11985. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  11986. this.entries = new Array();
  11987. this._boundingVectors = new Array();
  11988. this._capacity = capacity;
  11989. this._depth = depth;
  11990. this._maxDepth = maxDepth;
  11991. this._creationFunc = creationFunc;
  11992. this._minPoint = minPoint;
  11993. this._maxPoint = maxPoint;
  11994. this._boundingVectors.push(minPoint.clone());
  11995. this._boundingVectors.push(maxPoint.clone());
  11996. this._boundingVectors.push(minPoint.clone());
  11997. this._boundingVectors[2].x = maxPoint.x;
  11998. this._boundingVectors.push(minPoint.clone());
  11999. this._boundingVectors[3].y = maxPoint.y;
  12000. this._boundingVectors.push(minPoint.clone());
  12001. this._boundingVectors[4].z = maxPoint.z;
  12002. this._boundingVectors.push(maxPoint.clone());
  12003. this._boundingVectors[5].z = minPoint.z;
  12004. this._boundingVectors.push(maxPoint.clone());
  12005. this._boundingVectors[6].x = minPoint.x;
  12006. this._boundingVectors.push(maxPoint.clone());
  12007. this._boundingVectors[7].y = minPoint.y;
  12008. }
  12009. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  12010. get: function () {
  12011. return this._capacity;
  12012. },
  12013. enumerable: true,
  12014. configurable: true
  12015. });
  12016. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  12017. get: function () {
  12018. return this._minPoint;
  12019. },
  12020. enumerable: true,
  12021. configurable: true
  12022. });
  12023. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  12024. get: function () {
  12025. return this._maxPoint;
  12026. },
  12027. enumerable: true,
  12028. configurable: true
  12029. });
  12030. OctreeBlock.prototype.addEntry = function (entry) {
  12031. if (this.blocks) {
  12032. for (var index = 0; index < this.blocks.length; index++) {
  12033. var block = this.blocks[index];
  12034. block.addEntry(entry);
  12035. }
  12036. return;
  12037. }
  12038. this._creationFunc(entry, this);
  12039. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  12040. this.createInnerBlocks();
  12041. }
  12042. };
  12043. OctreeBlock.prototype.addEntries = function (entries) {
  12044. for (var index = 0; index < entries.length; index++) {
  12045. var mesh = entries[index];
  12046. this.addEntry(mesh);
  12047. }
  12048. };
  12049. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  12050. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  12051. if (this.blocks) {
  12052. for (var index = 0; index < this.blocks.length; index++) {
  12053. var block = this.blocks[index];
  12054. block.select(frustumPlanes, selection, allowDuplicate);
  12055. }
  12056. return;
  12057. }
  12058. if (allowDuplicate) {
  12059. selection.concat(this.entries);
  12060. } else {
  12061. selection.concatWithNoDuplicate(this.entries);
  12062. }
  12063. }
  12064. };
  12065. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  12066. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  12067. if (this.blocks) {
  12068. for (var index = 0; index < this.blocks.length; index++) {
  12069. var block = this.blocks[index];
  12070. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  12071. }
  12072. return;
  12073. }
  12074. if (allowDuplicate) {
  12075. selection.concat(this.entries);
  12076. } else {
  12077. selection.concatWithNoDuplicate(this.entries);
  12078. }
  12079. }
  12080. };
  12081. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  12082. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  12083. if (this.blocks) {
  12084. for (var index = 0; index < this.blocks.length; index++) {
  12085. var block = this.blocks[index];
  12086. block.intersectsRay(ray, selection);
  12087. }
  12088. return;
  12089. }
  12090. selection.concatWithNoDuplicate(this.entries);
  12091. }
  12092. };
  12093. OctreeBlock.prototype.createInnerBlocks = function () {
  12094. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  12095. };
  12096. return OctreeBlock;
  12097. })();
  12098. BABYLON.OctreeBlock = OctreeBlock;
  12099. })(BABYLON || (BABYLON = {}));
  12100. var BABYLON;
  12101. (function (BABYLON) {
  12102. var Bone = (function () {
  12103. function Bone(name, skeleton, parentBone, matrix) {
  12104. this.name = name;
  12105. this.children = new Array();
  12106. this.animations = new Array();
  12107. this._worldTransform = new BABYLON.Matrix();
  12108. this._absoluteTransform = new BABYLON.Matrix();
  12109. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  12110. this._skeleton = skeleton;
  12111. this._matrix = matrix;
  12112. this._baseMatrix = matrix;
  12113. skeleton.bones.push(this);
  12114. if (parentBone) {
  12115. this._parent = parentBone;
  12116. parentBone.children.push(this);
  12117. } else {
  12118. this._parent = null;
  12119. }
  12120. this._updateDifferenceMatrix();
  12121. }
  12122. Bone.prototype.getParent = function () {
  12123. return this._parent;
  12124. };
  12125. Bone.prototype.getLocalMatrix = function () {
  12126. return this._matrix;
  12127. };
  12128. Bone.prototype.getBaseMatrix = function () {
  12129. return this._baseMatrix;
  12130. };
  12131. Bone.prototype.getWorldMatrix = function () {
  12132. return this._worldTransform;
  12133. };
  12134. Bone.prototype.getInvertedAbsoluteTransform = function () {
  12135. return this._invertedAbsoluteTransform;
  12136. };
  12137. Bone.prototype.getAbsoluteMatrix = function () {
  12138. var matrix = this._matrix.clone();
  12139. var parent = this._parent;
  12140. while (parent) {
  12141. matrix = matrix.multiply(parent.getLocalMatrix());
  12142. parent = parent.getParent();
  12143. }
  12144. return matrix;
  12145. };
  12146. Bone.prototype.updateMatrix = function (matrix) {
  12147. this._matrix = matrix;
  12148. this._skeleton._markAsDirty();
  12149. this._updateDifferenceMatrix();
  12150. };
  12151. Bone.prototype._updateDifferenceMatrix = function () {
  12152. if (this._parent) {
  12153. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  12154. } else {
  12155. this._absoluteTransform.copyFrom(this._matrix);
  12156. }
  12157. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  12158. for (var index = 0; index < this.children.length; index++) {
  12159. this.children[index]._updateDifferenceMatrix();
  12160. }
  12161. };
  12162. Bone.prototype.markAsDirty = function () {
  12163. this._skeleton._markAsDirty();
  12164. };
  12165. return Bone;
  12166. })();
  12167. BABYLON.Bone = Bone;
  12168. })(BABYLON || (BABYLON = {}));
  12169. var BABYLON;
  12170. (function (BABYLON) {
  12171. var Skeleton = (function () {
  12172. function Skeleton(name, id, scene) {
  12173. this.name = name;
  12174. this.id = id;
  12175. this.bones = new Array();
  12176. this._isDirty = true;
  12177. this._identity = BABYLON.Matrix.Identity();
  12178. this.bones = [];
  12179. this._scene = scene;
  12180. scene.skeletons.push(this);
  12181. }
  12182. Skeleton.prototype.getTransformMatrices = function () {
  12183. return this._transformMatrices;
  12184. };
  12185. Skeleton.prototype._markAsDirty = function () {
  12186. this._isDirty = true;
  12187. };
  12188. Skeleton.prototype.prepare = function () {
  12189. if (!this._isDirty) {
  12190. return;
  12191. }
  12192. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  12193. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  12194. }
  12195. for (var index = 0; index < this.bones.length; index++) {
  12196. var bone = this.bones[index];
  12197. var parentBone = bone.getParent();
  12198. if (parentBone) {
  12199. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  12200. } else {
  12201. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  12202. }
  12203. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  12204. }
  12205. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  12206. this._isDirty = false;
  12207. };
  12208. Skeleton.prototype.getAnimatables = function () {
  12209. if (!this._animatables || this._animatables.length != this.bones.length) {
  12210. this._animatables = [];
  12211. for (var index = 0; index < this.bones.length; index++) {
  12212. this._animatables.push(this.bones[index]);
  12213. }
  12214. }
  12215. return this._animatables;
  12216. };
  12217. Skeleton.prototype.clone = function (name, id) {
  12218. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  12219. for (var index = 0; index < this.bones.length; index++) {
  12220. var source = this.bones[index];
  12221. var parentBone = null;
  12222. if (source.getParent()) {
  12223. var parentIndex = this.bones.indexOf(source.getParent());
  12224. parentBone = result.bones[parentIndex];
  12225. }
  12226. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  12227. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  12228. }
  12229. return result;
  12230. };
  12231. return Skeleton;
  12232. })();
  12233. BABYLON.Skeleton = Skeleton;
  12234. })(BABYLON || (BABYLON = {}));
  12235. var BABYLON;
  12236. (function (BABYLON) {
  12237. var PostProcess = (function () {
  12238. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  12239. this.name = name;
  12240. this.width = -1;
  12241. this.height = -1;
  12242. this._reusable = false;
  12243. this._textures = new BABYLON.SmartArray(2);
  12244. this._currentRenderTextureInd = 0;
  12245. if (camera != null) {
  12246. this._camera = camera;
  12247. this._scene = camera.getScene();
  12248. camera.attachPostProcess(this);
  12249. this._engine = this._scene.getEngine();
  12250. } else {
  12251. this._engine = engine;
  12252. }
  12253. this._renderRatio = ratio;
  12254. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12255. this._reusable = reusable || false;
  12256. samplers = samplers || [];
  12257. samplers.push("textureSampler");
  12258. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  12259. }
  12260. PostProcess.prototype.isReusable = function () {
  12261. return this._reusable;
  12262. };
  12263. PostProcess.prototype.activate = function (camera, sourceTexture) {
  12264. camera = camera || this._camera;
  12265. var scene = camera.getScene();
  12266. var desiredWidth = (sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio;
  12267. var desiredHeight = (sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio;
  12268. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  12269. if (this._textures.length > 0) {
  12270. for (var i = 0; i < this._textures.length; i++) {
  12271. this._engine._releaseTexture(this._textures.data[i]);
  12272. }
  12273. this._textures.reset();
  12274. }
  12275. this.width = desiredWidth;
  12276. this.height = desiredHeight;
  12277. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === camera._postProcessesTakenIndices[0], samplingMode: this.renderTargetSamplingMode }));
  12278. if (this._reusable) {
  12279. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === camera._postProcessesTakenIndices[0], samplingMode: this.renderTargetSamplingMode }));
  12280. }
  12281. if (this.onSizeChanged) {
  12282. this.onSizeChanged();
  12283. }
  12284. }
  12285. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  12286. if (this.onActivate) {
  12287. this.onActivate(camera);
  12288. }
  12289. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  12290. if (this._reusable) {
  12291. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  12292. }
  12293. };
  12294. PostProcess.prototype.apply = function () {
  12295. if (!this._effect.isReady())
  12296. return null;
  12297. this._engine.enableEffect(this._effect);
  12298. this._engine.setState(false);
  12299. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12300. this._engine.setDepthBuffer(false);
  12301. this._engine.setDepthWrite(false);
  12302. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  12303. if (this.onApply) {
  12304. this.onApply(this._effect);
  12305. }
  12306. return this._effect;
  12307. };
  12308. PostProcess.prototype.dispose = function (camera) {
  12309. camera = camera || this._camera;
  12310. if (this._textures.length > 0) {
  12311. for (var i = 0; i < this._textures.length; i++) {
  12312. this._engine._releaseTexture(this._textures.data[i]);
  12313. }
  12314. this._textures.reset();
  12315. }
  12316. camera.detachPostProcess(this);
  12317. var index = camera._postProcesses.indexOf(this);
  12318. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  12319. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1;
  12320. }
  12321. };
  12322. return PostProcess;
  12323. })();
  12324. BABYLON.PostProcess = PostProcess;
  12325. })(BABYLON || (BABYLON = {}));
  12326. var BABYLON;
  12327. (function (BABYLON) {
  12328. var PostProcessManager = (function () {
  12329. function PostProcessManager(scene) {
  12330. this._vertexDeclaration = [2];
  12331. this._vertexStrideSize = 2 * 4;
  12332. this._scene = scene;
  12333. var vertices = [];
  12334. vertices.push(1, 1);
  12335. vertices.push(-1, 1);
  12336. vertices.push(-1, -1);
  12337. vertices.push(1, -1);
  12338. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12339. var indices = [];
  12340. indices.push(0);
  12341. indices.push(1);
  12342. indices.push(2);
  12343. indices.push(0);
  12344. indices.push(2);
  12345. indices.push(3);
  12346. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12347. }
  12348. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  12349. var postProcesses = this._scene.activeCamera._postProcesses;
  12350. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12351. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12352. return false;
  12353. }
  12354. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  12355. return true;
  12356. };
  12357. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  12358. var postProcesses = this._scene.activeCamera._postProcesses;
  12359. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12360. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12361. return;
  12362. }
  12363. var engine = this._scene.getEngine();
  12364. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  12365. if (index < postProcessesTakenIndices.length - 1) {
  12366. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  12367. } else {
  12368. if (targetTexture) {
  12369. engine.bindFramebuffer(targetTexture);
  12370. } else {
  12371. engine.restoreDefaultFramebuffer();
  12372. }
  12373. }
  12374. if (doNotPresent) {
  12375. break;
  12376. }
  12377. var effect = postProcesses[postProcessesTakenIndices[index]].apply();
  12378. if (effect) {
  12379. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12380. engine.draw(true, 0, 6);
  12381. }
  12382. }
  12383. engine.setDepthBuffer(true);
  12384. engine.setDepthWrite(true);
  12385. };
  12386. PostProcessManager.prototype.dispose = function () {
  12387. if (this._vertexBuffer) {
  12388. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12389. this._vertexBuffer = null;
  12390. }
  12391. if (this._indexBuffer) {
  12392. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12393. this._indexBuffer = null;
  12394. }
  12395. };
  12396. return PostProcessManager;
  12397. })();
  12398. BABYLON.PostProcessManager = PostProcessManager;
  12399. })(BABYLON || (BABYLON = {}));
  12400. var __extends = this.__extends || function (d, b) {
  12401. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12402. function __() { this.constructor = d; }
  12403. __.prototype = b.prototype;
  12404. d.prototype = new __();
  12405. };
  12406. var BABYLON;
  12407. (function (BABYLON) {
  12408. var PassPostProcess = (function (_super) {
  12409. __extends(PassPostProcess, _super);
  12410. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12411. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  12412. }
  12413. return PassPostProcess;
  12414. })(BABYLON.PostProcess);
  12415. BABYLON.PassPostProcess = PassPostProcess;
  12416. })(BABYLON || (BABYLON = {}));
  12417. var __extends = this.__extends || function (d, b) {
  12418. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12419. function __() { this.constructor = d; }
  12420. __.prototype = b.prototype;
  12421. d.prototype = new __();
  12422. };
  12423. var BABYLON;
  12424. (function (BABYLON) {
  12425. var BlurPostProcess = (function (_super) {
  12426. __extends(BlurPostProcess, _super);
  12427. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  12428. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  12429. var _this = this;
  12430. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  12431. this.direction = direction;
  12432. this.blurWidth = blurWidth;
  12433. this.onApply = function (effect) {
  12434. effect.setFloat2("screenSize", _this.width, _this.height);
  12435. effect.setVector2("direction", _this.direction);
  12436. effect.setFloat("blurWidth", _this.blurWidth);
  12437. };
  12438. }
  12439. return BlurPostProcess;
  12440. })(BABYLON.PostProcess);
  12441. BABYLON.BlurPostProcess = BlurPostProcess;
  12442. })(BABYLON || (BABYLON = {}));
  12443. var __extends = this.__extends || function (d, b) {
  12444. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12445. function __() { this.constructor = d; }
  12446. __.prototype = b.prototype;
  12447. d.prototype = new __();
  12448. };
  12449. var BABYLON;
  12450. (function (BABYLON) {
  12451. var FilterPostProcess = (function (_super) {
  12452. __extends(FilterPostProcess, _super);
  12453. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  12454. var _this = this;
  12455. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  12456. this.kernelMatrix = kernelMatrix;
  12457. this.onApply = function (effect) {
  12458. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  12459. };
  12460. }
  12461. return FilterPostProcess;
  12462. })(BABYLON.PostProcess);
  12463. BABYLON.FilterPostProcess = FilterPostProcess;
  12464. })(BABYLON || (BABYLON = {}));
  12465. var __extends = this.__extends || function (d, b) {
  12466. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12467. function __() { this.constructor = d; }
  12468. __.prototype = b.prototype;
  12469. d.prototype = new __();
  12470. };
  12471. var BABYLON;
  12472. (function (BABYLON) {
  12473. var RefractionPostProcess = (function (_super) {
  12474. __extends(RefractionPostProcess, _super);
  12475. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  12476. var _this = this;
  12477. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  12478. this.color = color;
  12479. this.depth = depth;
  12480. this.colorLevel = colorLevel;
  12481. this.onActivate = function (cam) {
  12482. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  12483. };
  12484. this.onApply = function (effect) {
  12485. effect.setColor3("baseColor", _this.color);
  12486. effect.setFloat("depth", _this.depth);
  12487. effect.setFloat("colorLevel", _this.colorLevel);
  12488. effect.setTexture("refractionSampler", _this._refRexture);
  12489. };
  12490. }
  12491. RefractionPostProcess.prototype.dispose = function (camera) {
  12492. if (this._refRexture) {
  12493. this._refRexture.dispose();
  12494. }
  12495. _super.prototype.dispose.call(this, camera);
  12496. };
  12497. return RefractionPostProcess;
  12498. })(BABYLON.PostProcess);
  12499. BABYLON.RefractionPostProcess = RefractionPostProcess;
  12500. })(BABYLON || (BABYLON = {}));
  12501. var __extends = this.__extends || function (d, b) {
  12502. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12503. function __() { this.constructor = d; }
  12504. __.prototype = b.prototype;
  12505. d.prototype = new __();
  12506. };
  12507. var BABYLON;
  12508. (function (BABYLON) {
  12509. var BlackAndWhitePostProcess = (function (_super) {
  12510. __extends(BlackAndWhitePostProcess, _super);
  12511. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12512. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  12513. }
  12514. return BlackAndWhitePostProcess;
  12515. })(BABYLON.PostProcess);
  12516. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  12517. })(BABYLON || (BABYLON = {}));
  12518. var __extends = this.__extends || function (d, b) {
  12519. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12520. function __() { this.constructor = d; }
  12521. __.prototype = b.prototype;
  12522. d.prototype = new __();
  12523. };
  12524. var BABYLON;
  12525. (function (BABYLON) {
  12526. var ConvolutionPostProcess = (function (_super) {
  12527. __extends(ConvolutionPostProcess, _super);
  12528. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  12529. var _this = this;
  12530. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  12531. this.kernel = kernel;
  12532. this.onApply = function (effect) {
  12533. effect.setFloat2("screenSize", _this.width, _this.height);
  12534. effect.setArray("kernel", _this.kernel);
  12535. };
  12536. }
  12537. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  12538. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  12539. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  12540. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  12541. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  12542. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  12543. return ConvolutionPostProcess;
  12544. })(BABYLON.PostProcess);
  12545. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  12546. })(BABYLON || (BABYLON = {}));
  12547. var __extends = this.__extends || function (d, b) {
  12548. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12549. function __() { this.constructor = d; }
  12550. __.prototype = b.prototype;
  12551. d.prototype = new __();
  12552. };
  12553. var BABYLON;
  12554. (function (BABYLON) {
  12555. var FxaaPostProcess = (function (_super) {
  12556. __extends(FxaaPostProcess, _super);
  12557. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12558. var _this = this;
  12559. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  12560. this.onSizeChanged = function () {
  12561. _this.texelWidth = 1.0 / _this.width;
  12562. _this.texelHeight = 1.0 / _this.height;
  12563. };
  12564. this.onApply = function (effect) {
  12565. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  12566. };
  12567. }
  12568. return FxaaPostProcess;
  12569. })(BABYLON.PostProcess);
  12570. BABYLON.FxaaPostProcess = FxaaPostProcess;
  12571. })(BABYLON || (BABYLON = {}));
  12572. var BABYLON;
  12573. (function (BABYLON) {
  12574. var LensFlare = (function () {
  12575. function LensFlare(size, position, color, imgUrl, system) {
  12576. this.size = size;
  12577. this.position = position;
  12578. this.dispose = function () {
  12579. if (this.texture) {
  12580. this.texture.dispose();
  12581. }
  12582. var index = this._system.lensFlares.indexOf(this);
  12583. this._system.lensFlares.splice(index, 1);
  12584. };
  12585. this.color = color || new BABYLON.Color3(1, 1, 1);
  12586. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  12587. this._system = system;
  12588. system.lensFlares.push(this);
  12589. }
  12590. return LensFlare;
  12591. })();
  12592. BABYLON.LensFlare = LensFlare;
  12593. })(BABYLON || (BABYLON = {}));
  12594. var BABYLON;
  12595. (function (BABYLON) {
  12596. var LensFlareSystem = (function () {
  12597. function LensFlareSystem(name, emitter, scene) {
  12598. this.name = name;
  12599. this.lensFlares = new Array();
  12600. this.borderLimit = 300;
  12601. this._vertexDeclaration = [2];
  12602. this._vertexStrideSize = 2 * 4;
  12603. this._isEnabled = true;
  12604. this._scene = scene;
  12605. this._emitter = emitter;
  12606. scene.lensFlareSystems.push(this);
  12607. this.meshesSelectionPredicate = function (m) {
  12608. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  12609. };
  12610. var vertices = [];
  12611. vertices.push(1, 1);
  12612. vertices.push(-1, 1);
  12613. vertices.push(-1, -1);
  12614. vertices.push(1, -1);
  12615. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12616. var indices = [];
  12617. indices.push(0);
  12618. indices.push(1);
  12619. indices.push(2);
  12620. indices.push(0);
  12621. indices.push(2);
  12622. indices.push(3);
  12623. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12624. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  12625. }
  12626. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  12627. get: function () {
  12628. return this._isEnabled;
  12629. },
  12630. set: function (value) {
  12631. this._isEnabled = value;
  12632. },
  12633. enumerable: true,
  12634. configurable: true
  12635. });
  12636. LensFlareSystem.prototype.getScene = function () {
  12637. return this._scene;
  12638. };
  12639. LensFlareSystem.prototype.getEmitter = function () {
  12640. return this._emitter;
  12641. };
  12642. LensFlareSystem.prototype.getEmitterPosition = function () {
  12643. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  12644. };
  12645. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  12646. var position = this.getEmitterPosition();
  12647. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  12648. this._positionX = position.x;
  12649. this._positionY = position.y;
  12650. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  12651. if (position.z > 0) {
  12652. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  12653. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  12654. return true;
  12655. }
  12656. }
  12657. return false;
  12658. };
  12659. LensFlareSystem.prototype._isVisible = function () {
  12660. if (!this._isEnabled) {
  12661. return false;
  12662. }
  12663. var emitterPosition = this.getEmitterPosition();
  12664. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  12665. var distance = direction.length();
  12666. direction.normalize();
  12667. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  12668. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  12669. return !pickInfo.hit || pickInfo.distance > distance;
  12670. };
  12671. LensFlareSystem.prototype.render = function () {
  12672. if (!this._effect.isReady())
  12673. return false;
  12674. var engine = this._scene.getEngine();
  12675. var viewport = this._scene.activeCamera.viewport;
  12676. var globalViewport = viewport.toGlobal(engine);
  12677. if (!this.computeEffectivePosition(globalViewport)) {
  12678. return false;
  12679. }
  12680. if (!this._isVisible()) {
  12681. return false;
  12682. }
  12683. var awayX;
  12684. var awayY;
  12685. if (this._positionX < this.borderLimit + globalViewport.x) {
  12686. awayX = this.borderLimit + globalViewport.x - this._positionX;
  12687. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  12688. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  12689. } else {
  12690. awayX = 0;
  12691. }
  12692. if (this._positionY < this.borderLimit + globalViewport.y) {
  12693. awayY = this.borderLimit + globalViewport.y - this._positionY;
  12694. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  12695. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  12696. } else {
  12697. awayY = 0;
  12698. }
  12699. var away = (awayX > awayY) ? awayX : awayY;
  12700. if (away > this.borderLimit) {
  12701. away = this.borderLimit;
  12702. }
  12703. var intensity = 1.0 - (away / this.borderLimit);
  12704. if (intensity < 0) {
  12705. return false;
  12706. }
  12707. if (intensity > 1.0) {
  12708. intensity = 1.0;
  12709. }
  12710. var centerX = globalViewport.x + globalViewport.width / 2;
  12711. var centerY = globalViewport.y + globalViewport.height / 2;
  12712. var distX = centerX - this._positionX;
  12713. var distY = centerY - this._positionY;
  12714. engine.enableEffect(this._effect);
  12715. engine.setState(false);
  12716. engine.setDepthBuffer(false);
  12717. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  12718. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12719. for (var index = 0; index < this.lensFlares.length; index++) {
  12720. var flare = this.lensFlares[index];
  12721. var x = centerX - (distX * flare.position);
  12722. var y = centerY - (distY * flare.position);
  12723. var cw = flare.size;
  12724. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  12725. var cx = 2 * (x / globalViewport.width) - 1.0;
  12726. var cy = 1.0 - 2 * (y / globalViewport.height);
  12727. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  12728. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  12729. this._effect.setTexture("textureSampler", flare.texture);
  12730. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  12731. engine.draw(true, 0, 6);
  12732. }
  12733. engine.setDepthBuffer(true);
  12734. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12735. return true;
  12736. };
  12737. LensFlareSystem.prototype.dispose = function () {
  12738. if (this._vertexBuffer) {
  12739. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12740. this._vertexBuffer = null;
  12741. }
  12742. if (this._indexBuffer) {
  12743. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12744. this._indexBuffer = null;
  12745. }
  12746. while (this.lensFlares.length) {
  12747. this.lensFlares[0].dispose();
  12748. }
  12749. var index = this._scene.lensFlareSystems.indexOf(this);
  12750. this._scene.lensFlareSystems.splice(index, 1);
  12751. };
  12752. return LensFlareSystem;
  12753. })();
  12754. BABYLON.LensFlareSystem = LensFlareSystem;
  12755. })(BABYLON || (BABYLON = {}));
  12756. var BABYLON;
  12757. (function (BABYLON) {
  12758. var IntersectionInfo = (function () {
  12759. function IntersectionInfo(bu, bv, distance) {
  12760. this.bu = bu;
  12761. this.bv = bv;
  12762. this.distance = distance;
  12763. this.faceId = 0;
  12764. }
  12765. return IntersectionInfo;
  12766. })();
  12767. BABYLON.IntersectionInfo = IntersectionInfo;
  12768. var PickingInfo = (function () {
  12769. function PickingInfo() {
  12770. this.hit = false;
  12771. this.distance = 0;
  12772. this.pickedPoint = null;
  12773. this.pickedMesh = null;
  12774. this.bu = 0;
  12775. this.bv = 0;
  12776. this.faceId = -1;
  12777. }
  12778. PickingInfo.prototype.getNormal = function () {
  12779. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  12780. return null;
  12781. }
  12782. var indices = this.pickedMesh.getIndices();
  12783. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12784. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  12785. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  12786. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  12787. normal0 = normal0.scale(this.bu);
  12788. normal1 = normal1.scale(this.bv);
  12789. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  12790. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  12791. };
  12792. PickingInfo.prototype.getTextureCoordinates = function () {
  12793. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12794. return null;
  12795. }
  12796. var indices = this.pickedMesh.getIndices();
  12797. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  12798. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  12799. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  12800. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  12801. uv0 = uv0.scale(this.bu);
  12802. uv1 = uv1.scale(this.bv);
  12803. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  12804. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  12805. };
  12806. return PickingInfo;
  12807. })();
  12808. BABYLON.PickingInfo = PickingInfo;
  12809. })(BABYLON || (BABYLON = {}));
  12810. var BABYLON;
  12811. (function (BABYLON) {
  12812. var FilesInput = (function () {
  12813. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  12814. this.engine = p_engine;
  12815. this.canvas = p_canvas;
  12816. this.currentScene = p_scene;
  12817. this.sceneLoadedCallback = p_sceneLoadedCallback;
  12818. this.progressCallback = p_progressCallback;
  12819. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  12820. this.textureLoadingCallback = p_textureLoadingCallback;
  12821. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  12822. }
  12823. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  12824. var _this = this;
  12825. if (p_elementToMonitor) {
  12826. this.elementToMonitor = p_elementToMonitor;
  12827. this.elementToMonitor.addEventListener("dragenter", function (e) {
  12828. _this.drag(e);
  12829. }, false);
  12830. this.elementToMonitor.addEventListener("dragover", function (e) {
  12831. _this.drag(e);
  12832. }, false);
  12833. this.elementToMonitor.addEventListener("drop", function (e) {
  12834. _this.drop(e);
  12835. }, false);
  12836. }
  12837. };
  12838. FilesInput.prototype.renderFunction = function () {
  12839. if (this.additionnalRenderLoopLogicCallback) {
  12840. this.additionnalRenderLoopLogicCallback();
  12841. }
  12842. if (this.currentScene) {
  12843. if (this.textureLoadingCallback) {
  12844. var remaining = this.currentScene.getWaitingItemsCount();
  12845. if (remaining > 0) {
  12846. this.textureLoadingCallback(remaining);
  12847. }
  12848. }
  12849. this.currentScene.render();
  12850. }
  12851. };
  12852. FilesInput.prototype.drag = function (e) {
  12853. e.stopPropagation();
  12854. e.preventDefault();
  12855. };
  12856. FilesInput.prototype.drop = function (eventDrop) {
  12857. eventDrop.stopPropagation();
  12858. eventDrop.preventDefault();
  12859. this.loadFiles(eventDrop);
  12860. };
  12861. FilesInput.prototype.loadFiles = function (event) {
  12862. var _this = this;
  12863. var that = this;
  12864. if (this.startingProcessingFilesCallback)
  12865. this.startingProcessingFilesCallback();
  12866. var sceneFileToLoad;
  12867. var filesToLoad;
  12868. if (event && event.dataTransfer && event.dataTransfer.files) {
  12869. filesToLoad = event.dataTransfer.files;
  12870. }
  12871. if (event && event.target && event.target.files) {
  12872. filesToLoad = event.target.files;
  12873. }
  12874. if (filesToLoad && filesToLoad.length > 0) {
  12875. for (var i = 0; i < filesToLoad.length; i++) {
  12876. switch (filesToLoad[i].type) {
  12877. case "image/jpeg":
  12878. case "image/png":
  12879. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  12880. break;
  12881. case "image/targa":
  12882. case "image/vnd.ms-dds":
  12883. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  12884. break;
  12885. default:
  12886. if (filesToLoad[i].name.indexOf(".babylon") !== -1 && filesToLoad[i].name.indexOf(".manifest") === -1 && filesToLoad[i].name.indexOf(".incremental") === -1 && filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  12887. sceneFileToLoad = filesToLoad[i];
  12888. }
  12889. break;
  12890. }
  12891. }
  12892. if (sceneFileToLoad) {
  12893. if (this.currentScene) {
  12894. this.engine.stopRenderLoop();
  12895. this.currentScene.dispose();
  12896. }
  12897. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  12898. that.currentScene = newScene;
  12899. that.currentScene.executeWhenReady(function () {
  12900. if (that.currentScene.activeCamera) {
  12901. that.currentScene.activeCamera.attachControl(that.canvas);
  12902. }
  12903. if (that.sceneLoadedCallback) {
  12904. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  12905. }
  12906. that.engine.runRenderLoop(function () {
  12907. that.renderFunction();
  12908. });
  12909. });
  12910. }, function (progress) {
  12911. if (_this.progressCallback) {
  12912. _this.progressCallback(progress);
  12913. }
  12914. });
  12915. } else {
  12916. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  12917. }
  12918. }
  12919. };
  12920. FilesInput.FilesTextures = new Array();
  12921. FilesInput.FilesToLoad = new Array();
  12922. return FilesInput;
  12923. })();
  12924. BABYLON.FilesInput = FilesInput;
  12925. })(BABYLON || (BABYLON = {}));
  12926. var BABYLON;
  12927. (function (BABYLON) {
  12928. var OimoJSPlugin = (function () {
  12929. function OimoJSPlugin() {
  12930. this._registeredMeshes = [];
  12931. /**
  12932. * Update the body position according to the mesh position
  12933. * @param mesh
  12934. */
  12935. this.updateBodyPosition = function (mesh) {
  12936. for (var index = 0; index < this._registeredMeshes.length; index++) {
  12937. var registeredMesh = this._registeredMeshes[index];
  12938. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  12939. var body = registeredMesh.body.body;
  12940. var center = mesh.getBoundingInfo().boundingBox.center;
  12941. body.setPosition(center.x, center.y, center.z);
  12942. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  12943. return;
  12944. }
  12945. if (registeredMesh.mesh.parent === mesh) {
  12946. mesh.computeWorldMatrix(true);
  12947. registeredMesh.mesh.computeWorldMatrix(true);
  12948. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  12949. var absoluteRotation = mesh.rotation;
  12950. body = registeredMesh.body.body;
  12951. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  12952. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  12953. return;
  12954. }
  12955. }
  12956. };
  12957. }
  12958. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  12959. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  12960. };
  12961. OimoJSPlugin.prototype.initialize = function (iterations) {
  12962. this._world = new OIMO.World();
  12963. this._world.clear();
  12964. };
  12965. OimoJSPlugin.prototype.setGravity = function (gravity) {
  12966. this._world.gravity = gravity;
  12967. };
  12968. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  12969. var body = null;
  12970. this.unregisterMesh(mesh);
  12971. mesh.computeWorldMatrix(true);
  12972. switch (impostor) {
  12973. case BABYLON.PhysicsEngine.SphereImpostor:
  12974. var bbox = mesh.getBoundingInfo().boundingBox;
  12975. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  12976. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  12977. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  12978. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  12979. var deltaPosition = mesh.position.subtract(bbox.center);
  12980. body = new OIMO.Body({
  12981. type: 'sphere',
  12982. size: [size],
  12983. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  12984. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  12985. move: options.mass != 0,
  12986. config: [options.mass, options.friction, options.restitution],
  12987. world: this._world
  12988. });
  12989. this._registeredMeshes.push({
  12990. mesh: mesh,
  12991. body: body,
  12992. delta: deltaPosition
  12993. });
  12994. break;
  12995. case BABYLON.PhysicsEngine.PlaneImpostor:
  12996. case BABYLON.PhysicsEngine.BoxImpostor:
  12997. bbox = mesh.getBoundingInfo().boundingBox;
  12998. var min = bbox.minimumWorld;
  12999. var max = bbox.maximumWorld;
  13000. var box = max.subtract(min);
  13001. var sizeX = this._checkWithEpsilon(box.x);
  13002. var sizeY = this._checkWithEpsilon(box.y);
  13003. var sizeZ = this._checkWithEpsilon(box.z);
  13004. var deltaPosition = mesh.position.subtract(bbox.center);
  13005. body = new OIMO.Body({
  13006. type: 'box',
  13007. size: [sizeX, sizeY, sizeZ],
  13008. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  13009. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  13010. move: options.mass != 0,
  13011. config: [options.mass, options.friction, options.restitution],
  13012. world: this._world
  13013. });
  13014. this._registeredMeshes.push({
  13015. mesh: mesh,
  13016. body: body,
  13017. delta: deltaPosition
  13018. });
  13019. break;
  13020. }
  13021. return body;
  13022. };
  13023. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  13024. var types = [], sizes = [], positions = [], rotations = [];
  13025. var initialMesh = parts[0].mesh;
  13026. for (var index = 0; index < parts.length; index++) {
  13027. var part = parts[index];
  13028. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  13029. types.push(bodyParameters.type);
  13030. sizes.push.apply(sizes, bodyParameters.size);
  13031. positions.push.apply(positions, bodyParameters.pos);
  13032. rotations.push.apply(rotations, bodyParameters.rot);
  13033. }
  13034. var body = new OIMO.Body({
  13035. type: types,
  13036. size: sizes,
  13037. pos: positions,
  13038. rot: rotations,
  13039. move: options.mass != 0,
  13040. config: [options.mass, options.friction, options.restitution],
  13041. world: this._world
  13042. });
  13043. this._registeredMeshes.push({
  13044. mesh: initialMesh,
  13045. body: body
  13046. });
  13047. return body;
  13048. };
  13049. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  13050. var bodyParameters = null;
  13051. var mesh = part.mesh;
  13052. switch (part.impostor) {
  13053. case BABYLON.PhysicsEngine.SphereImpostor:
  13054. var bbox = mesh.getBoundingInfo().boundingBox;
  13055. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  13056. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  13057. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  13058. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  13059. bodyParameters = {
  13060. type: 'sphere',
  13061. /* bug with oimo : sphere needs 3 sizes in this case */
  13062. size: [size, -1, -1],
  13063. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  13064. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  13065. };
  13066. break;
  13067. case BABYLON.PhysicsEngine.PlaneImpostor:
  13068. case BABYLON.PhysicsEngine.BoxImpostor:
  13069. bbox = mesh.getBoundingInfo().boundingBox;
  13070. var min = bbox.minimumWorld;
  13071. var max = bbox.maximumWorld;
  13072. var box = max.subtract(min);
  13073. var sizeX = this._checkWithEpsilon(box.x);
  13074. var sizeY = this._checkWithEpsilon(box.y);
  13075. var sizeZ = this._checkWithEpsilon(box.z);
  13076. var relativePosition = mesh.position;
  13077. bodyParameters = {
  13078. type: 'box',
  13079. size: [sizeX, sizeY, sizeZ],
  13080. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  13081. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  13082. };
  13083. break;
  13084. }
  13085. return bodyParameters;
  13086. };
  13087. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  13088. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13089. var registeredMesh = this._registeredMeshes[index];
  13090. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13091. if (registeredMesh.body) {
  13092. this._world.removeRigidBody(registeredMesh.body.body);
  13093. this._unbindBody(registeredMesh.body);
  13094. }
  13095. this._registeredMeshes.splice(index, 1);
  13096. return;
  13097. }
  13098. }
  13099. };
  13100. OimoJSPlugin.prototype._unbindBody = function (body) {
  13101. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13102. var registeredMesh = this._registeredMeshes[index];
  13103. if (registeredMesh.body === body) {
  13104. registeredMesh.body = null;
  13105. }
  13106. }
  13107. };
  13108. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  13109. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13110. var registeredMesh = this._registeredMeshes[index];
  13111. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13112. var mass = registeredMesh.body.body.massInfo.mass;
  13113. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  13114. return;
  13115. }
  13116. }
  13117. };
  13118. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13119. var body1 = null, body2 = null;
  13120. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13121. var registeredMesh = this._registeredMeshes[index];
  13122. if (registeredMesh.mesh === mesh1) {
  13123. body1 = registeredMesh.body.body;
  13124. } else if (registeredMesh.mesh === mesh2) {
  13125. body2 = registeredMesh.body.body;
  13126. }
  13127. }
  13128. if (!body1 || !body2) {
  13129. return false;
  13130. }
  13131. if (!options) {
  13132. options = {};
  13133. }
  13134. new OIMO.Link({
  13135. type: options.type,
  13136. body1: body1,
  13137. body2: body2,
  13138. min: options.min,
  13139. max: options.max,
  13140. axe1: options.axe1,
  13141. axe2: options.axe2,
  13142. pos1: [pivot1.x, pivot1.y, pivot1.z],
  13143. pos2: [pivot2.x, pivot2.y, pivot2.z],
  13144. collision: options.collision,
  13145. spring: options.spring,
  13146. world: this._world
  13147. });
  13148. return true;
  13149. };
  13150. OimoJSPlugin.prototype.dispose = function () {
  13151. this._world.clear();
  13152. while (this._registeredMeshes.length) {
  13153. this.unregisterMesh(this._registeredMeshes[0].mesh);
  13154. }
  13155. };
  13156. OimoJSPlugin.prototype.isSupported = function () {
  13157. return OIMO !== undefined;
  13158. };
  13159. OimoJSPlugin.prototype._getLastShape = function (body) {
  13160. var lastShape = body.shapes;
  13161. while (lastShape.next) {
  13162. lastShape = lastShape.next;
  13163. }
  13164. return lastShape;
  13165. };
  13166. OimoJSPlugin.prototype.runOneStep = function (time) {
  13167. this._world.step();
  13168. var i = this._registeredMeshes.length;
  13169. var m;
  13170. while (i--) {
  13171. var body = this._registeredMeshes[i].body.body;
  13172. var mesh = this._registeredMeshes[i].mesh;
  13173. var delta = this._registeredMeshes[i].delta;
  13174. if (!body.sleeping) {
  13175. if (body.shapes.next) {
  13176. var parentShape = this._getLastShape(body);
  13177. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  13178. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  13179. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  13180. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  13181. if (!mesh.rotationQuaternion) {
  13182. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13183. }
  13184. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13185. } else {
  13186. m = body.getMatrix();
  13187. mtx = BABYLON.Matrix.FromArray(m);
  13188. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  13189. if (!delta) {
  13190. mesh.position.x = bodyX;
  13191. mesh.position.y = bodyY;
  13192. mesh.position.z = bodyZ;
  13193. } else {
  13194. mesh.position.x = bodyX + delta.x;
  13195. mesh.position.y = bodyY + delta.y;
  13196. mesh.position.z = bodyZ + delta.z;
  13197. }
  13198. if (!mesh.rotationQuaternion) {
  13199. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13200. }
  13201. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13202. }
  13203. }
  13204. }
  13205. };
  13206. return OimoJSPlugin;
  13207. })();
  13208. BABYLON.OimoJSPlugin = OimoJSPlugin;
  13209. })(BABYLON || (BABYLON = {}));
  13210. var BABYLON;
  13211. (function (BABYLON) {
  13212. var PhysicsEngine = (function () {
  13213. function PhysicsEngine(plugin) {
  13214. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  13215. }
  13216. PhysicsEngine.prototype._initialize = function (gravity) {
  13217. this._currentPlugin.initialize();
  13218. this._setGravity(gravity);
  13219. };
  13220. PhysicsEngine.prototype._runOneStep = function (delta) {
  13221. if (delta > 0.1) {
  13222. delta = 0.1;
  13223. } else if (delta <= 0) {
  13224. delta = 1.0 / 60.0;
  13225. }
  13226. this._currentPlugin.runOneStep(delta);
  13227. };
  13228. PhysicsEngine.prototype._setGravity = function (gravity) {
  13229. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  13230. this._currentPlugin.setGravity(this.gravity);
  13231. };
  13232. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  13233. return this._currentPlugin.registerMesh(mesh, impostor, options);
  13234. };
  13235. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  13236. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  13237. };
  13238. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  13239. this._currentPlugin.unregisterMesh(mesh);
  13240. };
  13241. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  13242. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  13243. };
  13244. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13245. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  13246. };
  13247. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  13248. this._currentPlugin.updateBodyPosition(mesh);
  13249. };
  13250. PhysicsEngine.prototype.dispose = function () {
  13251. this._currentPlugin.dispose();
  13252. };
  13253. PhysicsEngine.prototype.isSupported = function () {
  13254. return this._currentPlugin.isSupported();
  13255. };
  13256. PhysicsEngine.NoImpostor = 0;
  13257. PhysicsEngine.SphereImpostor = 1;
  13258. PhysicsEngine.BoxImpostor = 2;
  13259. PhysicsEngine.PlaneImpostor = 3;
  13260. PhysicsEngine.CompoundImpostor = 4;
  13261. PhysicsEngine.MeshImpostor = 4;
  13262. PhysicsEngine.CapsuleImpostor = 5;
  13263. PhysicsEngine.ConeImpostor = 6;
  13264. PhysicsEngine.CylinderImpostor = 7;
  13265. PhysicsEngine.ConvexHullImpostor = 8;
  13266. PhysicsEngine.Epsilon = 0.001;
  13267. return PhysicsEngine;
  13268. })();
  13269. BABYLON.PhysicsEngine = PhysicsEngine;
  13270. })(BABYLON || (BABYLON = {}));
  13271. var BABYLON;
  13272. (function (BABYLON) {
  13273. var serializeLight = function (light) {
  13274. var serializationObject = {};
  13275. serializationObject.name = light.name;
  13276. serializationObject.id = light.id;
  13277. serializationObject.tags = BABYLON.Tags.GetTags(light);
  13278. if (light instanceof BABYLON.PointLight) {
  13279. serializationObject.type = 0;
  13280. serializationObject.position = light.position.asArray();
  13281. } else if (light instanceof BABYLON.DirectionalLight) {
  13282. serializationObject.type = 1;
  13283. var directionalLight = light;
  13284. serializationObject.position = directionalLight.position.asArray();
  13285. serializationObject.direction = directionalLight.direction.asArray();
  13286. } else if (light instanceof BABYLON.SpotLight) {
  13287. serializationObject.type = 2;
  13288. var spotLight = light;
  13289. serializationObject.position = spotLight.position.asArray();
  13290. serializationObject.direction = spotLight.position.asArray();
  13291. serializationObject.angle = spotLight.angle;
  13292. serializationObject.exponent = spotLight.exponent;
  13293. } else if (light instanceof BABYLON.HemisphericLight) {
  13294. serializationObject.type = 3;
  13295. var hemisphericLight = light;
  13296. serializationObject.direction = hemisphericLight.direction.asArray();
  13297. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  13298. }
  13299. if (light.intensity) {
  13300. serializationObject.intensity = light.intensity;
  13301. }
  13302. serializationObject.range = light.range;
  13303. serializationObject.diffuse = light.diffuse.asArray();
  13304. serializationObject.specular = light.specular.asArray();
  13305. return serializationObject;
  13306. };
  13307. var serializeFresnelParameter = function (fresnelParameter) {
  13308. var serializationObject = {};
  13309. serializationObject.isEnabled = fresnelParameter.isEnabled;
  13310. serializationObject.leftColor = fresnelParameter.leftColor;
  13311. serializationObject.rightColor = fresnelParameter.rightColor;
  13312. serializationObject.bias = fresnelParameter.bias;
  13313. serializationObject.power = fresnelParameter.power;
  13314. return serializationObject;
  13315. };
  13316. var serializeCamera = function (camera) {
  13317. var serializationObject = {};
  13318. serializationObject.name = camera.name;
  13319. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  13320. serializationObject.id = camera.id;
  13321. serializationObject.position = camera.position.asArray();
  13322. if (camera.parent) {
  13323. serializationObject.parentId = camera.parent.id;
  13324. }
  13325. serializationObject.rotation = camera.rotation.asArray();
  13326. if (camera.lockedTarget && camera.lockedTarget.id) {
  13327. serializationObject.lockedTargetId = camera.lockedTarget.id;
  13328. }
  13329. serializationObject.fov = camera.fov;
  13330. serializationObject.minZ = camera.minZ;
  13331. serializationObject.maxZ = camera.maxZ;
  13332. serializationObject.speed = camera.speed;
  13333. serializationObject.inertia = camera.inertia;
  13334. serializationObject.checkCollisions = camera.checkCollisions;
  13335. serializationObject.applyGravity = camera.applyGravity;
  13336. if (camera.ellipsoid) {
  13337. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  13338. }
  13339. appendAnimations(camera, serializationObject);
  13340. serializationObject.layerMask = camera.layerMask;
  13341. return serializationObject;
  13342. };
  13343. var appendAnimations = function (source, destination) {
  13344. if (source.animations) {
  13345. destination.animations = [];
  13346. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  13347. var animation = source.animations[animationIndex];
  13348. destination.animations.push(serializeAnimation(animation));
  13349. }
  13350. }
  13351. };
  13352. var serializeAnimation = function (animation) {
  13353. var serializationObject = {};
  13354. serializationObject.name = animation.name;
  13355. serializationObject.property = animation.targetProperty;
  13356. serializationObject.framePerSecond = animation.framePerSecond;
  13357. serializationObject.dataType = animation.dataType;
  13358. serializationObject.loopBehavior = animation.loopMode;
  13359. var dataType = animation.dataType;
  13360. serializationObject.keys = [];
  13361. var keys = animation.getKeys();
  13362. for (var index = 0; index < keys.length; index++) {
  13363. var animationKey = keys[index];
  13364. var key = {};
  13365. key.frame = animationKey.frame;
  13366. switch (dataType) {
  13367. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  13368. key.values = [animationKey.value];
  13369. break;
  13370. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  13371. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  13372. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  13373. key.values = animationKey.value.asArray();
  13374. break;
  13375. }
  13376. serializationObject.keys.push(key);
  13377. }
  13378. return serializationObject;
  13379. };
  13380. var serializeMultiMaterial = function (material) {
  13381. var serializationObject = {};
  13382. serializationObject.name = material.name;
  13383. serializationObject.id = material.id;
  13384. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13385. serializationObject.materials = [];
  13386. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  13387. var subMat = material.subMaterials[matIndex];
  13388. if (subMat) {
  13389. serializationObject.materials.push(subMat.id);
  13390. } else {
  13391. serializationObject.materials.push(null);
  13392. }
  13393. }
  13394. return serializationObject;
  13395. };
  13396. var serializeMaterial = function (material) {
  13397. var serializationObject = {};
  13398. serializationObject.name = material.name;
  13399. serializationObject.ambient = material.ambientColor.asArray();
  13400. serializationObject.diffuse = material.diffuseColor.asArray();
  13401. serializationObject.specular = material.specularColor.asArray();
  13402. serializationObject.specularPower = material.specularPower;
  13403. serializationObject.emissive = material.emissiveColor.asArray();
  13404. serializationObject.alpha = material.alpha;
  13405. serializationObject.id = material.id;
  13406. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13407. serializationObject.backFaceCulling = material.backFaceCulling;
  13408. if (material.diffuseTexture) {
  13409. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  13410. }
  13411. if (material.diffuseFresnelParameters) {
  13412. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  13413. }
  13414. if (material.ambientTexture) {
  13415. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  13416. }
  13417. if (material.opacityTexture) {
  13418. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  13419. }
  13420. if (material.opacityFresnelParameters) {
  13421. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  13422. }
  13423. if (material.reflectionTexture) {
  13424. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  13425. }
  13426. if (material.reflectionFresnelParameters) {
  13427. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  13428. }
  13429. if (material.emissiveTexture) {
  13430. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  13431. }
  13432. if (material.emissiveFresnelParameters) {
  13433. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  13434. }
  13435. if (material.specularTexture) {
  13436. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  13437. }
  13438. if (material.bumpTexture) {
  13439. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  13440. }
  13441. return serializationObject;
  13442. };
  13443. var serializeTexture = function (texture) {
  13444. var serializationObject = {};
  13445. if (!texture.name) {
  13446. return null;
  13447. }
  13448. if (texture instanceof BABYLON.CubeTexture) {
  13449. serializationObject.name = texture.name;
  13450. serializationObject.hasAlpha = texture.hasAlpha;
  13451. serializationObject.level = texture.level;
  13452. serializationObject.coordinatesMode = texture.coordinatesMode;
  13453. return serializationObject;
  13454. }
  13455. if (texture instanceof BABYLON.MirrorTexture) {
  13456. var mirrorTexture = texture;
  13457. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  13458. serializationObject.renderList = [];
  13459. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  13460. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  13461. }
  13462. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  13463. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  13464. var renderTargetTexture = texture;
  13465. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  13466. serializationObject.renderList = [];
  13467. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  13468. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  13469. }
  13470. }
  13471. var regularTexture = texture;
  13472. serializationObject.name = texture.name;
  13473. serializationObject.hasAlpha = texture.hasAlpha;
  13474. serializationObject.level = texture.level;
  13475. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  13476. serializationObject.coordinatesMode = texture.coordinatesMode;
  13477. serializationObject.uOffset = regularTexture.uOffset;
  13478. serializationObject.vOffset = regularTexture.vOffset;
  13479. serializationObject.uScale = regularTexture.uScale;
  13480. serializationObject.vScale = regularTexture.vScale;
  13481. serializationObject.uAng = regularTexture.uAng;
  13482. serializationObject.vAng = regularTexture.vAng;
  13483. serializationObject.wAng = regularTexture.wAng;
  13484. serializationObject.wrapU = texture.wrapU;
  13485. serializationObject.wrapV = texture.wrapV;
  13486. appendAnimations(texture, serializationObject);
  13487. return serializationObject;
  13488. };
  13489. var serializeSkeleton = function (skeleton) {
  13490. var serializationObject = {};
  13491. serializationObject.name = skeleton.name;
  13492. serializationObject.id = skeleton.id;
  13493. serializationObject.bones = [];
  13494. for (var index = 0; index < skeleton.bones.length; index++) {
  13495. var bone = skeleton.bones[index];
  13496. var serializedBone = {
  13497. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  13498. name: bone.name,
  13499. matrix: bone.getLocalMatrix().toArray()
  13500. };
  13501. serializationObject.bones.push(serializedBone);
  13502. if (bone.animations && bone.animations.length > 0) {
  13503. serializedBone.animation = serializeAnimation(bone.animations[0]);
  13504. }
  13505. }
  13506. return serializationObject;
  13507. };
  13508. var serializeParticleSystem = function (particleSystem) {
  13509. var serializationObject = {};
  13510. serializationObject.emitterId = particleSystem.emitter.id;
  13511. serializationObject.capacity = particleSystem.getCapacity();
  13512. if (particleSystem.particleTexture) {
  13513. serializationObject.textureName = particleSystem.particleTexture.name;
  13514. }
  13515. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  13516. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  13517. serializationObject.minSize = particleSystem.minSize;
  13518. serializationObject.maxSize = particleSystem.maxSize;
  13519. serializationObject.minLifeTime = particleSystem.minLifeTime;
  13520. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  13521. serializationObject.emitRate = particleSystem.emitRate;
  13522. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  13523. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  13524. serializationObject.gravity = particleSystem.gravity.asArray();
  13525. serializationObject.direction1 = particleSystem.direction1.asArray();
  13526. serializationObject.direction2 = particleSystem.direction2.asArray();
  13527. serializationObject.color1 = particleSystem.color1.asArray();
  13528. serializationObject.color2 = particleSystem.color2.asArray();
  13529. serializationObject.colorDead = particleSystem.colorDead.asArray();
  13530. serializationObject.updateSpeed = particleSystem.updateSpeed;
  13531. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  13532. serializationObject.textureMask = particleSystem.textureMask.asArray();
  13533. serializationObject.blendMode = particleSystem.blendMode;
  13534. return serializationObject;
  13535. };
  13536. var serializeLensFlareSystem = function (lensFlareSystem) {
  13537. var serializationObject = {};
  13538. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  13539. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  13540. serializationObject.flares = [];
  13541. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  13542. var flare = lensFlareSystem.lensFlares[index];
  13543. serializationObject.flares.push({
  13544. size: flare.size,
  13545. position: flare.position,
  13546. color: flare.color.asArray(),
  13547. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  13548. });
  13549. }
  13550. return serializationObject;
  13551. };
  13552. var serializeShadowGenerator = function (light) {
  13553. var serializationObject = {};
  13554. var shadowGenerator = light.getShadowGenerator();
  13555. serializationObject.lightId = light.id;
  13556. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  13557. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  13558. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  13559. serializationObject.renderList = [];
  13560. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  13561. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  13562. serializationObject.renderList.push(mesh.id);
  13563. }
  13564. return serializationObject;
  13565. };
  13566. var serializedGeometries = [];
  13567. var serializeGeometry = function (geometry, serializationGeometries) {
  13568. if (serializedGeometries[geometry.id]) {
  13569. return;
  13570. }
  13571. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  13572. serializationGeometries.boxes.push(serializeBox(geometry));
  13573. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  13574. serializationGeometries.spheres.push(serializeSphere(geometry));
  13575. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  13576. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  13577. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  13578. serializationGeometries.toruses.push(serializeTorus(geometry));
  13579. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  13580. serializationGeometries.grounds.push(serializeGround(geometry));
  13581. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  13582. serializationGeometries.planes.push(serializePlane(geometry));
  13583. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  13584. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  13585. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  13586. throw new Error("Unknow primitive type");
  13587. } else {
  13588. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  13589. }
  13590. serializedGeometries[geometry.id] = true;
  13591. };
  13592. var serializeGeometryBase = function (geometry) {
  13593. var serializationObject = {};
  13594. serializationObject.id = geometry.id;
  13595. if (BABYLON.Tags.HasTags(geometry)) {
  13596. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  13597. }
  13598. return serializationObject;
  13599. };
  13600. var serializeVertexData = function (vertexData) {
  13601. var serializationObject = serializeGeometryBase(vertexData);
  13602. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  13603. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13604. }
  13605. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13606. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13607. }
  13608. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13609. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  13610. }
  13611. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13612. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  13613. }
  13614. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13615. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  13616. }
  13617. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  13618. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  13619. serializationObject.matricesIndices._isExpanded = true;
  13620. }
  13621. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13622. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  13623. }
  13624. serializationObject.indices = vertexData.getIndices();
  13625. return serializationObject;
  13626. };
  13627. var serializePrimitive = function (primitive) {
  13628. var serializationObject = serializeGeometryBase(primitive);
  13629. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  13630. return serializationObject;
  13631. };
  13632. var serializeBox = function (box) {
  13633. var serializationObject = serializePrimitive(box);
  13634. serializationObject.size = box.size;
  13635. return serializationObject;
  13636. };
  13637. var serializeSphere = function (sphere) {
  13638. var serializationObject = serializePrimitive(sphere);
  13639. serializationObject.segments = sphere.segments;
  13640. serializationObject.diameter = sphere.diameter;
  13641. return serializationObject;
  13642. };
  13643. var serializeCylinder = function (cylinder) {
  13644. var serializationObject = serializePrimitive(cylinder);
  13645. serializationObject.height = cylinder.height;
  13646. serializationObject.diameterTop = cylinder.diameterTop;
  13647. serializationObject.diameterBottom = cylinder.diameterBottom;
  13648. serializationObject.tessellation = cylinder.tessellation;
  13649. return serializationObject;
  13650. };
  13651. var serializeTorus = function (torus) {
  13652. var serializationObject = serializePrimitive(torus);
  13653. serializationObject.diameter = torus.diameter;
  13654. serializationObject.thickness = torus.thickness;
  13655. serializationObject.tessellation = torus.tessellation;
  13656. return serializationObject;
  13657. };
  13658. var serializeGround = function (ground) {
  13659. var serializationObject = serializePrimitive(ground);
  13660. serializationObject.width = ground.width;
  13661. serializationObject.height = ground.height;
  13662. serializationObject.subdivisions = ground.subdivisions;
  13663. return serializationObject;
  13664. };
  13665. var serializePlane = function (plane) {
  13666. var serializationObject = serializePrimitive(plane);
  13667. serializationObject.size = plane.size;
  13668. return serializationObject;
  13669. };
  13670. var serializeTorusKnot = function (torusKnot) {
  13671. var serializationObject = serializePrimitive(torusKnot);
  13672. serializationObject.radius = torusKnot.radius;
  13673. serializationObject.tube = torusKnot.tube;
  13674. serializationObject.radialSegments = torusKnot.radialSegments;
  13675. serializationObject.tubularSegments = torusKnot.tubularSegments;
  13676. serializationObject.p = torusKnot.p;
  13677. serializationObject.q = torusKnot.q;
  13678. return serializationObject;
  13679. };
  13680. var serializeMesh = function (mesh, serializationScene) {
  13681. var serializationObject = {};
  13682. serializationObject.name = mesh.name;
  13683. serializationObject.id = mesh.id;
  13684. if (BABYLON.Tags.HasTags(mesh)) {
  13685. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  13686. }
  13687. serializationObject.position = mesh.position.asArray();
  13688. if (mesh.rotationQuaternion) {
  13689. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  13690. } else if (mesh.rotation) {
  13691. serializationObject.rotation = mesh.rotation.asArray();
  13692. }
  13693. serializationObject.scaling = mesh.scaling.asArray();
  13694. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  13695. serializationObject.isEnabled = mesh.isEnabled();
  13696. serializationObject.isVisible = mesh.isVisible;
  13697. serializationObject.infiniteDistance = mesh.infiniteDistance;
  13698. serializationObject.pickable = mesh.isPickable;
  13699. serializationObject.receiveShadows = mesh.receiveShadows;
  13700. serializationObject.billboardMode = mesh.billboardMode;
  13701. serializationObject.visibility = mesh.visibility;
  13702. serializationObject.checkCollisions = mesh.checkCollisions;
  13703. if (mesh.parent) {
  13704. serializationObject.parentId = mesh.parent.id;
  13705. }
  13706. var geometry = mesh._geometry;
  13707. if (geometry) {
  13708. var geometryId = geometry.id;
  13709. serializationObject.geometryId = geometryId;
  13710. if (!mesh.getScene().getGeometryByID(geometryId)) {
  13711. serializeGeometry(geometry, serializationScene.geometries);
  13712. }
  13713. serializationObject.subMeshes = [];
  13714. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  13715. var subMesh = mesh.subMeshes[subIndex];
  13716. serializationObject.subMeshes.push({
  13717. materialIndex: subMesh.materialIndex,
  13718. verticesStart: subMesh.verticesStart,
  13719. verticesCount: subMesh.verticesCount,
  13720. indexStart: subMesh.indexStart,
  13721. indexCount: subMesh.indexCount
  13722. });
  13723. }
  13724. }
  13725. if (mesh.material) {
  13726. serializationObject.materialId = mesh.material.id;
  13727. } else {
  13728. mesh.material = null;
  13729. }
  13730. if (mesh.skeleton) {
  13731. serializationObject.skeletonId = mesh.skeleton.id;
  13732. }
  13733. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  13734. serializationObject.physicsMass = mesh.getPhysicsMass();
  13735. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  13736. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  13737. switch (mesh.getPhysicsImpostor()) {
  13738. case BABYLON.PhysicsEngine.BoxImpostor:
  13739. serializationObject.physicsImpostor = 1;
  13740. break;
  13741. case BABYLON.PhysicsEngine.SphereImpostor:
  13742. serializationObject.physicsImpostor = 2;
  13743. break;
  13744. }
  13745. }
  13746. serializationObject.instances = [];
  13747. for (var index = 0; index < mesh.instances.length; index++) {
  13748. var instance = mesh.instances[index];
  13749. var serializationInstance = {
  13750. name: instance.name,
  13751. position: instance.position,
  13752. rotation: instance.rotation,
  13753. rotationQuaternion: instance.rotationQuaternion,
  13754. scaling: instance.scaling
  13755. };
  13756. serializationObject.instances.push(serializationInstance);
  13757. appendAnimations(instance, serializationInstance);
  13758. }
  13759. appendAnimations(mesh, serializationObject);
  13760. serializationObject.layerMask = mesh.layerMask;
  13761. return serializationObject;
  13762. };
  13763. var SceneSerializer = (function () {
  13764. function SceneSerializer() {
  13765. }
  13766. SceneSerializer.Serialize = function (scene) {
  13767. var serializationObject = {};
  13768. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  13769. serializationObject.autoClear = scene.autoClear;
  13770. serializationObject.clearColor = scene.clearColor.asArray();
  13771. serializationObject.ambientColor = scene.ambientColor.asArray();
  13772. serializationObject.gravity = scene.gravity.asArray();
  13773. if (scene.fogMode && scene.fogMode !== 0) {
  13774. serializationObject.fogMode = scene.fogMode;
  13775. serializationObject.fogColor = scene.fogColor.asArray();
  13776. serializationObject.fogStart = scene.fogStart;
  13777. serializationObject.fogEnd = scene.fogEnd;
  13778. serializationObject.fogDensity = scene.fogDensity;
  13779. }
  13780. serializationObject.lights = [];
  13781. for (var index = 0; index < scene.lights.length; index++) {
  13782. var light = scene.lights[index];
  13783. serializationObject.lights.push(serializeLight(light));
  13784. }
  13785. serializationObject.cameras = [];
  13786. for (index = 0; index < scene.cameras.length; index++) {
  13787. var camera = scene.cameras[index];
  13788. if (camera instanceof BABYLON.FreeCamera) {
  13789. serializationObject.cameras.push(serializeCamera(camera));
  13790. }
  13791. }
  13792. if (scene.activeCamera) {
  13793. serializationObject.activeCameraID = scene.activeCamera.id;
  13794. }
  13795. serializationObject.materials = [];
  13796. serializationObject.multiMaterials = [];
  13797. for (index = 0; index < scene.materials.length; index++) {
  13798. var material = scene.materials[index];
  13799. if (material instanceof BABYLON.StandardMaterial) {
  13800. serializationObject.materials.push(serializeMaterial(material));
  13801. } else if (material instanceof BABYLON.MultiMaterial) {
  13802. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  13803. }
  13804. }
  13805. serializationObject.skeletons = [];
  13806. for (index = 0; index < scene.skeletons.length; index++) {
  13807. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  13808. }
  13809. serializationObject.geometries = {};
  13810. serializationObject.geometries.boxes = [];
  13811. serializationObject.geometries.spheres = [];
  13812. serializationObject.geometries.cylinders = [];
  13813. serializationObject.geometries.toruses = [];
  13814. serializationObject.geometries.grounds = [];
  13815. serializationObject.geometries.planes = [];
  13816. serializationObject.geometries.torusKnots = [];
  13817. serializationObject.geometries.vertexData = [];
  13818. serializedGeometries = [];
  13819. var geometries = scene.getGeometries();
  13820. for (var index = 0; index < geometries.length; index++) {
  13821. var geometry = geometries[index];
  13822. if (geometry.isReady()) {
  13823. serializeGeometry(geometry, serializationObject.geometries);
  13824. }
  13825. }
  13826. serializationObject.meshes = [];
  13827. for (index = 0; index < scene.meshes.length; index++) {
  13828. var abstractMesh = scene.meshes[index];
  13829. if (abstractMesh instanceof BABYLON.Mesh) {
  13830. var mesh = abstractMesh;
  13831. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  13832. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  13833. }
  13834. }
  13835. }
  13836. serializationObject.particleSystems = [];
  13837. for (index = 0; index < scene.particleSystems.length; index++) {
  13838. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  13839. }
  13840. serializationObject.lensFlareSystems = [];
  13841. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  13842. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  13843. }
  13844. serializationObject.shadowGenerators = [];
  13845. for (index = 0; index < scene.lights.length; index++) {
  13846. light = scene.lights[index];
  13847. if (light.getShadowGenerator()) {
  13848. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  13849. }
  13850. }
  13851. return serializationObject;
  13852. };
  13853. return SceneSerializer;
  13854. })();
  13855. BABYLON.SceneSerializer = SceneSerializer;
  13856. })(BABYLON || (BABYLON = {}));
  13857. var BABYLON;
  13858. (function (BABYLON) {
  13859. var SceneLoader = (function () {
  13860. function SceneLoader() {
  13861. }
  13862. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  13863. get: function () {
  13864. return SceneLoader._ForceFullSceneLoadingForIncremental;
  13865. },
  13866. set: function (value) {
  13867. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  13868. },
  13869. enumerable: true,
  13870. configurable: true
  13871. });
  13872. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  13873. get: function () {
  13874. return SceneLoader._ShowLoadingScreen;
  13875. },
  13876. set: function (value) {
  13877. SceneLoader._ShowLoadingScreen = value;
  13878. },
  13879. enumerable: true,
  13880. configurable: true
  13881. });
  13882. SceneLoader._getPluginForFilename = function (sceneFilename) {
  13883. var dotPosition = sceneFilename.lastIndexOf(".");
  13884. var extension = sceneFilename.substring(dotPosition).toLowerCase();
  13885. for (var index = 0; index < this._registeredPlugins.length; index++) {
  13886. var plugin = this._registeredPlugins[index];
  13887. if (plugin.extensions.indexOf(extension) !== -1) {
  13888. return plugin;
  13889. }
  13890. }
  13891. return this._registeredPlugins[this._registeredPlugins.length - 1];
  13892. };
  13893. SceneLoader.RegisterPlugin = function (plugin) {
  13894. plugin.extensions = plugin.extensions.toLowerCase();
  13895. SceneLoader._registeredPlugins.push(plugin);
  13896. };
  13897. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  13898. var _this = this;
  13899. var manifestChecked = function (success) {
  13900. scene.database = database;
  13901. var plugin = _this._getPluginForFilename(sceneFilename);
  13902. var importMeshFromData = function (data) {
  13903. var meshes = [];
  13904. var particleSystems = [];
  13905. var skeletons = [];
  13906. try {
  13907. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  13908. if (onerror) {
  13909. onerror(scene);
  13910. }
  13911. return;
  13912. }
  13913. } catch (e) {
  13914. if (onerror) {
  13915. onerror(scene);
  13916. }
  13917. return;
  13918. }
  13919. if (onsuccess) {
  13920. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  13921. onsuccess(meshes, particleSystems, skeletons);
  13922. }
  13923. };
  13924. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  13925. importMeshFromData(sceneFilename.substr(5));
  13926. return;
  13927. }
  13928. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  13929. importMeshFromData(data);
  13930. }, progressCallBack, database);
  13931. };
  13932. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  13933. };
  13934. /**
  13935. * Load a scene
  13936. * @param rootUrl a string that defines the root url for scene and resources
  13937. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  13938. * @param engine is the instance of BABYLON.Engine to use to create the scene
  13939. */
  13940. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  13941. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  13942. };
  13943. /**
  13944. * Append a scene
  13945. * @param rootUrl a string that defines the root url for scene and resources
  13946. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  13947. * @param scene is the instance of BABYLON.Scene to append to
  13948. */
  13949. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  13950. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  13951. var database;
  13952. if (SceneLoader.ShowLoadingScreen) {
  13953. scene.getEngine().displayLoadingUI();
  13954. }
  13955. var loadSceneFromData = function (data) {
  13956. scene.database = database;
  13957. if (!plugin.load(scene, data, rootUrl)) {
  13958. if (onerror) {
  13959. onerror(scene);
  13960. }
  13961. scene.getEngine().hideLoadingUI();
  13962. return;
  13963. }
  13964. if (onsuccess) {
  13965. onsuccess(scene);
  13966. }
  13967. if (SceneLoader.ShowLoadingScreen) {
  13968. scene.executeWhenReady(function () {
  13969. scene.getEngine().hideLoadingUI();
  13970. });
  13971. }
  13972. };
  13973. var manifestChecked = function (success) {
  13974. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  13975. };
  13976. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  13977. loadSceneFromData(sceneFilename.substr(5));
  13978. return;
  13979. }
  13980. if (rootUrl.indexOf("file:") === -1) {
  13981. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  13982. } else {
  13983. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  13984. }
  13985. };
  13986. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  13987. SceneLoader._ShowLoadingScreen = true;
  13988. SceneLoader._registeredPlugins = new Array();
  13989. return SceneLoader;
  13990. })();
  13991. BABYLON.SceneLoader = SceneLoader;
  13992. ;
  13993. })(BABYLON || (BABYLON = {}));
  13994. var BABYLON;
  13995. (function (BABYLON) {
  13996. (function (Internals) {
  13997. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  13998. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  13999. texture.name = parsedTexture.name;
  14000. texture.hasAlpha = parsedTexture.hasAlpha;
  14001. texture.level = parsedTexture.level;
  14002. texture.coordinatesMode = parsedTexture.coordinatesMode;
  14003. return texture;
  14004. };
  14005. var loadTexture = function (rootUrl, parsedTexture, scene) {
  14006. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  14007. return null;
  14008. }
  14009. if (parsedTexture.isCube) {
  14010. return loadCubeTexture(rootUrl, parsedTexture, scene);
  14011. }
  14012. var texture;
  14013. if (parsedTexture.mirrorPlane) {
  14014. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  14015. texture._waitingRenderList = parsedTexture.renderList;
  14016. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  14017. } else if (parsedTexture.isRenderTarget) {
  14018. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  14019. texture._waitingRenderList = parsedTexture.renderList;
  14020. } else {
  14021. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  14022. }
  14023. texture.name = parsedTexture.name;
  14024. texture.hasAlpha = parsedTexture.hasAlpha;
  14025. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  14026. texture.level = parsedTexture.level;
  14027. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  14028. texture.coordinatesMode = parsedTexture.coordinatesMode;
  14029. texture.uOffset = parsedTexture.uOffset;
  14030. texture.vOffset = parsedTexture.vOffset;
  14031. texture.uScale = parsedTexture.uScale;
  14032. texture.vScale = parsedTexture.vScale;
  14033. texture.uAng = parsedTexture.uAng;
  14034. texture.vAng = parsedTexture.vAng;
  14035. texture.wAng = parsedTexture.wAng;
  14036. texture.wrapU = parsedTexture.wrapU;
  14037. texture.wrapV = parsedTexture.wrapV;
  14038. if (parsedTexture.animations) {
  14039. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  14040. var parsedAnimation = parsedTexture.animations[animationIndex];
  14041. texture.animations.push(parseAnimation(parsedAnimation));
  14042. }
  14043. }
  14044. return texture;
  14045. };
  14046. var parseSkeleton = function (parsedSkeleton, scene) {
  14047. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  14048. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  14049. var parsedBone = parsedSkeleton.bones[index];
  14050. var parentBone = null;
  14051. if (parsedBone.parentBoneIndex > -1) {
  14052. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  14053. }
  14054. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  14055. if (parsedBone.animation) {
  14056. bone.animations.push(parseAnimation(parsedBone.animation));
  14057. }
  14058. }
  14059. return skeleton;
  14060. };
  14061. var parseFresnelParameters = function (parsedFresnelParameters) {
  14062. var fresnelParameters = new BABYLON.FresnelParameters();
  14063. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  14064. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  14065. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  14066. fresnelParameters.bias = parsedFresnelParameters.bias;
  14067. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  14068. return fresnelParameters;
  14069. };
  14070. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  14071. var material;
  14072. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  14073. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  14074. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  14075. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  14076. material.specularPower = parsedMaterial.specularPower;
  14077. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  14078. material.alpha = parsedMaterial.alpha;
  14079. material.id = parsedMaterial.id;
  14080. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  14081. material.backFaceCulling = parsedMaterial.backFaceCulling;
  14082. material.wireframe = parsedMaterial.wireframe;
  14083. if (parsedMaterial.diffuseTexture) {
  14084. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  14085. }
  14086. if (parsedMaterial.diffuseFresnelParameters) {
  14087. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  14088. }
  14089. if (parsedMaterial.ambientTexture) {
  14090. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  14091. }
  14092. if (parsedMaterial.opacityTexture) {
  14093. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  14094. }
  14095. if (parsedMaterial.opacityFresnelParameters) {
  14096. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  14097. }
  14098. if (parsedMaterial.reflectionTexture) {
  14099. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  14100. }
  14101. if (parsedMaterial.reflectionFresnelParameters) {
  14102. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  14103. }
  14104. if (parsedMaterial.emissiveTexture) {
  14105. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  14106. }
  14107. if (parsedMaterial.emissiveFresnelParameters) {
  14108. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  14109. }
  14110. if (parsedMaterial.specularTexture) {
  14111. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  14112. }
  14113. if (parsedMaterial.bumpTexture) {
  14114. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  14115. }
  14116. return material;
  14117. };
  14118. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  14119. for (var index = 0; index < parsedData.materials.length; index++) {
  14120. var parsedMaterial = parsedData.materials[index];
  14121. if (parsedMaterial.id === id) {
  14122. return parseMaterial(parsedMaterial, scene, rootUrl);
  14123. }
  14124. }
  14125. return null;
  14126. };
  14127. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  14128. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  14129. multiMaterial.id = parsedMultiMaterial.id;
  14130. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  14131. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14132. var subMatId = parsedMultiMaterial.materials[matIndex];
  14133. if (subMatId) {
  14134. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  14135. } else {
  14136. multiMaterial.subMaterials.push(null);
  14137. }
  14138. }
  14139. return multiMaterial;
  14140. };
  14141. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  14142. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  14143. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  14144. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  14145. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  14146. var parsedFlare = parsedLensFlareSystem.flares[index];
  14147. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  14148. }
  14149. return lensFlareSystem;
  14150. };
  14151. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  14152. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  14153. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  14154. if (parsedParticleSystem.textureName) {
  14155. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  14156. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  14157. }
  14158. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  14159. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  14160. particleSystem.minSize = parsedParticleSystem.minSize;
  14161. particleSystem.maxSize = parsedParticleSystem.maxSize;
  14162. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  14163. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  14164. particleSystem.emitter = emitter;
  14165. particleSystem.emitRate = parsedParticleSystem.emitRate;
  14166. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  14167. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  14168. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  14169. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  14170. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  14171. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  14172. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  14173. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  14174. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  14175. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  14176. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  14177. particleSystem.blendMode = parsedParticleSystem.blendMode;
  14178. particleSystem.start();
  14179. return particleSystem;
  14180. };
  14181. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  14182. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  14183. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  14184. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  14185. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  14186. shadowGenerator.getShadowMap().renderList.push(mesh);
  14187. }
  14188. if (parsedShadowGenerator.usePoissonSampling) {
  14189. shadowGenerator.usePoissonSampling = true;
  14190. } else {
  14191. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  14192. }
  14193. return shadowGenerator;
  14194. };
  14195. var parseAnimation = function (parsedAnimation) {
  14196. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  14197. var dataType = parsedAnimation.dataType;
  14198. var keys = [];
  14199. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  14200. var key = parsedAnimation.keys[index];
  14201. var data;
  14202. switch (dataType) {
  14203. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  14204. data = key.values[0];
  14205. break;
  14206. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  14207. data = BABYLON.Quaternion.FromArray(key.values);
  14208. break;
  14209. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  14210. data = BABYLON.Matrix.FromArray(key.values);
  14211. break;
  14212. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  14213. default:
  14214. data = BABYLON.Vector3.FromArray(key.values);
  14215. break;
  14216. }
  14217. keys.push({
  14218. frame: key.frame,
  14219. value: data
  14220. });
  14221. }
  14222. animation.setKeys(keys);
  14223. return animation;
  14224. };
  14225. var parseLight = function (parsedLight, scene) {
  14226. var light;
  14227. switch (parsedLight.type) {
  14228. case 0:
  14229. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  14230. break;
  14231. case 1:
  14232. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14233. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  14234. break;
  14235. case 2:
  14236. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  14237. break;
  14238. case 3:
  14239. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14240. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  14241. break;
  14242. }
  14243. light.id = parsedLight.id;
  14244. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  14245. if (parsedLight.intensity !== undefined) {
  14246. light.intensity = parsedLight.intensity;
  14247. }
  14248. if (parsedLight.range) {
  14249. light.range = parsedLight.range;
  14250. }
  14251. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  14252. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  14253. if (parsedLight.excludedMeshesIds) {
  14254. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14255. }
  14256. if (parsedLight.includedOnlyMeshesIds) {
  14257. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14258. }
  14259. if (parsedLight.animations) {
  14260. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14261. var parsedAnimation = parsedLight.animations[animationIndex];
  14262. light.animations.push(parseAnimation(parsedAnimation));
  14263. }
  14264. }
  14265. if (parsedLight.autoAnimate) {
  14266. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  14267. }
  14268. };
  14269. var parseCamera = function (parsedCamera, scene) {
  14270. var camera = new BABYLON.FreeCamera(parsedCamera.name, BABYLON.Vector3.FromArray(parsedCamera.position), scene);
  14271. camera.id = parsedCamera.id;
  14272. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  14273. if (parsedCamera.parentId) {
  14274. camera._waitingParentId = parsedCamera.parentId;
  14275. }
  14276. if (parsedCamera.target) {
  14277. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14278. } else {
  14279. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  14280. }
  14281. if (parsedCamera.lockedTargetId) {
  14282. camera._waitingLockedTargetId = parsedCamera.lockedTargetId;
  14283. }
  14284. camera.fov = parsedCamera.fov;
  14285. camera.minZ = parsedCamera.minZ;
  14286. camera.maxZ = parsedCamera.maxZ;
  14287. camera.speed = parsedCamera.speed;
  14288. camera.inertia = parsedCamera.inertia;
  14289. camera.checkCollisions = parsedCamera.checkCollisions;
  14290. camera.applyGravity = parsedCamera.applyGravity;
  14291. if (parsedCamera.ellipsoid) {
  14292. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  14293. }
  14294. if (parsedCamera.animations) {
  14295. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14296. var parsedAnimation = parsedCamera.animations[animationIndex];
  14297. camera.animations.push(parseAnimation(parsedAnimation));
  14298. }
  14299. }
  14300. if (parsedCamera.autoAnimate) {
  14301. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  14302. }
  14303. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  14304. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  14305. } else {
  14306. camera.layerMask = 0xFFFFFFFF;
  14307. }
  14308. return camera;
  14309. };
  14310. var parseGeometry = function (parsedGeometry, scene) {
  14311. var id = parsedGeometry.id;
  14312. return scene.getGeometryByID(id);
  14313. };
  14314. var parseBox = function (parsedBox, scene) {
  14315. if (parseGeometry(parsedBox, scene)) {
  14316. return null;
  14317. }
  14318. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  14319. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  14320. scene.pushGeometry(box, true);
  14321. return box;
  14322. };
  14323. var parseSphere = function (parsedSphere, scene) {
  14324. if (parseGeometry(parsedSphere, scene)) {
  14325. return null;
  14326. }
  14327. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  14328. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  14329. scene.pushGeometry(sphere, true);
  14330. return sphere;
  14331. };
  14332. var parseCylinder = function (parsedCylinder, scene) {
  14333. if (parseGeometry(parsedCylinder, scene)) {
  14334. return null;
  14335. }
  14336. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  14337. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  14338. scene.pushGeometry(cylinder, true);
  14339. return cylinder;
  14340. };
  14341. var parseTorus = function (parsedTorus, scene) {
  14342. if (parseGeometry(parsedTorus, scene)) {
  14343. return null;
  14344. }
  14345. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  14346. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  14347. scene.pushGeometry(torus, true);
  14348. return torus;
  14349. };
  14350. var parseGround = function (parsedGround, scene) {
  14351. if (parseGeometry(parsedGround, scene)) {
  14352. return null;
  14353. }
  14354. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  14355. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  14356. scene.pushGeometry(ground, true);
  14357. return ground;
  14358. };
  14359. var parsePlane = function (parsedPlane, scene) {
  14360. if (parseGeometry(parsedPlane, scene)) {
  14361. return null;
  14362. }
  14363. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  14364. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  14365. scene.pushGeometry(plane, true);
  14366. return plane;
  14367. };
  14368. var parseTorusKnot = function (parsedTorusKnot, scene) {
  14369. if (parseGeometry(parsedTorusKnot, scene)) {
  14370. return null;
  14371. }
  14372. var torusKnot = new BABYLON.Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  14373. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  14374. scene.pushGeometry(torusKnot, true);
  14375. return torusKnot;
  14376. };
  14377. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  14378. if (parseGeometry(parsedVertexData, scene)) {
  14379. return null;
  14380. }
  14381. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  14382. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  14383. if (parsedVertexData.delayLoadingFile) {
  14384. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14385. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  14386. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  14387. geometry._delayInfo = [];
  14388. if (parsedVertexData.hasUVs) {
  14389. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  14390. }
  14391. if (parsedVertexData.hasUVs2) {
  14392. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  14393. }
  14394. if (parsedVertexData.hasColors) {
  14395. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  14396. }
  14397. if (parsedVertexData.hasMatricesIndices) {
  14398. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14399. }
  14400. if (parsedVertexData.hasMatricesWeights) {
  14401. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14402. }
  14403. geometry._delayLoadingFunction = importVertexData;
  14404. } else {
  14405. importVertexData(parsedVertexData, geometry);
  14406. }
  14407. scene.pushGeometry(geometry, true);
  14408. return geometry;
  14409. };
  14410. var parseMesh = function (parsedMesh, scene, rootUrl) {
  14411. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  14412. mesh.id = parsedMesh.id;
  14413. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  14414. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  14415. if (parsedMesh.rotationQuaternion) {
  14416. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  14417. } else if (parsedMesh.rotation) {
  14418. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  14419. }
  14420. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  14421. if (parsedMesh.localMatrix) {
  14422. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  14423. } else if (parsedMesh.pivotMatrix) {
  14424. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  14425. }
  14426. mesh.setEnabled(parsedMesh.isEnabled);
  14427. mesh.isVisible = parsedMesh.isVisible;
  14428. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  14429. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  14430. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  14431. if (parsedMesh.pickable !== undefined) {
  14432. mesh.isPickable = parsedMesh.pickable;
  14433. }
  14434. mesh.receiveShadows = parsedMesh.receiveShadows;
  14435. mesh.billboardMode = parsedMesh.billboardMode;
  14436. if (parsedMesh.visibility !== undefined) {
  14437. mesh.visibility = parsedMesh.visibility;
  14438. }
  14439. mesh.checkCollisions = parsedMesh.checkCollisions;
  14440. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  14441. if (parsedMesh.parentId) {
  14442. mesh.parent = scene.getLastEntryByID(parsedMesh.parentId);
  14443. }
  14444. if (parsedMesh.delayLoadingFile) {
  14445. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14446. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  14447. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  14448. if (parsedMesh._binaryInfo) {
  14449. mesh._binaryInfo = parsedMesh._binaryInfo;
  14450. }
  14451. mesh._delayInfo = [];
  14452. if (parsedMesh.hasUVs) {
  14453. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  14454. }
  14455. if (parsedMesh.hasUVs2) {
  14456. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  14457. }
  14458. if (parsedMesh.hasColors) {
  14459. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  14460. }
  14461. if (parsedMesh.hasMatricesIndices) {
  14462. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14463. }
  14464. if (parsedMesh.hasMatricesWeights) {
  14465. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14466. }
  14467. mesh._delayLoadingFunction = importGeometry;
  14468. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  14469. mesh._checkDelayState();
  14470. }
  14471. } else {
  14472. importGeometry(parsedMesh, mesh);
  14473. }
  14474. if (parsedMesh.materialId) {
  14475. mesh.setMaterialByID(parsedMesh.materialId);
  14476. } else {
  14477. mesh.material = null;
  14478. }
  14479. if (parsedMesh.skeletonId > -1) {
  14480. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  14481. }
  14482. if (parsedMesh.physicsImpostor) {
  14483. if (!scene.isPhysicsEnabled()) {
  14484. scene.enablePhysics();
  14485. }
  14486. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  14487. }
  14488. if (parsedMesh.animations) {
  14489. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  14490. var parsedAnimation = parsedMesh.animations[animationIndex];
  14491. mesh.animations.push(parseAnimation(parsedAnimation));
  14492. }
  14493. }
  14494. if (parsedMesh.autoAnimate) {
  14495. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  14496. }
  14497. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  14498. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  14499. } else {
  14500. mesh.layerMask = 0xFFFFFFFF;
  14501. }
  14502. if (parsedMesh.instances) {
  14503. for (var index = 0; index < parsedMesh.instances.length; index++) {
  14504. var parsedInstance = parsedMesh.instances[index];
  14505. var instance = mesh.createInstance(parsedInstance.name);
  14506. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  14507. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  14508. if (parsedInstance.rotationQuaternion) {
  14509. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  14510. } else if (parsedInstance.rotation) {
  14511. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  14512. }
  14513. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  14514. instance.checkCollisions = mesh.checkCollisions;
  14515. if (parsedMesh.animations) {
  14516. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  14517. parsedAnimation = parsedMesh.animations[animationIndex];
  14518. instance.animations.push(parseAnimation(parsedAnimation));
  14519. }
  14520. }
  14521. }
  14522. }
  14523. return mesh;
  14524. };
  14525. var isDescendantOf = function (mesh, names, hierarchyIds) {
  14526. names = (names instanceof Array) ? names : [names];
  14527. for (var i in names) {
  14528. if (mesh.name === names[i]) {
  14529. hierarchyIds.push(mesh.id);
  14530. return true;
  14531. }
  14532. }
  14533. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  14534. hierarchyIds.push(mesh.id);
  14535. return true;
  14536. }
  14537. return false;
  14538. };
  14539. var importVertexData = function (parsedVertexData, geometry) {
  14540. var vertexData = new BABYLON.VertexData();
  14541. var positions = parsedVertexData.positions;
  14542. if (positions) {
  14543. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  14544. }
  14545. var normals = parsedVertexData.normals;
  14546. if (normals) {
  14547. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  14548. }
  14549. var uvs = parsedVertexData.uvs;
  14550. if (uvs) {
  14551. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  14552. }
  14553. var uv2s = parsedVertexData.uv2s;
  14554. if (uv2s) {
  14555. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  14556. }
  14557. var colors = parsedVertexData.colors;
  14558. if (colors) {
  14559. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  14560. }
  14561. var matricesIndices = parsedVertexData.matricesIndices;
  14562. if (matricesIndices) {
  14563. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  14564. }
  14565. var matricesWeights = parsedVertexData.matricesWeights;
  14566. if (matricesWeights) {
  14567. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  14568. }
  14569. var indices = parsedVertexData.indices;
  14570. if (indices) {
  14571. vertexData.indices = indices;
  14572. }
  14573. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  14574. };
  14575. var importGeometry = function (parsedGeometry, mesh) {
  14576. var scene = mesh.getScene();
  14577. var geometryId = parsedGeometry.geometryId;
  14578. if (geometryId) {
  14579. var geometry = scene.getGeometryByID(geometryId);
  14580. if (geometry) {
  14581. geometry.applyToMesh(mesh);
  14582. }
  14583. } else if (parsedGeometry instanceof ArrayBuffer) {
  14584. var binaryInfo = mesh._binaryInfo;
  14585. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  14586. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  14587. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  14588. }
  14589. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  14590. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  14591. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  14592. }
  14593. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  14594. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  14595. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  14596. }
  14597. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  14598. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  14599. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  14600. }
  14601. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  14602. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  14603. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  14604. }
  14605. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  14606. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  14607. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  14608. }
  14609. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  14610. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  14611. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  14612. }
  14613. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  14614. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  14615. mesh.setIndices(indicesData);
  14616. }
  14617. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  14618. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  14619. mesh.subMeshes = [];
  14620. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  14621. var materialIndex = subMeshesData[(i * 5) + 0];
  14622. var verticesStart = subMeshesData[(i * 5) + 1];
  14623. var verticesCount = subMeshesData[(i * 5) + 2];
  14624. var indexStart = subMeshesData[(i * 5) + 3];
  14625. var indexCount = subMeshesData[(i * 5) + 4];
  14626. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  14627. }
  14628. }
  14629. return;
  14630. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  14631. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  14632. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  14633. if (parsedGeometry.uvs) {
  14634. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  14635. }
  14636. if (parsedGeometry.uvs2) {
  14637. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  14638. }
  14639. if (parsedGeometry.colors) {
  14640. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, parsedGeometry.colors, false);
  14641. }
  14642. if (parsedGeometry.matricesIndices) {
  14643. if (!parsedGeometry.matricesIndices._isExpanded) {
  14644. var floatIndices = [];
  14645. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  14646. var matricesIndex = parsedGeometry.matricesIndices[i];
  14647. floatIndices.push(matricesIndex & 0x000000FF);
  14648. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  14649. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  14650. floatIndices.push(matricesIndex >> 24);
  14651. }
  14652. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  14653. } else {
  14654. delete parsedGeometry.matricesIndices._isExpanded;
  14655. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  14656. }
  14657. }
  14658. if (parsedGeometry.matricesWeights) {
  14659. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  14660. }
  14661. mesh.setIndices(parsedGeometry.indices);
  14662. }
  14663. if (parsedGeometry.subMeshes) {
  14664. mesh.subMeshes = [];
  14665. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  14666. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  14667. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  14668. }
  14669. }
  14670. if (mesh._shouldGenerateFlatShading) {
  14671. mesh.convertToFlatShadedMesh();
  14672. delete mesh._shouldGenerateFlatShading;
  14673. }
  14674. mesh.computeWorldMatrix(true);
  14675. if (scene._selectionOctree) {
  14676. scene._selectionOctree.addMesh(mesh);
  14677. }
  14678. };
  14679. BABYLON.SceneLoader.RegisterPlugin({
  14680. extensions: ".babylon",
  14681. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  14682. var parsedData = JSON.parse(data);
  14683. var loadedSkeletonsIds = [];
  14684. var loadedMaterialsIds = [];
  14685. var hierarchyIds = [];
  14686. for (var index = 0; index < parsedData.meshes.length; index++) {
  14687. var parsedMesh = parsedData.meshes[index];
  14688. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  14689. if (meshesNames instanceof Array) {
  14690. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  14691. }
  14692. if (parsedMesh.materialId) {
  14693. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  14694. if (!materialFound) {
  14695. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  14696. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  14697. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  14698. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14699. var subMatId = parsedMultiMaterial.materials[matIndex];
  14700. loadedMaterialsIds.push(subMatId);
  14701. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  14702. }
  14703. loadedMaterialsIds.push(parsedMultiMaterial.id);
  14704. parseMultiMaterial(parsedMultiMaterial, scene);
  14705. materialFound = true;
  14706. break;
  14707. }
  14708. }
  14709. }
  14710. if (!materialFound) {
  14711. loadedMaterialsIds.push(parsedMesh.materialId);
  14712. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  14713. }
  14714. }
  14715. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  14716. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  14717. if (!skeletonAlreadyLoaded) {
  14718. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  14719. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  14720. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  14721. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  14722. loadedSkeletonsIds.push(parsedSkeleton.id);
  14723. }
  14724. }
  14725. }
  14726. }
  14727. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  14728. meshes.push(mesh);
  14729. }
  14730. }
  14731. if (parsedData.particleSystems) {
  14732. for (index = 0; index < parsedData.particleSystems.length; index++) {
  14733. var parsedParticleSystem = parsedData.particleSystems[index];
  14734. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  14735. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  14736. }
  14737. }
  14738. }
  14739. return true;
  14740. },
  14741. load: function (scene, data, rootUrl) {
  14742. var parsedData = JSON.parse(data);
  14743. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  14744. scene.autoClear = parsedData.autoClear;
  14745. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  14746. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  14747. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  14748. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  14749. scene.fogMode = parsedData.fogMode;
  14750. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  14751. scene.fogStart = parsedData.fogStart;
  14752. scene.fogEnd = parsedData.fogEnd;
  14753. scene.fogDensity = parsedData.fogDensity;
  14754. }
  14755. for (var index = 0; index < parsedData.lights.length; index++) {
  14756. var parsedLight = parsedData.lights[index];
  14757. parseLight(parsedLight, scene);
  14758. }
  14759. for (index = 0; index < parsedData.cameras.length; index++) {
  14760. var parsedCamera = parsedData.cameras[index];
  14761. parseCamera(parsedCamera, scene);
  14762. }
  14763. if (parsedData.activeCameraID) {
  14764. scene.setActiveCameraByID(parsedData.activeCameraID);
  14765. }
  14766. if (parsedData.materials) {
  14767. for (index = 0; index < parsedData.materials.length; index++) {
  14768. var parsedMaterial = parsedData.materials[index];
  14769. parseMaterial(parsedMaterial, scene, rootUrl);
  14770. }
  14771. }
  14772. if (parsedData.multiMaterials) {
  14773. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  14774. var parsedMultiMaterial = parsedData.multiMaterials[index];
  14775. parseMultiMaterial(parsedMultiMaterial, scene);
  14776. }
  14777. }
  14778. if (parsedData.skeletons) {
  14779. for (index = 0; index < parsedData.skeletons.length; index++) {
  14780. var parsedSkeleton = parsedData.skeletons[index];
  14781. parseSkeleton(parsedSkeleton, scene);
  14782. }
  14783. }
  14784. var geometries = parsedData.geometries;
  14785. if (geometries) {
  14786. var boxes = geometries.boxes;
  14787. if (boxes) {
  14788. for (index = 0; index < boxes.length; index++) {
  14789. var parsedBox = boxes[index];
  14790. parseBox(parsedBox, scene);
  14791. }
  14792. }
  14793. var spheres = geometries.spheres;
  14794. if (spheres) {
  14795. for (index = 0; index < spheres.length; index++) {
  14796. var parsedSphere = spheres[index];
  14797. parseSphere(parsedSphere, scene);
  14798. }
  14799. }
  14800. var cylinders = geometries.cylinders;
  14801. if (cylinders) {
  14802. for (index = 0; index < cylinders.length; index++) {
  14803. var parsedCylinder = cylinders[index];
  14804. parseCylinder(parsedCylinder, scene);
  14805. }
  14806. }
  14807. var toruses = geometries.toruses;
  14808. if (toruses) {
  14809. for (index = 0; index < toruses.length; index++) {
  14810. var parsedTorus = toruses[index];
  14811. parseTorus(parsedTorus, scene);
  14812. }
  14813. }
  14814. var grounds = geometries.grounds;
  14815. if (grounds) {
  14816. for (index = 0; index < grounds.length; index++) {
  14817. var parsedGround = grounds[index];
  14818. parseGround(parsedGround, scene);
  14819. }
  14820. }
  14821. var planes = geometries.planes;
  14822. if (planes) {
  14823. for (index = 0; index < planes.length; index++) {
  14824. var parsedPlane = planes[index];
  14825. parsePlane(parsedPlane, scene);
  14826. }
  14827. }
  14828. var torusKnots = geometries.torusKnots;
  14829. if (torusKnots) {
  14830. for (index = 0; index < torusKnots.length; index++) {
  14831. var parsedTorusKnot = torusKnots[index];
  14832. parseTorusKnot(parsedTorusKnot, scene);
  14833. }
  14834. }
  14835. var vertexData = geometries.vertexData;
  14836. if (vertexData) {
  14837. for (index = 0; index < vertexData.length; index++) {
  14838. var parsedVertexData = vertexData[index];
  14839. parseVertexData(parsedVertexData, scene, rootUrl);
  14840. }
  14841. }
  14842. }
  14843. for (index = 0; index < parsedData.meshes.length; index++) {
  14844. var parsedMesh = parsedData.meshes[index];
  14845. parseMesh(parsedMesh, scene, rootUrl);
  14846. }
  14847. for (index = 0; index < scene.cameras.length; index++) {
  14848. var camera = scene.cameras[index];
  14849. if (camera._waitingParentId) {
  14850. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  14851. delete camera._waitingParentId;
  14852. }
  14853. if (camera instanceof BABYLON.FreeCamera) {
  14854. var freecamera = camera;
  14855. if (freecamera._waitingLockedTargetId) {
  14856. freecamera.lockedTarget = scene.getLastEntryByID(freecamera._waitingLockedTargetId);
  14857. delete freecamera._waitingLockedTargetId;
  14858. }
  14859. }
  14860. }
  14861. if (parsedData.particleSystems) {
  14862. for (index = 0; index < parsedData.particleSystems.length; index++) {
  14863. var parsedParticleSystem = parsedData.particleSystems[index];
  14864. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  14865. }
  14866. }
  14867. if (parsedData.lensFlareSystems) {
  14868. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  14869. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  14870. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  14871. }
  14872. }
  14873. if (parsedData.shadowGenerators) {
  14874. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  14875. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  14876. parseShadowGenerator(parsedShadowGenerator, scene);
  14877. }
  14878. }
  14879. return true;
  14880. }
  14881. });
  14882. })(BABYLON.Internals || (BABYLON.Internals = {}));
  14883. var Internals = BABYLON.Internals;
  14884. })(BABYLON || (BABYLON = {}));
  14885. var BABYLON;
  14886. (function (BABYLON) {
  14887. var currentCSGMeshId = 0;
  14888. var Vertex = (function () {
  14889. function Vertex(pos, normal, uv) {
  14890. this.pos = pos;
  14891. this.normal = normal;
  14892. this.uv = uv;
  14893. }
  14894. Vertex.prototype.clone = function () {
  14895. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  14896. };
  14897. Vertex.prototype.flip = function () {
  14898. this.normal = this.normal.scale(-1);
  14899. };
  14900. Vertex.prototype.interpolate = function (other, t) {
  14901. 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));
  14902. };
  14903. return Vertex;
  14904. })();
  14905. var Plane = (function () {
  14906. function Plane(normal, w) {
  14907. this.normal = normal;
  14908. this.w = w;
  14909. }
  14910. Plane.FromPoints = function (a, b, c) {
  14911. var v0 = c.subtract(a);
  14912. var v1 = b.subtract(a);
  14913. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  14914. return null;
  14915. }
  14916. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  14917. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  14918. };
  14919. Plane.prototype.clone = function () {
  14920. return new Plane(this.normal.clone(), this.w);
  14921. };
  14922. Plane.prototype.flip = function () {
  14923. this.normal.scaleInPlace(-1);
  14924. this.w = -this.w;
  14925. };
  14926. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  14927. var COPLANAR = 0;
  14928. var FRONT = 1;
  14929. var BACK = 2;
  14930. var SPANNING = 3;
  14931. var polygonType = 0;
  14932. var types = [];
  14933. for (var i = 0; i < polygon.vertices.length; i++) {
  14934. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  14935. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  14936. polygonType |= type;
  14937. types.push(type);
  14938. }
  14939. switch (polygonType) {
  14940. case COPLANAR:
  14941. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  14942. break;
  14943. case FRONT:
  14944. front.push(polygon);
  14945. break;
  14946. case BACK:
  14947. back.push(polygon);
  14948. break;
  14949. case SPANNING:
  14950. var f = [], b = [];
  14951. for (i = 0; i < polygon.vertices.length; i++) {
  14952. var j = (i + 1) % polygon.vertices.length;
  14953. var ti = types[i], tj = types[j];
  14954. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  14955. if (ti != BACK)
  14956. f.push(vi);
  14957. if (ti != FRONT)
  14958. b.push(ti != BACK ? vi.clone() : vi);
  14959. if ((ti | tj) == SPANNING) {
  14960. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  14961. var v = vi.interpolate(vj, t);
  14962. f.push(v);
  14963. b.push(v.clone());
  14964. }
  14965. }
  14966. if (f.length >= 3) {
  14967. var poly = new Polygon(f, polygon.shared);
  14968. if (poly.plane)
  14969. front.push(poly);
  14970. }
  14971. if (b.length >= 3) {
  14972. poly = new Polygon(b, polygon.shared);
  14973. if (poly.plane)
  14974. back.push(poly);
  14975. }
  14976. break;
  14977. }
  14978. };
  14979. Plane.EPSILON = 1e-5;
  14980. return Plane;
  14981. })();
  14982. var Polygon = (function () {
  14983. function Polygon(vertices, shared) {
  14984. this.vertices = vertices;
  14985. this.shared = shared;
  14986. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  14987. }
  14988. Polygon.prototype.clone = function () {
  14989. var vertices = this.vertices.map(function (v) {
  14990. return v.clone();
  14991. });
  14992. return new Polygon(vertices, this.shared);
  14993. };
  14994. Polygon.prototype.flip = function () {
  14995. this.vertices.reverse().map(function (v) {
  14996. v.flip();
  14997. });
  14998. this.plane.flip();
  14999. };
  15000. return Polygon;
  15001. })();
  15002. var Node = (function () {
  15003. function Node(polygons) {
  15004. this.plane = null;
  15005. this.front = null;
  15006. this.back = null;
  15007. this.polygons = [];
  15008. if (polygons) {
  15009. this.build(polygons);
  15010. }
  15011. }
  15012. Node.prototype.clone = function () {
  15013. var node = new Node();
  15014. node.plane = this.plane && this.plane.clone();
  15015. node.front = this.front && this.front.clone();
  15016. node.back = this.back && this.back.clone();
  15017. node.polygons = this.polygons.map(function (p) {
  15018. return p.clone();
  15019. });
  15020. return node;
  15021. };
  15022. Node.prototype.invert = function () {
  15023. for (var i = 0; i < this.polygons.length; i++) {
  15024. this.polygons[i].flip();
  15025. }
  15026. if (this.plane) {
  15027. this.plane.flip();
  15028. }
  15029. if (this.front) {
  15030. this.front.invert();
  15031. }
  15032. if (this.back) {
  15033. this.back.invert();
  15034. }
  15035. var temp = this.front;
  15036. this.front = this.back;
  15037. this.back = temp;
  15038. };
  15039. Node.prototype.clipPolygons = function (polygons) {
  15040. if (!this.plane)
  15041. return polygons.slice();
  15042. var front = [], back = [];
  15043. for (var i = 0; i < polygons.length; i++) {
  15044. this.plane.splitPolygon(polygons[i], front, back, front, back);
  15045. }
  15046. if (this.front) {
  15047. front = this.front.clipPolygons(front);
  15048. }
  15049. if (this.back) {
  15050. back = this.back.clipPolygons(back);
  15051. } else {
  15052. back = [];
  15053. }
  15054. return front.concat(back);
  15055. };
  15056. Node.prototype.clipTo = function (bsp) {
  15057. this.polygons = bsp.clipPolygons(this.polygons);
  15058. if (this.front)
  15059. this.front.clipTo(bsp);
  15060. if (this.back)
  15061. this.back.clipTo(bsp);
  15062. };
  15063. Node.prototype.allPolygons = function () {
  15064. var polygons = this.polygons.slice();
  15065. if (this.front)
  15066. polygons = polygons.concat(this.front.allPolygons());
  15067. if (this.back)
  15068. polygons = polygons.concat(this.back.allPolygons());
  15069. return polygons;
  15070. };
  15071. Node.prototype.build = function (polygons) {
  15072. if (!polygons.length)
  15073. return;
  15074. if (!this.plane)
  15075. this.plane = polygons[0].plane.clone();
  15076. var front = [], back = [];
  15077. for (var i = 0; i < polygons.length; i++) {
  15078. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  15079. }
  15080. if (front.length) {
  15081. if (!this.front)
  15082. this.front = new Node();
  15083. this.front.build(front);
  15084. }
  15085. if (back.length) {
  15086. if (!this.back)
  15087. this.back = new Node();
  15088. this.back.build(back);
  15089. }
  15090. };
  15091. return Node;
  15092. })();
  15093. var CSG = (function () {
  15094. function CSG() {
  15095. this.polygons = new Array();
  15096. }
  15097. CSG.FromMesh = function (mesh) {
  15098. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  15099. if (mesh instanceof BABYLON.Mesh) {
  15100. mesh.computeWorldMatrix(true);
  15101. var matrix = mesh.getWorldMatrix();
  15102. var meshPosition = mesh.position.clone();
  15103. var meshRotation = mesh.rotation.clone();
  15104. var meshScaling = mesh.scaling.clone();
  15105. } else {
  15106. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  15107. }
  15108. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15109. var subMeshes = mesh.subMeshes;
  15110. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  15111. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  15112. vertices = [];
  15113. for (var j = 0; j < 3; j++) {
  15114. normal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  15115. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  15116. position = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  15117. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, position);
  15118. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  15119. vertex = new Vertex(position, normal, uv);
  15120. vertices.push(vertex);
  15121. }
  15122. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  15123. if (polygon.plane)
  15124. polygons.push(polygon);
  15125. }
  15126. }
  15127. var csg = CSG.FromPolygons(polygons);
  15128. csg.matrix = matrix;
  15129. csg.position = meshPosition;
  15130. csg.rotation = meshRotation;
  15131. csg.scaling = meshScaling;
  15132. currentCSGMeshId++;
  15133. return csg;
  15134. };
  15135. CSG.FromPolygons = function (polygons) {
  15136. var csg = new BABYLON.CSG();
  15137. csg.polygons = polygons;
  15138. return csg;
  15139. };
  15140. CSG.prototype.clone = function () {
  15141. var csg = new BABYLON.CSG();
  15142. csg.polygons = this.polygons.map(function (p) {
  15143. return p.clone();
  15144. });
  15145. csg.copyTransformAttributes(this);
  15146. return csg;
  15147. };
  15148. CSG.prototype.toPolygons = function () {
  15149. return this.polygons;
  15150. };
  15151. CSG.prototype.union = function (csg) {
  15152. var a = new Node(this.clone().polygons);
  15153. var b = new Node(csg.clone().polygons);
  15154. a.clipTo(b);
  15155. b.clipTo(a);
  15156. b.invert();
  15157. b.clipTo(a);
  15158. b.invert();
  15159. a.build(b.allPolygons());
  15160. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15161. };
  15162. CSG.prototype.unionInPlace = function (csg) {
  15163. var a = new Node(this.polygons);
  15164. var b = new Node(csg.polygons);
  15165. a.clipTo(b);
  15166. b.clipTo(a);
  15167. b.invert();
  15168. b.clipTo(a);
  15169. b.invert();
  15170. a.build(b.allPolygons());
  15171. this.polygons = a.allPolygons();
  15172. };
  15173. CSG.prototype.subtract = function (csg) {
  15174. var a = new Node(this.clone().polygons);
  15175. var b = new Node(csg.clone().polygons);
  15176. a.invert();
  15177. a.clipTo(b);
  15178. b.clipTo(a);
  15179. b.invert();
  15180. b.clipTo(a);
  15181. b.invert();
  15182. a.build(b.allPolygons());
  15183. a.invert();
  15184. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15185. };
  15186. CSG.prototype.subtractInPlace = function (csg) {
  15187. var a = new Node(this.polygons);
  15188. var b = new Node(csg.polygons);
  15189. a.invert();
  15190. a.clipTo(b);
  15191. b.clipTo(a);
  15192. b.invert();
  15193. b.clipTo(a);
  15194. b.invert();
  15195. a.build(b.allPolygons());
  15196. a.invert();
  15197. this.polygons = a.allPolygons();
  15198. };
  15199. CSG.prototype.intersect = function (csg) {
  15200. var a = new Node(this.clone().polygons);
  15201. var b = new Node(csg.clone().polygons);
  15202. a.invert();
  15203. b.clipTo(a);
  15204. b.invert();
  15205. a.clipTo(b);
  15206. b.clipTo(a);
  15207. a.build(b.allPolygons());
  15208. a.invert();
  15209. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15210. };
  15211. CSG.prototype.intersectInPlace = function (csg) {
  15212. var a = new Node(this.polygons);
  15213. var b = new Node(csg.polygons);
  15214. a.invert();
  15215. b.clipTo(a);
  15216. b.invert();
  15217. a.clipTo(b);
  15218. b.clipTo(a);
  15219. a.build(b.allPolygons());
  15220. a.invert();
  15221. this.polygons = a.allPolygons();
  15222. };
  15223. CSG.prototype.inverse = function () {
  15224. var csg = this.clone();
  15225. csg.inverseInPlace();
  15226. return csg;
  15227. };
  15228. CSG.prototype.inverseInPlace = function () {
  15229. this.polygons.map(function (p) {
  15230. p.flip();
  15231. });
  15232. };
  15233. CSG.prototype.copyTransformAttributes = function (csg) {
  15234. this.matrix = csg.matrix;
  15235. this.position = csg.position;
  15236. this.rotation = csg.rotation;
  15237. this.scaling = csg.scaling;
  15238. return this;
  15239. };
  15240. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  15241. var matrix = this.matrix.clone();
  15242. matrix.invert();
  15243. 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;
  15244. if (keepSubMeshes) {
  15245. polygons.sort(function (a, b) {
  15246. if (a.shared.meshId === b.shared.meshId) {
  15247. return a.shared.subMeshId - b.shared.subMeshId;
  15248. } else {
  15249. return a.shared.meshId - b.shared.meshId;
  15250. }
  15251. });
  15252. }
  15253. for (var i = 0, il = polygons.length; i < il; i++) {
  15254. polygon = polygons[i];
  15255. if (!subMesh_dict[polygon.shared.meshId]) {
  15256. subMesh_dict[polygon.shared.meshId] = {};
  15257. }
  15258. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  15259. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  15260. indexStart: +Infinity,
  15261. indexEnd: -Infinity,
  15262. materialIndex: polygon.shared.materialIndex
  15263. };
  15264. }
  15265. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  15266. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  15267. polygonIndices[0] = 0;
  15268. polygonIndices[1] = j - 1;
  15269. polygonIndices[2] = j;
  15270. for (var k = 0; k < 3; k++) {
  15271. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  15272. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  15273. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  15274. BABYLON.Vector3.TransformCoordinatesToRef(vertex, matrix, vertex);
  15275. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  15276. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z];
  15277. if (!(typeof vertex_idx !== 'undefined' && normals[vertex_idx * 3] === normal.x && normals[vertex_idx * 3 + 1] === normal.y && normals[vertex_idx * 3 + 2] === normal.z && uvs[vertex_idx * 2] === uv.x && uvs[vertex_idx * 2 + 1] === uv.y)) {
  15278. vertices.push(vertex.x, vertex.y, vertex.z);
  15279. uvs.push(uv.x, uv.y);
  15280. normals.push(normal.x, normal.y, normal.z);
  15281. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z] = (vertices.length / 3) - 1;
  15282. }
  15283. indices.push(vertex_idx);
  15284. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  15285. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  15286. currentIndex++;
  15287. }
  15288. }
  15289. }
  15290. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  15291. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15292. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  15293. mesh.setIndices(indices);
  15294. if (keepSubMeshes) {
  15295. var materialIndexOffset = 0, materialMaxIndex;
  15296. mesh.subMeshes.length = 0;
  15297. for (var m in subMesh_dict) {
  15298. materialMaxIndex = -1;
  15299. for (var sm in subMesh_dict[m]) {
  15300. subMesh_obj = subMesh_dict[m][sm];
  15301. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  15302. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  15303. }
  15304. materialIndexOffset += ++materialMaxIndex;
  15305. }
  15306. }
  15307. return mesh;
  15308. };
  15309. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  15310. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  15311. mesh.material = material;
  15312. mesh.position.copyFrom(this.position);
  15313. mesh.rotation.copyFrom(this.rotation);
  15314. mesh.scaling.copyFrom(this.scaling);
  15315. mesh.computeWorldMatrix(true);
  15316. return mesh;
  15317. };
  15318. return CSG;
  15319. })();
  15320. BABYLON.CSG = CSG;
  15321. })(BABYLON || (BABYLON = {}));
  15322. var __extends = this.__extends || function (d, b) {
  15323. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15324. function __() { this.constructor = d; }
  15325. __.prototype = b.prototype;
  15326. d.prototype = new __();
  15327. };
  15328. var BABYLON;
  15329. (function (BABYLON) {
  15330. var OculusDistortionCorrectionPostProcess = (function (_super) {
  15331. __extends(OculusDistortionCorrectionPostProcess, _super);
  15332. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  15333. var _this = this;
  15334. _super.call(this, name, "oculusDistortionCorrection", [
  15335. 'LensCenter',
  15336. 'Scale',
  15337. 'ScaleIn',
  15338. 'HmdWarpParam'
  15339. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  15340. this._isRightEye = isRightEye;
  15341. this._distortionFactors = cameraSettings.DistortionK;
  15342. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  15343. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  15344. this.onSizeChanged = function () {
  15345. _this.aspectRatio = _this.width * .5 / _this.height;
  15346. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  15347. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  15348. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  15349. };
  15350. this.onApply = function (effect) {
  15351. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  15352. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  15353. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  15354. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  15355. };
  15356. }
  15357. return OculusDistortionCorrectionPostProcess;
  15358. })(BABYLON.PostProcess);
  15359. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  15360. })(BABYLON || (BABYLON = {}));
  15361. var BABYLON;
  15362. (function (BABYLON) {
  15363. (function (JoystickAxis) {
  15364. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  15365. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  15366. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  15367. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  15368. var JoystickAxis = BABYLON.JoystickAxis;
  15369. var VirtualJoystick = (function () {
  15370. function VirtualJoystick(leftJoystick) {
  15371. var _this = this;
  15372. if (leftJoystick) {
  15373. this._leftJoystick = true;
  15374. } else {
  15375. this._leftJoystick = false;
  15376. }
  15377. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  15378. VirtualJoystick._globalJoystickIndex++;
  15379. this._axisTargetedByLeftAndRight = 0 /* X */;
  15380. this._axisTargetedByUpAndDown = 1 /* Y */;
  15381. this.reverseLeftRight = false;
  15382. this.reverseUpDown = false;
  15383. this._touches = new BABYLON.VirtualJoystick.Collection();
  15384. this.deltaPosition = BABYLON.Vector3.Zero();
  15385. this._joystickSensibility = 25;
  15386. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  15387. this._rotationSpeed = 25;
  15388. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  15389. this._rotateOnAxisRelativeToMesh = false;
  15390. if (!VirtualJoystick.vjCanvas) {
  15391. window.addEventListener("resize", function () {
  15392. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  15393. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  15394. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  15395. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  15396. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  15397. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  15398. }, false);
  15399. VirtualJoystick.vjCanvas = document.createElement("canvas");
  15400. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  15401. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  15402. VirtualJoystick.vjCanvas.width = window.innerWidth;
  15403. VirtualJoystick.vjCanvas.height = window.innerHeight;
  15404. VirtualJoystick.vjCanvas.style.width = "100%";
  15405. VirtualJoystick.vjCanvas.style.height = "100%";
  15406. VirtualJoystick.vjCanvas.style.position = "absolute";
  15407. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  15408. VirtualJoystick.vjCanvas.style.top = "0px";
  15409. VirtualJoystick.vjCanvas.style.left = "0px";
  15410. VirtualJoystick.vjCanvas.style.zIndex = "5";
  15411. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  15412. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  15413. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  15414. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  15415. document.body.appendChild(VirtualJoystick.vjCanvas);
  15416. }
  15417. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  15418. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  15419. this.pressed = false;
  15420. this._joystickColor = "cyan";
  15421. this._joystickPointerID = -1;
  15422. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  15423. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  15424. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  15425. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  15426. _this._onPointerDown(evt);
  15427. }, false);
  15428. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  15429. _this._onPointerMove(evt);
  15430. }, false);
  15431. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  15432. _this._onPointerUp(evt);
  15433. }, false);
  15434. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  15435. _this._onPointerUp(evt);
  15436. }, false);
  15437. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  15438. evt.preventDefault();
  15439. }, false);
  15440. requestAnimationFrame(function () {
  15441. _this._drawVirtualJoystick();
  15442. });
  15443. }
  15444. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  15445. this._joystickSensibility = newJoystickSensibility;
  15446. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  15447. };
  15448. VirtualJoystick.prototype._onPointerDown = function (e) {
  15449. var positionOnScreenCondition;
  15450. e.preventDefault();
  15451. if (this._leftJoystick === true) {
  15452. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  15453. } else {
  15454. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  15455. }
  15456. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  15457. this._joystickPointerID = e.pointerId;
  15458. this._joystickPointerStartPos.x = e.clientX;
  15459. this._joystickPointerStartPos.y = e.clientY;
  15460. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  15461. this._deltaJoystickVector.x = 0;
  15462. this._deltaJoystickVector.y = 0;
  15463. this.pressed = true;
  15464. this._touches.add(e.pointerId.toString(), e);
  15465. } else {
  15466. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  15467. this._action();
  15468. this._touches.add(e.pointerId.toString(), e);
  15469. }
  15470. }
  15471. };
  15472. VirtualJoystick.prototype._onPointerMove = function (e) {
  15473. if (this._joystickPointerID == e.pointerId) {
  15474. this._joystickPointerPos.x = e.clientX;
  15475. this._joystickPointerPos.y = e.clientY;
  15476. this._deltaJoystickVector = this._joystickPointerPos.clone();
  15477. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  15478. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  15479. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  15480. switch (this._axisTargetedByLeftAndRight) {
  15481. case 0 /* X */:
  15482. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  15483. break;
  15484. case 1 /* Y */:
  15485. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  15486. break;
  15487. case 2 /* Z */:
  15488. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  15489. break;
  15490. }
  15491. var directionUpDown = this.reverseUpDown ? 1 : -1;
  15492. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  15493. switch (this._axisTargetedByUpAndDown) {
  15494. case 0 /* X */:
  15495. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  15496. break;
  15497. case 1 /* Y */:
  15498. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  15499. break;
  15500. case 2 /* Z */:
  15501. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  15502. break;
  15503. }
  15504. } else {
  15505. if (this._touches.item(e.pointerId.toString())) {
  15506. this._touches.item(e.pointerId.toString()).x = e.clientX;
  15507. this._touches.item(e.pointerId.toString()).y = e.clientY;
  15508. }
  15509. }
  15510. };
  15511. VirtualJoystick.prototype._onPointerUp = function (e) {
  15512. this._clearCanvas();
  15513. if (this._joystickPointerID == e.pointerId) {
  15514. this._joystickPointerID = -1;
  15515. this.pressed = false;
  15516. }
  15517. this._deltaJoystickVector.x = 0;
  15518. this._deltaJoystickVector.y = 0;
  15519. this._touches.remove(e.pointerId.toString());
  15520. };
  15521. /**
  15522. * Change the color of the virtual joystick
  15523. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  15524. */
  15525. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  15526. this._joystickColor = newColor;
  15527. };
  15528. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  15529. this._action = action;
  15530. };
  15531. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  15532. switch (axis) {
  15533. case 0 /* X */:
  15534. case 1 /* Y */:
  15535. case 2 /* Z */:
  15536. this._axisTargetedByLeftAndRight = axis;
  15537. break;
  15538. default:
  15539. this._axisTargetedByLeftAndRight = 0 /* X */;
  15540. break;
  15541. }
  15542. };
  15543. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  15544. switch (axis) {
  15545. case 0 /* X */:
  15546. case 1 /* Y */:
  15547. case 2 /* Z */:
  15548. this._axisTargetedByUpAndDown = axis;
  15549. break;
  15550. default:
  15551. this._axisTargetedByUpAndDown = 1 /* Y */;
  15552. break;
  15553. }
  15554. };
  15555. VirtualJoystick.prototype._clearCanvas = function () {
  15556. if (this._leftJoystick) {
  15557. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  15558. } else {
  15559. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  15560. }
  15561. };
  15562. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  15563. var _this = this;
  15564. if (this.pressed) {
  15565. this._clearCanvas();
  15566. this._touches.forEach(function (touch) {
  15567. if (touch.pointerId === _this._joystickPointerID) {
  15568. VirtualJoystick.vjCanvasContext.beginPath();
  15569. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15570. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  15571. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  15572. VirtualJoystick.vjCanvasContext.stroke();
  15573. VirtualJoystick.vjCanvasContext.beginPath();
  15574. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15575. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  15576. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  15577. VirtualJoystick.vjCanvasContext.stroke();
  15578. VirtualJoystick.vjCanvasContext.beginPath();
  15579. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15580. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  15581. VirtualJoystick.vjCanvasContext.stroke();
  15582. } else {
  15583. VirtualJoystick.vjCanvasContext.beginPath();
  15584. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  15585. VirtualJoystick.vjCanvasContext.beginPath();
  15586. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  15587. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  15588. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  15589. VirtualJoystick.vjCanvasContext.stroke();
  15590. }
  15591. ;
  15592. });
  15593. }
  15594. requestAnimationFrame(function () {
  15595. _this._drawVirtualJoystick();
  15596. });
  15597. };
  15598. VirtualJoystick.prototype.releaseCanvas = function () {
  15599. if (VirtualJoystick.vjCanvas) {
  15600. document.body.removeChild(VirtualJoystick.vjCanvas);
  15601. VirtualJoystick.vjCanvas = null;
  15602. }
  15603. };
  15604. VirtualJoystick._globalJoystickIndex = 0;
  15605. return VirtualJoystick;
  15606. })();
  15607. BABYLON.VirtualJoystick = VirtualJoystick;
  15608. })(BABYLON || (BABYLON = {}));
  15609. var BABYLON;
  15610. (function (BABYLON) {
  15611. (function (VirtualJoystick) {
  15612. var Collection = (function () {
  15613. function Collection() {
  15614. this._count = 0;
  15615. this._collection = new Array();
  15616. }
  15617. Collection.prototype.Count = function () {
  15618. return this._count;
  15619. };
  15620. Collection.prototype.add = function (key, item) {
  15621. if (this._collection[key] != undefined) {
  15622. return undefined;
  15623. }
  15624. this._collection[key] = item;
  15625. return ++this._count;
  15626. };
  15627. Collection.prototype.remove = function (key) {
  15628. if (this._collection[key] == undefined) {
  15629. return undefined;
  15630. }
  15631. delete this._collection[key];
  15632. return --this._count;
  15633. };
  15634. Collection.prototype.item = function (key) {
  15635. return this._collection[key];
  15636. };
  15637. Collection.prototype.forEach = function (block) {
  15638. var key;
  15639. for (key in this._collection) {
  15640. if (this._collection.hasOwnProperty(key)) {
  15641. block(this._collection[key]);
  15642. }
  15643. }
  15644. };
  15645. return Collection;
  15646. })();
  15647. VirtualJoystick.Collection = Collection;
  15648. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  15649. var VirtualJoystick = BABYLON.VirtualJoystick;
  15650. })(BABYLON || (BABYLON = {}));
  15651. var __extends = this.__extends || function (d, b) {
  15652. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15653. function __() { this.constructor = d; }
  15654. __.prototype = b.prototype;
  15655. d.prototype = new __();
  15656. };
  15657. var BABYLON;
  15658. (function (BABYLON) {
  15659. var OculusRiftDevKit2013_Metric = {
  15660. HResolution: 1280,
  15661. VResolution: 800,
  15662. HScreenSize: 0.149759993,
  15663. VScreenSize: 0.0935999975,
  15664. VScreenCenter: 0.0467999987,
  15665. EyeToScreenDistance: 0.0410000011,
  15666. LensSeparationDistance: 0.0635000020,
  15667. InterpupillaryDistance: 0.0640000030,
  15668. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  15669. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  15670. PostProcessScaleFactor: 1.714605507808412,
  15671. LensCenterOffset: 0.151976421
  15672. };
  15673. var _OculusInnerCamera = (function (_super) {
  15674. __extends(_OculusInnerCamera, _super);
  15675. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  15676. _super.call(this, name, position, scene);
  15677. this._workMatrix = new BABYLON.Matrix();
  15678. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  15679. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  15680. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  15681. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  15682. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  15683. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  15684. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  15685. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  15686. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  15687. }
  15688. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  15689. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  15690. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  15691. return this._projectionMatrix;
  15692. };
  15693. _OculusInnerCamera.prototype._getViewMatrix = function () {
  15694. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  15695. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  15696. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  15697. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  15698. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  15699. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  15700. return this._viewMatrix;
  15701. };
  15702. return _OculusInnerCamera;
  15703. })(BABYLON.FreeCamera);
  15704. var OculusCamera = (function (_super) {
  15705. __extends(OculusCamera, _super);
  15706. function OculusCamera(name, position, scene) {
  15707. _super.call(this, name, position, scene);
  15708. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  15709. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  15710. this.subCameras.push(this._leftCamera);
  15711. this.subCameras.push(this._rightCamera);
  15712. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  15713. }
  15714. OculusCamera.prototype._update = function () {
  15715. this._leftCamera.position.copyFrom(this.position);
  15716. this._rightCamera.position.copyFrom(this.position);
  15717. this._updateCamera(this._leftCamera);
  15718. this._updateCamera(this._rightCamera);
  15719. _super.prototype._update.call(this);
  15720. };
  15721. OculusCamera.prototype._updateCamera = function (camera) {
  15722. camera.minZ = this.minZ;
  15723. camera.maxZ = this.maxZ;
  15724. camera.rotation.x = this.rotation.x;
  15725. camera.rotation.y = this.rotation.y;
  15726. camera.rotation.z = this.rotation.z;
  15727. };
  15728. OculusCamera.prototype._onOrientationEvent = function (evt) {
  15729. var yaw = evt.alpha / 180 * Math.PI;
  15730. var pitch = evt.beta / 180 * Math.PI;
  15731. var roll = evt.gamma / 180 * Math.PI;
  15732. if (!this._offsetOrientation) {
  15733. this._offsetOrientation = {
  15734. yaw: yaw,
  15735. pitch: pitch,
  15736. roll: roll
  15737. };
  15738. return;
  15739. } else {
  15740. this.rotation.y += yaw - this._offsetOrientation.yaw;
  15741. this.rotation.x += pitch - this._offsetOrientation.pitch;
  15742. this.rotation.z += this._offsetOrientation.roll - roll;
  15743. this._offsetOrientation.yaw = yaw;
  15744. this._offsetOrientation.pitch = pitch;
  15745. this._offsetOrientation.roll = roll;
  15746. }
  15747. };
  15748. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  15749. _super.prototype.attachControl.call(this, element, noPreventDefault);
  15750. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  15751. };
  15752. OculusCamera.prototype.detachControl = function (element) {
  15753. _super.prototype.detachControl.call(this, element);
  15754. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  15755. };
  15756. return OculusCamera;
  15757. })(BABYLON.FreeCamera);
  15758. BABYLON.OculusCamera = OculusCamera;
  15759. })(BABYLON || (BABYLON = {}));
  15760. var __extends = this.__extends || function (d, b) {
  15761. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15762. function __() { this.constructor = d; }
  15763. __.prototype = b.prototype;
  15764. d.prototype = new __();
  15765. };
  15766. var BABYLON;
  15767. (function (BABYLON) {
  15768. var VirtualJoysticksCamera = (function (_super) {
  15769. __extends(VirtualJoysticksCamera, _super);
  15770. function VirtualJoysticksCamera(name, position, scene) {
  15771. _super.call(this, name, position, scene);
  15772. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  15773. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  15774. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  15775. this._leftjoystick.setJoystickSensibility(0.15);
  15776. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  15777. this._rightjoystick.setAxisForUpDown(0 /* X */);
  15778. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  15779. this._rightjoystick.reverseUpDown = true;
  15780. this._rightjoystick.setJoystickSensibility(0.05);
  15781. this._rightjoystick.setJoystickColor("yellow");
  15782. }
  15783. VirtualJoysticksCamera.prototype._checkInputs = function () {
  15784. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  15785. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  15786. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  15787. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  15788. if (!this._leftjoystick.pressed) {
  15789. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  15790. }
  15791. if (!this._rightjoystick.pressed) {
  15792. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  15793. }
  15794. };
  15795. VirtualJoysticksCamera.prototype.dispose = function () {
  15796. this._leftjoystick.releaseCanvas();
  15797. _super.prototype.dispose.call(this);
  15798. };
  15799. return VirtualJoysticksCamera;
  15800. })(BABYLON.FreeCamera);
  15801. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  15802. })(BABYLON || (BABYLON = {}));
  15803. var __extends = this.__extends || function (d, b) {
  15804. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15805. function __() { this.constructor = d; }
  15806. __.prototype = b.prototype;
  15807. d.prototype = new __();
  15808. };
  15809. var BABYLON;
  15810. (function (BABYLON) {
  15811. var ShaderMaterial = (function (_super) {
  15812. __extends(ShaderMaterial, _super);
  15813. function ShaderMaterial(name, scene, shaderPath, options) {
  15814. _super.call(this, name, scene);
  15815. this._textures = new Array();
  15816. this._floats = new Array();
  15817. this._floatsArrays = {};
  15818. this._colors3 = new Array();
  15819. this._colors4 = new Array();
  15820. this._vectors2 = new Array();
  15821. this._vectors3 = new Array();
  15822. this._matrices = new Array();
  15823. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  15824. this._shaderPath = shaderPath;
  15825. options.needAlphaBlending = options.needAlphaBlending || false;
  15826. options.needAlphaTesting = options.needAlphaTesting || false;
  15827. options.attributes = options.attributes || ["position", "normal", "uv"];
  15828. options.uniforms = options.uniforms || ["worldViewProjection"];
  15829. options.samplers = options.samplers || [];
  15830. this._options = options;
  15831. }
  15832. ShaderMaterial.prototype.needAlphaBlending = function () {
  15833. return this._options.needAlphaBlending;
  15834. };
  15835. ShaderMaterial.prototype.needAlphaTesting = function () {
  15836. return this._options.needAlphaTesting;
  15837. };
  15838. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  15839. if (this._options.uniforms.indexOf(uniformName) === -1) {
  15840. this._options.uniforms.push(uniformName);
  15841. }
  15842. };
  15843. ShaderMaterial.prototype.setTexture = function (name, texture) {
  15844. if (this._options.samplers.indexOf(name) === -1) {
  15845. this._options.samplers.push(name);
  15846. }
  15847. this._textures[name] = texture;
  15848. return this;
  15849. };
  15850. ShaderMaterial.prototype.setFloat = function (name, value) {
  15851. this._checkUniform(name);
  15852. this._floats[name] = value;
  15853. return this;
  15854. };
  15855. ShaderMaterial.prototype.setFloats = function (name, value) {
  15856. this._checkUniform(name);
  15857. this._floatsArrays[name] = value;
  15858. return this;
  15859. };
  15860. ShaderMaterial.prototype.setColor3 = function (name, value) {
  15861. this._checkUniform(name);
  15862. this._colors3[name] = value;
  15863. return this;
  15864. };
  15865. ShaderMaterial.prototype.setColor4 = function (name, value) {
  15866. this._checkUniform(name);
  15867. this._colors4[name] = value;
  15868. return this;
  15869. };
  15870. ShaderMaterial.prototype.setVector2 = function (name, value) {
  15871. this._checkUniform(name);
  15872. this._vectors2[name] = value;
  15873. return this;
  15874. };
  15875. ShaderMaterial.prototype.setVector3 = function (name, value) {
  15876. this._checkUniform(name);
  15877. this._vectors3[name] = value;
  15878. return this;
  15879. };
  15880. ShaderMaterial.prototype.setMatrix = function (name, value) {
  15881. this._checkUniform(name);
  15882. this._matrices[name] = value;
  15883. return this;
  15884. };
  15885. ShaderMaterial.prototype.isReady = function () {
  15886. var engine = this.getScene().getEngine();
  15887. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  15888. if (!this._effect.isReady()) {
  15889. return false;
  15890. }
  15891. return true;
  15892. };
  15893. ShaderMaterial.prototype.bind = function (world) {
  15894. if (this._options.uniforms.indexOf("world") !== -1) {
  15895. this._effect.setMatrix("world", world);
  15896. }
  15897. if (this._options.uniforms.indexOf("view") !== -1) {
  15898. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  15899. }
  15900. if (this._options.uniforms.indexOf("worldView") !== -1) {
  15901. world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
  15902. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  15903. }
  15904. if (this._options.uniforms.indexOf("projection") !== -1) {
  15905. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  15906. }
  15907. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  15908. this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
  15909. }
  15910. for (var name in this._textures) {
  15911. this._effect.setTexture(name, this._textures[name]);
  15912. }
  15913. for (name in this._floats) {
  15914. this._effect.setFloat(name, this._floats[name]);
  15915. }
  15916. for (name in this._floatsArrays) {
  15917. this._effect.setArray(name, this._floatsArrays[name]);
  15918. }
  15919. for (name in this._colors3) {
  15920. this._effect.setColor3(name, this._colors3[name]);
  15921. }
  15922. for (name in this._colors4) {
  15923. var color = this._colors4[name];
  15924. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  15925. }
  15926. for (name in this._vectors2) {
  15927. this._effect.setVector2(name, this._vectors2[name]);
  15928. }
  15929. for (name in this._vectors3) {
  15930. this._effect.setVector3(name, this._vectors3[name]);
  15931. }
  15932. for (name in this._matrices) {
  15933. this._effect.setMatrix(name, this._matrices[name]);
  15934. }
  15935. };
  15936. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  15937. for (var name in this._textures) {
  15938. this._textures[name].dispose();
  15939. }
  15940. this._textures = [];
  15941. _super.prototype.dispose.call(this, forceDisposeEffect);
  15942. };
  15943. return ShaderMaterial;
  15944. })(BABYLON.Material);
  15945. BABYLON.ShaderMaterial = ShaderMaterial;
  15946. })(BABYLON || (BABYLON = {}));
  15947. var BABYLON;
  15948. (function (BABYLON) {
  15949. var VertexData = (function () {
  15950. function VertexData() {
  15951. }
  15952. VertexData.prototype.set = function (data, kind) {
  15953. switch (kind) {
  15954. case BABYLON.VertexBuffer.PositionKind:
  15955. this.positions = data;
  15956. break;
  15957. case BABYLON.VertexBuffer.NormalKind:
  15958. this.normals = data;
  15959. break;
  15960. case BABYLON.VertexBuffer.UVKind:
  15961. this.uvs = data;
  15962. break;
  15963. case BABYLON.VertexBuffer.UV2Kind:
  15964. this.uv2s = data;
  15965. break;
  15966. case BABYLON.VertexBuffer.ColorKind:
  15967. this.colors = data;
  15968. break;
  15969. case BABYLON.VertexBuffer.MatricesIndicesKind:
  15970. this.matricesIndices = data;
  15971. break;
  15972. case BABYLON.VertexBuffer.MatricesWeightsKind:
  15973. this.matricesWeights = data;
  15974. break;
  15975. }
  15976. };
  15977. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  15978. this._applyTo(mesh, updatable);
  15979. };
  15980. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  15981. this._applyTo(geometry, updatable);
  15982. };
  15983. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  15984. this._update(mesh);
  15985. };
  15986. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  15987. this._update(geometry);
  15988. };
  15989. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  15990. if (this.positions) {
  15991. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  15992. }
  15993. if (this.normals) {
  15994. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  15995. }
  15996. if (this.uvs) {
  15997. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  15998. }
  15999. if (this.uv2s) {
  16000. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  16001. }
  16002. if (this.colors) {
  16003. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  16004. }
  16005. if (this.matricesIndices) {
  16006. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  16007. }
  16008. if (this.matricesWeights) {
  16009. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  16010. }
  16011. if (this.indices) {
  16012. meshOrGeometry.setIndices(this.indices);
  16013. }
  16014. };
  16015. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  16016. if (this.positions) {
  16017. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  16018. }
  16019. if (this.normals) {
  16020. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  16021. }
  16022. if (this.uvs) {
  16023. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  16024. }
  16025. if (this.uv2s) {
  16026. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  16027. }
  16028. if (this.colors) {
  16029. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  16030. }
  16031. if (this.matricesIndices) {
  16032. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  16033. }
  16034. if (this.matricesWeights) {
  16035. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  16036. }
  16037. if (this.indices) {
  16038. meshOrGeometry.setIndices(this.indices);
  16039. }
  16040. };
  16041. VertexData.prototype.transform = function (matrix) {
  16042. var transformed = BABYLON.Vector3.Zero();
  16043. if (this.positions) {
  16044. var position = BABYLON.Vector3.Zero();
  16045. for (var index = 0; index < this.positions.length; index += 3) {
  16046. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  16047. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  16048. this.positions[index] = transformed.x;
  16049. this.positions[index + 1] = transformed.y;
  16050. this.positions[index + 2] = transformed.z;
  16051. }
  16052. }
  16053. if (this.normals) {
  16054. var normal = BABYLON.Vector3.Zero();
  16055. for (index = 0; index < this.normals.length; index += 3) {
  16056. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  16057. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  16058. this.normals[index] = transformed.x;
  16059. this.normals[index + 1] = transformed.y;
  16060. this.normals[index + 2] = transformed.z;
  16061. }
  16062. }
  16063. };
  16064. VertexData.prototype.merge = function (other) {
  16065. if (other.indices) {
  16066. if (!this.indices) {
  16067. this.indices = [];
  16068. }
  16069. var offset = this.positions ? this.positions.length / 3 : 0;
  16070. for (var index = 0; index < other.indices.length; index++) {
  16071. this.indices.push(other.indices[index] + offset);
  16072. }
  16073. }
  16074. if (other.positions) {
  16075. if (!this.positions) {
  16076. this.positions = [];
  16077. }
  16078. for (index = 0; index < other.positions.length; index++) {
  16079. this.positions.push(other.positions[index]);
  16080. }
  16081. }
  16082. if (other.normals) {
  16083. if (!this.normals) {
  16084. this.normals = [];
  16085. }
  16086. for (index = 0; index < other.normals.length; index++) {
  16087. this.normals.push(other.normals[index]);
  16088. }
  16089. }
  16090. if (other.uvs) {
  16091. if (!this.uvs) {
  16092. this.uvs = [];
  16093. }
  16094. for (index = 0; index < other.uvs.length; index++) {
  16095. this.uvs.push(other.uvs[index]);
  16096. }
  16097. }
  16098. if (other.uv2s) {
  16099. if (!this.uv2s) {
  16100. this.uv2s = [];
  16101. }
  16102. for (index = 0; index < other.uv2s.length; index++) {
  16103. this.uv2s.push(other.uv2s[index]);
  16104. }
  16105. }
  16106. if (other.matricesIndices) {
  16107. if (!this.matricesIndices) {
  16108. this.matricesIndices = [];
  16109. }
  16110. for (index = 0; index < other.matricesIndices.length; index++) {
  16111. this.matricesIndices.push(other.matricesIndices[index]);
  16112. }
  16113. }
  16114. if (other.matricesWeights) {
  16115. if (!this.matricesWeights) {
  16116. this.matricesWeights = [];
  16117. }
  16118. for (index = 0; index < other.matricesWeights.length; index++) {
  16119. this.matricesWeights.push(other.matricesWeights[index]);
  16120. }
  16121. }
  16122. if (other.colors) {
  16123. if (!this.colors) {
  16124. this.colors = [];
  16125. }
  16126. for (index = 0; index < other.colors.length; index++) {
  16127. this.colors.push(other.colors[index]);
  16128. }
  16129. }
  16130. };
  16131. VertexData.ExtractFromMesh = function (mesh) {
  16132. return VertexData._ExtractFrom(mesh);
  16133. };
  16134. VertexData.ExtractFromGeometry = function (geometry) {
  16135. return VertexData._ExtractFrom(geometry);
  16136. };
  16137. VertexData._ExtractFrom = function (meshOrGeometry) {
  16138. var result = new BABYLON.VertexData();
  16139. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16140. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16141. }
  16142. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16143. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16144. }
  16145. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16146. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16147. }
  16148. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  16149. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  16150. }
  16151. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  16152. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  16153. }
  16154. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16155. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16156. }
  16157. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16158. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16159. }
  16160. result.indices = meshOrGeometry.getIndices();
  16161. return result;
  16162. };
  16163. VertexData.CreateBox = function (size) {
  16164. var normalsSource = [
  16165. new BABYLON.Vector3(0, 0, 1),
  16166. new BABYLON.Vector3(0, 0, -1),
  16167. new BABYLON.Vector3(1, 0, 0),
  16168. new BABYLON.Vector3(-1, 0, 0),
  16169. new BABYLON.Vector3(0, 1, 0),
  16170. new BABYLON.Vector3(0, -1, 0)
  16171. ];
  16172. var indices = [];
  16173. var positions = [];
  16174. var normals = [];
  16175. var uvs = [];
  16176. size = size || 1;
  16177. for (var index = 0; index < normalsSource.length; index++) {
  16178. var normal = normalsSource[index];
  16179. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  16180. var side2 = BABYLON.Vector3.Cross(normal, side1);
  16181. var verticesLength = positions.length / 3;
  16182. indices.push(verticesLength);
  16183. indices.push(verticesLength + 1);
  16184. indices.push(verticesLength + 2);
  16185. indices.push(verticesLength);
  16186. indices.push(verticesLength + 2);
  16187. indices.push(verticesLength + 3);
  16188. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  16189. positions.push(vertex.x, vertex.y, vertex.z);
  16190. normals.push(normal.x, normal.y, normal.z);
  16191. uvs.push(1.0, 1.0);
  16192. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  16193. positions.push(vertex.x, vertex.y, vertex.z);
  16194. normals.push(normal.x, normal.y, normal.z);
  16195. uvs.push(0.0, 1.0);
  16196. vertex = normal.add(side1).add(side2).scale(size / 2);
  16197. positions.push(vertex.x, vertex.y, vertex.z);
  16198. normals.push(normal.x, normal.y, normal.z);
  16199. uvs.push(0.0, 0.0);
  16200. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  16201. positions.push(vertex.x, vertex.y, vertex.z);
  16202. normals.push(normal.x, normal.y, normal.z);
  16203. uvs.push(1.0, 0.0);
  16204. }
  16205. var vertexData = new BABYLON.VertexData();
  16206. vertexData.indices = indices;
  16207. vertexData.positions = positions;
  16208. vertexData.normals = normals;
  16209. vertexData.uvs = uvs;
  16210. return vertexData;
  16211. };
  16212. VertexData.CreateSphere = function (segments, diameter) {
  16213. segments = segments || 32;
  16214. diameter = diameter || 1;
  16215. var radius = diameter / 2;
  16216. var totalZRotationSteps = 2 + segments;
  16217. var totalYRotationSteps = 2 * totalZRotationSteps;
  16218. var indices = [];
  16219. var positions = [];
  16220. var normals = [];
  16221. var uvs = [];
  16222. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  16223. var normalizedZ = zRotationStep / totalZRotationSteps;
  16224. var angleZ = (normalizedZ * Math.PI);
  16225. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  16226. var normalizedY = yRotationStep / totalYRotationSteps;
  16227. var angleY = normalizedY * Math.PI * 2;
  16228. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  16229. var rotationY = BABYLON.Matrix.RotationY(angleY);
  16230. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  16231. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  16232. var vertex = complete.scale(radius);
  16233. var normal = BABYLON.Vector3.Normalize(vertex);
  16234. positions.push(vertex.x, vertex.y, vertex.z);
  16235. normals.push(normal.x, normal.y, normal.z);
  16236. uvs.push(normalizedZ, normalizedY);
  16237. }
  16238. if (zRotationStep > 0) {
  16239. var verticesCount = positions.length / 3;
  16240. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  16241. indices.push((firstIndex));
  16242. indices.push((firstIndex + 1));
  16243. indices.push(firstIndex + totalYRotationSteps + 1);
  16244. indices.push((firstIndex + totalYRotationSteps + 1));
  16245. indices.push((firstIndex + 1));
  16246. indices.push((firstIndex + totalYRotationSteps + 2));
  16247. }
  16248. }
  16249. }
  16250. var vertexData = new BABYLON.VertexData();
  16251. vertexData.indices = indices;
  16252. vertexData.positions = positions;
  16253. vertexData.normals = normals;
  16254. vertexData.uvs = uvs;
  16255. return vertexData;
  16256. };
  16257. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  16258. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  16259. var radiusTop = diameterTop / 2;
  16260. var radiusBottom = diameterBottom / 2;
  16261. var indices = [];
  16262. var positions = [];
  16263. var normals = [];
  16264. var uvs = [];
  16265. height = height || 1;
  16266. diameterTop = diameterTop || 0.5;
  16267. diameterBottom = diameterBottom || 1;
  16268. tessellation = tessellation || 16;
  16269. subdivisions = subdivisions || 1;
  16270. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  16271. var getCircleVector = function (i) {
  16272. var angle = (i * 2.0 * Math.PI / tessellation);
  16273. var dx = Math.cos(angle);
  16274. var dz = Math.sin(angle);
  16275. return new BABYLON.Vector3(dx, 0, dz);
  16276. };
  16277. var createCylinderCap = function (isTop) {
  16278. var radius = isTop ? radiusTop : radiusBottom;
  16279. if (radius == 0) {
  16280. return;
  16281. }
  16282. var vbase = positions.length / 3;
  16283. var offset = new BABYLON.Vector3(0, height / 2, 0);
  16284. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  16285. if (!isTop) {
  16286. offset.scaleInPlace(-1);
  16287. textureScale.x = -textureScale.x;
  16288. }
  16289. for (i = 0; i < tessellation; i++) {
  16290. var circleVector = getCircleVector(i);
  16291. var position = circleVector.scale(radius).add(offset);
  16292. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  16293. positions.push(position.x, position.y, position.z);
  16294. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16295. }
  16296. for (var i = 0; i < tessellation - 2; i++) {
  16297. if (!isTop) {
  16298. indices.push(vbase);
  16299. indices.push(vbase + (i + 2) % tessellation);
  16300. indices.push(vbase + (i + 1) % tessellation);
  16301. } else {
  16302. indices.push(vbase);
  16303. indices.push(vbase + (i + 1) % tessellation);
  16304. indices.push(vbase + (i + 2) % tessellation);
  16305. }
  16306. }
  16307. };
  16308. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  16309. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  16310. var stride = tessellation + 1;
  16311. for (var i = 0; i <= tessellation; i++) {
  16312. var circleVector = getCircleVector(i);
  16313. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  16314. var position, radius = radiusBottom;
  16315. for (var s = 0; s <= subdivisions; s++) {
  16316. position = circleVector.scale(radius);
  16317. position.addInPlace(base.add(offset.scale(s)));
  16318. textureCoordinate.y += 1 / subdivisions;
  16319. radius += (radiusTop - radiusBottom) / subdivisions;
  16320. positions.push(position.x, position.y, position.z);
  16321. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16322. }
  16323. }
  16324. subdivisions += 1;
  16325. for (var s = 0; s < subdivisions - 1; s++) {
  16326. for (var i = 0; i <= tessellation; i++) {
  16327. indices.push(i * subdivisions + s);
  16328. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  16329. indices.push(i * subdivisions + (s + 1));
  16330. indices.push(i * subdivisions + (s + 1));
  16331. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  16332. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  16333. }
  16334. }
  16335. createCylinderCap(true);
  16336. createCylinderCap(false);
  16337. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16338. var vertexData = new BABYLON.VertexData();
  16339. vertexData.indices = indices;
  16340. vertexData.positions = positions;
  16341. vertexData.normals = normals;
  16342. vertexData.uvs = uvs;
  16343. return vertexData;
  16344. };
  16345. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  16346. var indices = [];
  16347. var positions = [];
  16348. var normals = [];
  16349. var uvs = [];
  16350. diameter = diameter || 1;
  16351. thickness = thickness || 0.5;
  16352. tessellation = tessellation || 16;
  16353. var stride = tessellation + 1;
  16354. for (var i = 0; i <= tessellation; i++) {
  16355. var u = i / tessellation;
  16356. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  16357. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  16358. for (var j = 0; j <= tessellation; j++) {
  16359. var v = 1 - j / tessellation;
  16360. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  16361. var dx = Math.cos(innerAngle);
  16362. var dy = Math.sin(innerAngle);
  16363. var normal = new BABYLON.Vector3(dx, dy, 0);
  16364. var position = normal.scale(thickness / 2);
  16365. var textureCoordinate = new BABYLON.Vector2(u, v);
  16366. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  16367. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  16368. positions.push(position.x, position.y, position.z);
  16369. normals.push(normal.x, normal.y, normal.z);
  16370. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16371. var nextI = (i + 1) % stride;
  16372. var nextJ = (j + 1) % stride;
  16373. indices.push(i * stride + j);
  16374. indices.push(i * stride + nextJ);
  16375. indices.push(nextI * stride + j);
  16376. indices.push(i * stride + nextJ);
  16377. indices.push(nextI * stride + nextJ);
  16378. indices.push(nextI * stride + j);
  16379. }
  16380. }
  16381. var vertexData = new BABYLON.VertexData();
  16382. vertexData.indices = indices;
  16383. vertexData.positions = positions;
  16384. vertexData.normals = normals;
  16385. vertexData.uvs = uvs;
  16386. return vertexData;
  16387. };
  16388. VertexData.CreateLines = function (points) {
  16389. var indices = [];
  16390. var positions = [];
  16391. for (var index = 0; index < points.length; index++) {
  16392. positions.push(points[index].x, points[index].y, points[index].z);
  16393. if (index > 0) {
  16394. indices.push(index - 1);
  16395. indices.push(index);
  16396. }
  16397. }
  16398. var vertexData = new BABYLON.VertexData();
  16399. vertexData.indices = indices;
  16400. vertexData.positions = positions;
  16401. return vertexData;
  16402. };
  16403. VertexData.CreateGround = function (width, height, subdivisions) {
  16404. var indices = [];
  16405. var positions = [];
  16406. var normals = [];
  16407. var uvs = [];
  16408. var row, col;
  16409. width = width || 1;
  16410. height = height || 1;
  16411. subdivisions = subdivisions || 1;
  16412. for (row = 0; row <= subdivisions; row++) {
  16413. for (col = 0; col <= subdivisions; col++) {
  16414. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  16415. var normal = new BABYLON.Vector3(0, 1.0, 0);
  16416. positions.push(position.x, position.y, position.z);
  16417. normals.push(normal.x, normal.y, normal.z);
  16418. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  16419. }
  16420. }
  16421. for (row = 0; row < subdivisions; row++) {
  16422. for (col = 0; col < subdivisions; col++) {
  16423. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16424. indices.push(col + 1 + row * (subdivisions + 1));
  16425. indices.push(col + row * (subdivisions + 1));
  16426. indices.push(col + (row + 1) * (subdivisions + 1));
  16427. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16428. indices.push(col + row * (subdivisions + 1));
  16429. }
  16430. }
  16431. var vertexData = new BABYLON.VertexData();
  16432. vertexData.indices = indices;
  16433. vertexData.positions = positions;
  16434. vertexData.normals = normals;
  16435. vertexData.uvs = uvs;
  16436. return vertexData;
  16437. };
  16438. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  16439. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  16440. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  16441. var indices = [];
  16442. var positions = [];
  16443. var normals = [];
  16444. var uvs = [];
  16445. var row, col, tileRow, tileCol;
  16446. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  16447. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  16448. precision.w = (precision.w < 1) ? 1 : precision.w;
  16449. precision.h = (precision.h < 1) ? 1 : precision.h;
  16450. var tileSize = {
  16451. 'w': (xmax - xmin) / subdivisions.w,
  16452. 'h': (zmax - zmin) / subdivisions.h
  16453. };
  16454. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  16455. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  16456. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  16457. }
  16458. }
  16459. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  16460. var base = positions.length / 3;
  16461. var rowLength = precision.w + 1;
  16462. for (row = 0; row < precision.h; row++) {
  16463. for (col = 0; col < precision.w; col++) {
  16464. var square = [
  16465. base + col + row * rowLength,
  16466. base + (col + 1) + row * rowLength,
  16467. base + (col + 1) + (row + 1) * rowLength,
  16468. base + col + (row + 1) * rowLength
  16469. ];
  16470. indices.push(square[1]);
  16471. indices.push(square[2]);
  16472. indices.push(square[3]);
  16473. indices.push(square[0]);
  16474. indices.push(square[1]);
  16475. indices.push(square[3]);
  16476. }
  16477. }
  16478. var position = BABYLON.Vector3.Zero();
  16479. var normal = new BABYLON.Vector3(0, 1.0, 0);
  16480. for (row = 0; row <= precision.h; row++) {
  16481. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  16482. for (col = 0; col <= precision.w; col++) {
  16483. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  16484. position.y = 0;
  16485. positions.push(position.x, position.y, position.z);
  16486. normals.push(normal.x, normal.y, normal.z);
  16487. uvs.push(col / precision.w, row / precision.h);
  16488. }
  16489. }
  16490. }
  16491. var vertexData = new BABYLON.VertexData();
  16492. vertexData.indices = indices;
  16493. vertexData.positions = positions;
  16494. vertexData.normals = normals;
  16495. vertexData.uvs = uvs;
  16496. return vertexData;
  16497. };
  16498. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  16499. var indices = [];
  16500. var positions = [];
  16501. var normals = [];
  16502. var uvs = [];
  16503. var row, col;
  16504. for (row = 0; row <= subdivisions; row++) {
  16505. for (col = 0; col <= subdivisions; col++) {
  16506. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  16507. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  16508. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  16509. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  16510. var r = buffer[pos] / 255.0;
  16511. var g = buffer[pos + 1] / 255.0;
  16512. var b = buffer[pos + 2] / 255.0;
  16513. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  16514. position.y = minHeight + (maxHeight - minHeight) * gradient;
  16515. positions.push(position.x, position.y, position.z);
  16516. normals.push(0, 0, 0);
  16517. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  16518. }
  16519. }
  16520. for (row = 0; row < subdivisions; row++) {
  16521. for (col = 0; col < subdivisions; col++) {
  16522. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16523. indices.push(col + 1 + row * (subdivisions + 1));
  16524. indices.push(col + row * (subdivisions + 1));
  16525. indices.push(col + (row + 1) * (subdivisions + 1));
  16526. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16527. indices.push(col + row * (subdivisions + 1));
  16528. }
  16529. }
  16530. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16531. var vertexData = new BABYLON.VertexData();
  16532. vertexData.indices = indices;
  16533. vertexData.positions = positions;
  16534. vertexData.normals = normals;
  16535. vertexData.uvs = uvs;
  16536. return vertexData;
  16537. };
  16538. VertexData.CreatePlane = function (size) {
  16539. var indices = [];
  16540. var positions = [];
  16541. var normals = [];
  16542. var uvs = [];
  16543. size = size || 1;
  16544. var halfSize = size / 2.0;
  16545. positions.push(-halfSize, -halfSize, 0);
  16546. normals.push(0, 0, -1.0);
  16547. uvs.push(0.0, 0.0);
  16548. positions.push(halfSize, -halfSize, 0);
  16549. normals.push(0, 0, -1.0);
  16550. uvs.push(1.0, 0.0);
  16551. positions.push(halfSize, halfSize, 0);
  16552. normals.push(0, 0, -1.0);
  16553. uvs.push(1.0, 1.0);
  16554. positions.push(-halfSize, halfSize, 0);
  16555. normals.push(0, 0, -1.0);
  16556. uvs.push(0.0, 1.0);
  16557. indices.push(0);
  16558. indices.push(1);
  16559. indices.push(2);
  16560. indices.push(0);
  16561. indices.push(2);
  16562. indices.push(3);
  16563. var vertexData = new BABYLON.VertexData();
  16564. vertexData.indices = indices;
  16565. vertexData.positions = positions;
  16566. vertexData.normals = normals;
  16567. vertexData.uvs = uvs;
  16568. return vertexData;
  16569. };
  16570. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  16571. var indices = [];
  16572. var positions = [];
  16573. var normals = [];
  16574. var uvs = [];
  16575. radius = radius || 2;
  16576. tube = tube || 0.5;
  16577. radialSegments = radialSegments || 32;
  16578. tubularSegments = tubularSegments || 32;
  16579. p = p || 2;
  16580. q = q || 3;
  16581. var getPos = function (angle) {
  16582. var cu = Math.cos(angle);
  16583. var su = Math.sin(angle);
  16584. var quOverP = q / p * angle;
  16585. var cs = Math.cos(quOverP);
  16586. var tx = radius * (2 + cs) * 0.5 * cu;
  16587. var ty = radius * (2 + cs) * su * 0.5;
  16588. var tz = radius * Math.sin(quOverP) * 0.5;
  16589. return new BABYLON.Vector3(tx, ty, tz);
  16590. };
  16591. for (var i = 0; i <= radialSegments; i++) {
  16592. var modI = i % radialSegments;
  16593. var u = modI / radialSegments * 2 * p * Math.PI;
  16594. var p1 = getPos(u);
  16595. var p2 = getPos(u + 0.01);
  16596. var tang = p2.subtract(p1);
  16597. var n = p2.add(p1);
  16598. var bitan = BABYLON.Vector3.Cross(tang, n);
  16599. n = BABYLON.Vector3.Cross(bitan, tang);
  16600. bitan.normalize();
  16601. n.normalize();
  16602. for (var j = 0; j < tubularSegments; j++) {
  16603. var modJ = j % tubularSegments;
  16604. var v = modJ / tubularSegments * 2 * Math.PI;
  16605. var cx = -tube * Math.cos(v);
  16606. var cy = tube * Math.sin(v);
  16607. positions.push(p1.x + cx * n.x + cy * bitan.x);
  16608. positions.push(p1.y + cx * n.y + cy * bitan.y);
  16609. positions.push(p1.z + cx * n.z + cy * bitan.z);
  16610. uvs.push(i / radialSegments);
  16611. uvs.push(j / tubularSegments);
  16612. }
  16613. }
  16614. for (i = 0; i < radialSegments; i++) {
  16615. for (j = 0; j < tubularSegments; j++) {
  16616. var jNext = (j + 1) % tubularSegments;
  16617. var a = i * tubularSegments + j;
  16618. var b = (i + 1) * tubularSegments + j;
  16619. var c = (i + 1) * tubularSegments + jNext;
  16620. var d = i * tubularSegments + jNext;
  16621. indices.push(d);
  16622. indices.push(b);
  16623. indices.push(a);
  16624. indices.push(d);
  16625. indices.push(c);
  16626. indices.push(b);
  16627. }
  16628. }
  16629. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16630. var vertexData = new BABYLON.VertexData();
  16631. vertexData.indices = indices;
  16632. vertexData.positions = positions;
  16633. vertexData.normals = normals;
  16634. vertexData.uvs = uvs;
  16635. return vertexData;
  16636. };
  16637. VertexData.ComputeNormals = function (positions, indices, normals) {
  16638. var positionVectors = [];
  16639. var facesOfVertices = [];
  16640. var index;
  16641. for (index = 0; index < positions.length; index += 3) {
  16642. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  16643. positionVectors.push(vector3);
  16644. facesOfVertices.push([]);
  16645. }
  16646. var facesNormals = [];
  16647. for (index = 0; index < indices.length / 3; index++) {
  16648. var i1 = indices[index * 3];
  16649. var i2 = indices[index * 3 + 1];
  16650. var i3 = indices[index * 3 + 2];
  16651. var p1 = positionVectors[i1];
  16652. var p2 = positionVectors[i2];
  16653. var p3 = positionVectors[i3];
  16654. var p1p2 = p1.subtract(p2);
  16655. var p3p2 = p3.subtract(p2);
  16656. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  16657. facesOfVertices[i1].push(index);
  16658. facesOfVertices[i2].push(index);
  16659. facesOfVertices[i3].push(index);
  16660. }
  16661. for (index = 0; index < positionVectors.length; index++) {
  16662. var faces = facesOfVertices[index];
  16663. var normal = BABYLON.Vector3.Zero();
  16664. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  16665. normal.addInPlace(facesNormals[faces[faceIndex]]);
  16666. }
  16667. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  16668. normals[index * 3] = normal.x;
  16669. normals[index * 3 + 1] = normal.y;
  16670. normals[index * 3 + 2] = normal.z;
  16671. }
  16672. };
  16673. return VertexData;
  16674. })();
  16675. BABYLON.VertexData = VertexData;
  16676. })(BABYLON || (BABYLON = {}));
  16677. var __extends = this.__extends || function (d, b) {
  16678. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16679. function __() { this.constructor = d; }
  16680. __.prototype = b.prototype;
  16681. d.prototype = new __();
  16682. };
  16683. var BABYLON;
  16684. (function (BABYLON) {
  16685. var buildCamera = function (that, name) {
  16686. that._leftCamera.isIntermediate = true;
  16687. that.subCameras.push(that._leftCamera);
  16688. that.subCameras.push(that._rightCamera);
  16689. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  16690. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  16691. that._anaglyphPostProcess.onApply = function (effect) {
  16692. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  16693. };
  16694. that._update();
  16695. };
  16696. var AnaglyphArcRotateCamera = (function (_super) {
  16697. __extends(AnaglyphArcRotateCamera, _super);
  16698. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  16699. _super.call(this, name, alpha, beta, radius, target, scene);
  16700. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  16701. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  16702. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  16703. buildCamera(this, name);
  16704. }
  16705. AnaglyphArcRotateCamera.prototype._update = function () {
  16706. this._updateCamera(this._leftCamera);
  16707. this._updateCamera(this._rightCamera);
  16708. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  16709. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  16710. _super.prototype._update.call(this);
  16711. };
  16712. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  16713. camera.beta = this.beta;
  16714. camera.radius = this.radius;
  16715. camera.minZ = this.minZ;
  16716. camera.maxZ = this.maxZ;
  16717. camera.fov = this.fov;
  16718. camera.target = this.target;
  16719. };
  16720. return AnaglyphArcRotateCamera;
  16721. })(BABYLON.ArcRotateCamera);
  16722. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  16723. var AnaglyphFreeCamera = (function (_super) {
  16724. __extends(AnaglyphFreeCamera, _super);
  16725. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  16726. _super.call(this, name, position, scene);
  16727. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  16728. this._transformMatrix = new BABYLON.Matrix();
  16729. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  16730. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  16731. buildCamera(this, name);
  16732. }
  16733. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  16734. var target = this.getTarget();
  16735. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  16736. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  16737. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  16738. };
  16739. AnaglyphFreeCamera.prototype._update = function () {
  16740. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  16741. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  16742. this._updateCamera(this._leftCamera);
  16743. this._updateCamera(this._rightCamera);
  16744. _super.prototype._update.call(this);
  16745. };
  16746. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  16747. camera.minZ = this.minZ;
  16748. camera.maxZ = this.maxZ;
  16749. camera.fov = this.fov;
  16750. camera.viewport = this.viewport;
  16751. camera.setTarget(this.getTarget());
  16752. };
  16753. return AnaglyphFreeCamera;
  16754. })(BABYLON.FreeCamera);
  16755. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  16756. })(BABYLON || (BABYLON = {}));
  16757. var __extends = this.__extends || function (d, b) {
  16758. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16759. function __() { this.constructor = d; }
  16760. __.prototype = b.prototype;
  16761. d.prototype = new __();
  16762. };
  16763. var BABYLON;
  16764. (function (BABYLON) {
  16765. var AnaglyphPostProcess = (function (_super) {
  16766. __extends(AnaglyphPostProcess, _super);
  16767. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16768. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  16769. }
  16770. return AnaglyphPostProcess;
  16771. })(BABYLON.PostProcess);
  16772. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  16773. })(BABYLON || (BABYLON = {}));
  16774. var BABYLON;
  16775. (function (BABYLON) {
  16776. var Tags = (function () {
  16777. function Tags() {
  16778. }
  16779. Tags.EnableFor = function (obj) {
  16780. obj._tags = obj._tags || {};
  16781. obj.hasTags = function () {
  16782. return Tags.HasTags(obj);
  16783. };
  16784. obj.addTags = function (tagsString) {
  16785. return Tags.AddTagsTo(obj, tagsString);
  16786. };
  16787. obj.removeTags = function (tagsString) {
  16788. return Tags.RemoveTagsFrom(obj, tagsString);
  16789. };
  16790. obj.matchesTagsQuery = function (tagsQuery) {
  16791. return Tags.MatchesQuery(obj, tagsQuery);
  16792. };
  16793. };
  16794. Tags.DisableFor = function (obj) {
  16795. delete obj._tags;
  16796. delete obj.hasTags;
  16797. delete obj.addTags;
  16798. delete obj.removeTags;
  16799. delete obj.matchesTagsQuery;
  16800. };
  16801. Tags.HasTags = function (obj) {
  16802. if (!obj._tags) {
  16803. return false;
  16804. }
  16805. return !BABYLON.Tools.IsEmpty(obj._tags);
  16806. };
  16807. Tags.GetTags = function (obj) {
  16808. if (!obj._tags) {
  16809. return null;
  16810. }
  16811. return obj._tags;
  16812. };
  16813. Tags.AddTagsTo = function (obj, tagsString) {
  16814. if (!tagsString) {
  16815. return;
  16816. }
  16817. var tags = tagsString.split(" ");
  16818. for (var t in tags) {
  16819. Tags._AddTagTo(obj, tags[t]);
  16820. }
  16821. };
  16822. Tags._AddTagTo = function (obj, tag) {
  16823. tag = tag.trim();
  16824. if (tag === "" || tag === "true" || tag === "false") {
  16825. return;
  16826. }
  16827. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  16828. return;
  16829. }
  16830. Tags.EnableFor(obj);
  16831. obj._tags[tag] = true;
  16832. };
  16833. Tags.RemoveTagsFrom = function (obj, tagsString) {
  16834. if (!Tags.HasTags(obj)) {
  16835. return;
  16836. }
  16837. var tags = tagsString.split(" ");
  16838. for (var t in tags) {
  16839. Tags._RemoveTagFrom(obj, tags[t]);
  16840. }
  16841. };
  16842. Tags._RemoveTagFrom = function (obj, tag) {
  16843. delete obj._tags[tag];
  16844. };
  16845. Tags.MatchesQuery = function (obj, tagsQuery) {
  16846. if (tagsQuery === undefined) {
  16847. return true;
  16848. }
  16849. if (tagsQuery === "") {
  16850. return Tags.HasTags(obj);
  16851. }
  16852. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  16853. return Tags.HasTags(obj) && obj._tags[r];
  16854. });
  16855. };
  16856. return Tags;
  16857. })();
  16858. BABYLON.Tags = Tags;
  16859. })(BABYLON || (BABYLON = {}));
  16860. var BABYLON;
  16861. (function (BABYLON) {
  16862. (function (Internals) {
  16863. var AndOrNotEvaluator = (function () {
  16864. function AndOrNotEvaluator() {
  16865. }
  16866. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  16867. if (!query.match(/\([^\(\)]*\)/g)) {
  16868. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  16869. } else {
  16870. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  16871. r = r.slice(1, r.length - 1);
  16872. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  16873. });
  16874. }
  16875. if (query === "true") {
  16876. return true;
  16877. }
  16878. if (query === "false") {
  16879. return false;
  16880. }
  16881. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  16882. };
  16883. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  16884. evaluateCallback = evaluateCallback || (function (r) {
  16885. return r === "true" ? true : false;
  16886. });
  16887. var result;
  16888. var or = parenthesisContent.split("||");
  16889. for (var i in or) {
  16890. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  16891. var and = ori.split("&&");
  16892. if (and.length > 1) {
  16893. for (var j = 0; j < and.length; ++j) {
  16894. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  16895. if (andj !== "true" && andj !== "false") {
  16896. if (andj[0] === "!") {
  16897. result = !evaluateCallback(andj.substring(1));
  16898. } else {
  16899. result = evaluateCallback(andj);
  16900. }
  16901. } else {
  16902. result = andj === "true" ? true : false;
  16903. }
  16904. if (!result) {
  16905. ori = "false";
  16906. break;
  16907. }
  16908. }
  16909. }
  16910. if (result || ori === "true") {
  16911. result = true;
  16912. break;
  16913. }
  16914. if (ori !== "true" && ori !== "false") {
  16915. if (ori[0] === "!") {
  16916. result = !evaluateCallback(ori.substring(1));
  16917. } else {
  16918. result = evaluateCallback(ori);
  16919. }
  16920. } else {
  16921. result = ori === "true" ? true : false;
  16922. }
  16923. }
  16924. return result ? "true" : "false";
  16925. };
  16926. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  16927. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  16928. r = r.replace(/[\s]/g, function () {
  16929. return "";
  16930. });
  16931. return r.length % 2 ? "!" : "";
  16932. });
  16933. booleanString = booleanString.trim();
  16934. if (booleanString === "!true") {
  16935. booleanString = "false";
  16936. } else if (booleanString === "!false") {
  16937. booleanString = "true";
  16938. }
  16939. return booleanString;
  16940. };
  16941. return AndOrNotEvaluator;
  16942. })();
  16943. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  16944. })(BABYLON.Internals || (BABYLON.Internals = {}));
  16945. var Internals = BABYLON.Internals;
  16946. })(BABYLON || (BABYLON = {}));
  16947. var BABYLON;
  16948. (function (BABYLON) {
  16949. var PostProcessRenderPass = (function () {
  16950. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  16951. this._enabled = true;
  16952. this._refCount = 0;
  16953. this._name = name;
  16954. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  16955. this.setRenderList(renderList);
  16956. this._renderTexture.onBeforeRender = beforeRender;
  16957. this._renderTexture.onAfterRender = afterRender;
  16958. this._scene = scene;
  16959. }
  16960. PostProcessRenderPass.prototype._incRefCount = function () {
  16961. if (this._refCount === 0) {
  16962. this._scene.customRenderTargets.push(this._renderTexture);
  16963. }
  16964. return ++this._refCount;
  16965. };
  16966. PostProcessRenderPass.prototype._decRefCount = function () {
  16967. this._refCount--;
  16968. if (this._refCount <= 0) {
  16969. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  16970. }
  16971. return this._refCount;
  16972. };
  16973. PostProcessRenderPass.prototype._update = function () {
  16974. this.setRenderList(this._renderList);
  16975. };
  16976. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  16977. this._renderTexture.renderList = renderList;
  16978. };
  16979. PostProcessRenderPass.prototype.getRenderTexture = function () {
  16980. return this._renderTexture;
  16981. };
  16982. return PostProcessRenderPass;
  16983. })();
  16984. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  16985. })(BABYLON || (BABYLON = {}));
  16986. var BABYLON;
  16987. (function (BABYLON) {
  16988. var PostProcessRenderEffect = (function () {
  16989. function PostProcessRenderEffect(engine, name, postProcessType, ratio, samplingMode, singleInstance) {
  16990. this._engine = engine;
  16991. this._name = name;
  16992. this._postProcessType = postProcessType;
  16993. this._ratio = ratio || 1.0;
  16994. this._samplingMode = samplingMode || null;
  16995. this._singleInstance = singleInstance || true;
  16996. this._cameras = [];
  16997. this._postProcesses = [];
  16998. this._indicesForCamera = [];
  16999. this._renderPasses = [];
  17000. this._renderEffectAsPasses = [];
  17001. this.parameters = function (effect) {
  17002. };
  17003. }
  17004. PostProcessRenderEffect._GetInstance = function (engine, postProcessType, ratio, samplingMode) {
  17005. var postProcess;
  17006. var instance;
  17007. var args = [];
  17008. var parameters = PostProcessRenderEffect._GetParametersNames(postProcessType);
  17009. for (var i = 0; i < parameters.length; i++) {
  17010. switch (parameters[i]) {
  17011. case "name":
  17012. args[i] = postProcessType.toString();
  17013. break;
  17014. case "ratio":
  17015. args[i] = ratio;
  17016. break;
  17017. case "camera":
  17018. args[i] = null;
  17019. break;
  17020. case "samplingMode":
  17021. args[i] = samplingMode;
  17022. break;
  17023. case "engine":
  17024. args[i] = engine;
  17025. break;
  17026. case "reusable":
  17027. args[i] = true;
  17028. break;
  17029. default:
  17030. args[i] = null;
  17031. break;
  17032. }
  17033. }
  17034. postProcess = function () {
  17035. };
  17036. postProcess.prototype = postProcessType.prototype;
  17037. instance = new postProcess();
  17038. postProcessType.apply(instance, args);
  17039. return instance;
  17040. };
  17041. PostProcessRenderEffect._GetParametersNames = function (func) {
  17042. var commentsRegex = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  17043. var functWithoutComments = func.toString().replace(commentsRegex, '');
  17044. var parameters = functWithoutComments.slice(functWithoutComments.indexOf('(') + 1, functWithoutComments.indexOf(')')).match(/([^\s,]+)/g);
  17045. if (parameters === null)
  17046. parameters = [];
  17047. return parameters;
  17048. };
  17049. PostProcessRenderEffect.prototype._update = function () {
  17050. for (var renderPassName in this._renderPasses) {
  17051. this._renderPasses[renderPassName]._update();
  17052. }
  17053. };
  17054. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  17055. this._renderPasses[renderPass._name] = renderPass;
  17056. this._linkParameters();
  17057. };
  17058. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  17059. delete this._renderPasses[renderPass._name];
  17060. this._linkParameters();
  17061. };
  17062. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  17063. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  17064. this._linkParameters();
  17065. };
  17066. PostProcessRenderEffect.prototype.getPass = function (passName) {
  17067. for (var renderPassName in this._renderPasses) {
  17068. if (renderPassName === passName) {
  17069. return this._renderPasses[passName];
  17070. }
  17071. }
  17072. };
  17073. PostProcessRenderEffect.prototype.emptyPasses = function () {
  17074. this._renderPasses.length = 0;
  17075. this._linkParameters();
  17076. };
  17077. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  17078. var cameraKey;
  17079. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17080. for (var i = 0; i < _cam.length; i++) {
  17081. var camera = _cam[i];
  17082. var cameraName = camera.name;
  17083. if (this._singleInstance) {
  17084. cameraKey = 0;
  17085. } else {
  17086. cameraKey = cameraName;
  17087. }
  17088. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || PostProcessRenderEffect._GetInstance(this._engine, this._postProcessType, this._ratio, this._samplingMode);
  17089. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  17090. if (this._indicesForCamera[cameraName] === null) {
  17091. this._indicesForCamera[cameraName] = [];
  17092. }
  17093. this._indicesForCamera[cameraName].push(index);
  17094. if (this._cameras.indexOf(camera) === -1) {
  17095. this._cameras[cameraName] = camera;
  17096. }
  17097. for (var passName in this._renderPasses) {
  17098. this._renderPasses[passName]._incRefCount();
  17099. }
  17100. }
  17101. this._linkParameters();
  17102. };
  17103. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  17104. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17105. for (var i = 0; i < _cam.length; i++) {
  17106. var camera = _cam[i];
  17107. var cameraName = camera.name;
  17108. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  17109. var index = this._cameras.indexOf(cameraName);
  17110. this._indicesForCamera.splice(index, 1);
  17111. this._cameras.splice(index, 1);
  17112. for (var passName in this._renderPasses) {
  17113. this._renderPasses[passName]._decRefCount();
  17114. }
  17115. }
  17116. };
  17117. PostProcessRenderEffect.prototype._enable = function (cameras) {
  17118. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17119. for (var i = 0; i < _cam.length; i++) {
  17120. var camera = _cam[i];
  17121. var cameraName = camera.name;
  17122. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  17123. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  17124. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  17125. }
  17126. }
  17127. for (var passName in this._renderPasses) {
  17128. this._renderPasses[passName]._incRefCount();
  17129. }
  17130. }
  17131. };
  17132. PostProcessRenderEffect.prototype._disable = function (cameras) {
  17133. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17134. for (var i = 0; i < _cam.length; i++) {
  17135. var camera = _cam[i];
  17136. var cameraName = camera.Name;
  17137. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  17138. for (var passName in this._renderPasses) {
  17139. this._renderPasses[passName]._decRefCount();
  17140. }
  17141. }
  17142. };
  17143. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  17144. if (this._singleInstance) {
  17145. return this._postProcesses[0];
  17146. } else {
  17147. return this._postProcesses[camera.name];
  17148. }
  17149. };
  17150. PostProcessRenderEffect.prototype._linkParameters = function () {
  17151. var _this = this;
  17152. for (var index in this._postProcesses) {
  17153. this._postProcesses[index].onApply = function (effect) {
  17154. _this.parameters(effect);
  17155. _this._linkTextures(effect);
  17156. };
  17157. }
  17158. };
  17159. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  17160. for (var renderPassName in this._renderPasses) {
  17161. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  17162. }
  17163. for (var renderEffectName in this._renderEffectAsPasses) {
  17164. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  17165. }
  17166. };
  17167. return PostProcessRenderEffect;
  17168. })();
  17169. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  17170. })(BABYLON || (BABYLON = {}));
  17171. var BABYLON;
  17172. (function (BABYLON) {
  17173. var PostProcessRenderPipeline = (function () {
  17174. function PostProcessRenderPipeline(engine, name) {
  17175. this._engine = engine;
  17176. this._name = name;
  17177. this._renderEffects = [];
  17178. this._renderEffectsForIsolatedPass = [];
  17179. this._cameras = [];
  17180. }
  17181. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  17182. this._renderEffects[renderEffect._name] = renderEffect;
  17183. };
  17184. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  17185. var renderEffects = this._renderEffects[renderEffectName];
  17186. if (!renderEffects) {
  17187. return;
  17188. }
  17189. renderEffects.enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  17190. };
  17191. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  17192. var renderEffects = this._renderEffects[renderEffectName];
  17193. if (!renderEffects) {
  17194. return;
  17195. }
  17196. renderEffects.disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  17197. };
  17198. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  17199. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17200. var indicesToDelete = [];
  17201. for (var i = 0; i < _cam.length; i++) {
  17202. var camera = _cam[i];
  17203. var cameraName = camera.name;
  17204. if (this._cameras.indexOf(camera) === -1) {
  17205. this._cameras[cameraName] = camera;
  17206. } else if (unique) {
  17207. indicesToDelete.push(i);
  17208. }
  17209. }
  17210. for (var i = 0; i < indicesToDelete.length; i++) {
  17211. cameras.splice(indicesToDelete[i], 1);
  17212. }
  17213. for (var renderEffectName in this._renderEffects) {
  17214. this._renderEffects[renderEffectName]._attachCameras(_cam);
  17215. }
  17216. };
  17217. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  17218. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17219. for (var renderEffectName in this._renderEffects) {
  17220. this._renderEffects[renderEffectName]._detachCameras(_cam);
  17221. }
  17222. for (var i = 0; i < _cam.length; i++) {
  17223. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  17224. }
  17225. };
  17226. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  17227. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17228. var pass = null;
  17229. for (var renderEffectName in this._renderEffects) {
  17230. pass = this._renderEffects[renderEffectName].getPass(passName);
  17231. if (pass != null) {
  17232. break;
  17233. }
  17234. }
  17235. if (pass === null) {
  17236. return;
  17237. }
  17238. for (var renderEffectName in this._renderEffects) {
  17239. this._renderEffects[renderEffectName]._disable(_cam);
  17240. }
  17241. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  17242. for (var i = 0; i < _cam.length; i++) {
  17243. var camera = _cam[i];
  17244. var cameraName = camera.name;
  17245. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, "BABYLON.DisplayPassPostProcess", 1.0, null, null);
  17246. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  17247. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  17248. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  17249. }
  17250. };
  17251. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  17252. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17253. for (var i = 0; i < _cam.length; i++) {
  17254. var camera = _cam[i];
  17255. var cameraName = camera.name;
  17256. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, "BABYLON.DisplayPassPostProcess", 1.0, null, null);
  17257. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  17258. }
  17259. for (var renderEffectName in this._renderEffects) {
  17260. this._renderEffects[renderEffectName]._enable(_cam);
  17261. }
  17262. };
  17263. PostProcessRenderPipeline.prototype._update = function () {
  17264. for (var renderEffectName in this._renderEffects) {
  17265. this._renderEffects[renderEffectName]._update();
  17266. }
  17267. for (var i = 0; i < this._cameras.length; i++) {
  17268. var cameraName = this._cameras[i].name;
  17269. if (this._renderEffectsForIsolatedPass[cameraName]) {
  17270. this._renderEffectsForIsolatedPass[cameraName]._update();
  17271. }
  17272. }
  17273. };
  17274. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  17275. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  17276. return PostProcessRenderPipeline;
  17277. })();
  17278. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  17279. })(BABYLON || (BABYLON = {}));
  17280. var BABYLON;
  17281. (function (BABYLON) {
  17282. var PostProcessRenderPipelineManager = (function () {
  17283. function PostProcessRenderPipelineManager() {
  17284. this._renderPipelines = [];
  17285. }
  17286. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  17287. this._renderPipelines[renderPipeline._name] = renderPipeline;
  17288. };
  17289. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  17290. var renderPipeline = this._renderPipelines[renderPipelineName];
  17291. if (!renderPipeline) {
  17292. return;
  17293. }
  17294. renderPipeline.attachCameras(cameras, unique);
  17295. };
  17296. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  17297. var renderPipeline = this._renderPipelines[renderPipelineName];
  17298. if (!renderPipeline) {
  17299. return;
  17300. }
  17301. renderPipeline.detachCameras(cameras);
  17302. };
  17303. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  17304. var renderPipeline = this._renderPipelines[renderPipelineName];
  17305. if (!renderPipeline) {
  17306. return;
  17307. }
  17308. renderPipeline.enableEffect(renderEffectName, cameras);
  17309. };
  17310. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  17311. var renderPipeline = this._renderPipelines[renderPipelineName];
  17312. if (!renderPipeline) {
  17313. return;
  17314. }
  17315. renderPipeline.disableEffect(renderEffectName, cameras);
  17316. };
  17317. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  17318. var renderPipeline = this._renderPipelines[renderPipelineName];
  17319. if (!renderPipeline) {
  17320. return;
  17321. }
  17322. renderPipeline.enableDisplayOnlyPass(passName, cameras);
  17323. };
  17324. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  17325. var renderPipeline = this._renderPipelines[renderPipelineName];
  17326. if (!renderPipeline) {
  17327. return;
  17328. }
  17329. renderPipeline.disableDisplayOnlyPass(cameras);
  17330. };
  17331. PostProcessRenderPipelineManager.prototype.update = function () {
  17332. for (var renderPipelineName in this._renderPipelines) {
  17333. this._renderPipelines[renderPipelineName]._update();
  17334. }
  17335. };
  17336. return PostProcessRenderPipelineManager;
  17337. })();
  17338. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  17339. })(BABYLON || (BABYLON = {}));
  17340. var __extends = this.__extends || function (d, b) {
  17341. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17342. function __() { this.constructor = d; }
  17343. __.prototype = b.prototype;
  17344. d.prototype = new __();
  17345. };
  17346. var BABYLON;
  17347. (function (BABYLON) {
  17348. var DisplayPassPostProcess = (function (_super) {
  17349. __extends(DisplayPassPostProcess, _super);
  17350. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17351. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  17352. }
  17353. return DisplayPassPostProcess;
  17354. })(BABYLON.PostProcess);
  17355. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  17356. })(BABYLON || (BABYLON = {}));
  17357. var BABYLON;
  17358. (function (BABYLON) {
  17359. var BoundingBoxRenderer = (function () {
  17360. function BoundingBoxRenderer(scene) {
  17361. this.frontColor = new BABYLON.Color3(1, 1, 1);
  17362. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  17363. this.showBackLines = true;
  17364. this.renderList = new BABYLON.SmartArray(32);
  17365. this._scene = scene;
  17366. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  17367. attributes: ["position"],
  17368. uniforms: ["worldViewProjection", "color"]
  17369. });
  17370. var engine = this._scene.getEngine();
  17371. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  17372. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  17373. this._ib = 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]);
  17374. }
  17375. BoundingBoxRenderer.prototype.reset = function () {
  17376. this.renderList.reset();
  17377. };
  17378. BoundingBoxRenderer.prototype.render = function () {
  17379. if (this.renderList.length == 0 || !this._colorShader.isReady()) {
  17380. return;
  17381. }
  17382. var engine = this._scene.getEngine();
  17383. engine.setDepthWrite(false);
  17384. this._colorShader._preBind();
  17385. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  17386. var boundingBox = this.renderList.data[boundingBoxIndex];
  17387. var min = boundingBox.minimum;
  17388. var max = boundingBox.maximum;
  17389. var diff = max.subtract(min);
  17390. var median = min.add(diff.scale(0.5));
  17391. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  17392. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  17393. if (this.showBackLines) {
  17394. engine.setDepthFunctionToGreaterOrEqual();
  17395. this._colorShader.setColor4("color", this.backColor.toColor4());
  17396. this._colorShader.bind(worldMatrix);
  17397. engine.draw(false, 0, 24);
  17398. }
  17399. engine.setDepthFunctionToLess();
  17400. this._colorShader.setColor4("color", this.frontColor.toColor4());
  17401. this._colorShader.bind(worldMatrix);
  17402. engine.draw(false, 0, 24);
  17403. }
  17404. this._colorShader.unbind();
  17405. engine.setDepthFunctionToLessOrEqual();
  17406. engine.setDepthWrite(true);
  17407. };
  17408. BoundingBoxRenderer.prototype.dispose = function () {
  17409. this._colorShader.dispose();
  17410. this._vb.dispose();
  17411. this._scene.getEngine()._releaseBuffer(this._ib);
  17412. };
  17413. return BoundingBoxRenderer;
  17414. })();
  17415. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  17416. })(BABYLON || (BABYLON = {}));
  17417. /**
  17418. * Based on jsTGALoader - Javascript loader for TGA file
  17419. * By Vincent Thibault
  17420. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  17421. */
  17422. var BABYLON;
  17423. (function (BABYLON) {
  17424. (function (Internals) {
  17425. var TGATools = (function () {
  17426. function TGATools() {
  17427. }
  17428. TGATools.GetTGAHeader = function (data) {
  17429. var offset = 0;
  17430. var header = {
  17431. id_length: data[offset++],
  17432. colormap_type: data[offset++],
  17433. image_type: data[offset++],
  17434. colormap_index: data[offset++] | data[offset++] << 8,
  17435. colormap_length: data[offset++] | data[offset++] << 8,
  17436. colormap_size: data[offset++],
  17437. origin: [
  17438. data[offset++] | data[offset++] << 8,
  17439. data[offset++] | data[offset++] << 8
  17440. ],
  17441. width: data[offset++] | data[offset++] << 8,
  17442. height: data[offset++] | data[offset++] << 8,
  17443. pixel_size: data[offset++],
  17444. flags: data[offset++]
  17445. };
  17446. return header;
  17447. };
  17448. TGATools.UploadContent = function (gl, data) {
  17449. if (data.length < 19) {
  17450. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  17451. return;
  17452. }
  17453. var offset = 18;
  17454. var header = TGATools.GetTGAHeader(data);
  17455. if (header.id_length + offset > data.length) {
  17456. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  17457. return;
  17458. }
  17459. offset += header.id_length;
  17460. var use_rle = false;
  17461. var use_pal = false;
  17462. var use_rgb = false;
  17463. var use_grey = false;
  17464. switch (header.image_type) {
  17465. case TGATools._TYPE_RLE_INDEXED:
  17466. use_rle = true;
  17467. case TGATools._TYPE_INDEXED:
  17468. use_pal = true;
  17469. break;
  17470. case TGATools._TYPE_RLE_RGB:
  17471. use_rle = true;
  17472. case TGATools._TYPE_RGB:
  17473. use_rgb = true;
  17474. break;
  17475. case TGATools._TYPE_RLE_GREY:
  17476. use_rle = true;
  17477. case TGATools._TYPE_GREY:
  17478. use_grey = true;
  17479. break;
  17480. }
  17481. var pixel_data;
  17482. var numAlphaBits = header.flags & 0xf;
  17483. var pixel_size = header.pixel_size >> 3;
  17484. var pixel_total = header.width * header.height * pixel_size;
  17485. var palettes;
  17486. if (use_pal) {
  17487. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  17488. }
  17489. if (use_rle) {
  17490. pixel_data = new Uint8Array(pixel_total);
  17491. var c, count, i;
  17492. var localOffset = 0;
  17493. var pixels = new Uint8Array(pixel_size);
  17494. while (offset < pixel_total && localOffset < pixel_total) {
  17495. c = data[offset++];
  17496. count = (c & 0x7f) + 1;
  17497. if (c & 0x80) {
  17498. for (i = 0; i < pixel_size; ++i) {
  17499. pixels[i] = data[offset++];
  17500. }
  17501. for (i = 0; i < count; ++i) {
  17502. pixel_data.set(pixels, localOffset + i * pixel_size);
  17503. }
  17504. localOffset += pixel_size * count;
  17505. } else {
  17506. count *= pixel_size;
  17507. for (i = 0; i < count; ++i) {
  17508. pixel_data[localOffset + i] = data[offset++];
  17509. }
  17510. localOffset += count;
  17511. }
  17512. }
  17513. } else {
  17514. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  17515. }
  17516. var x_start, y_start, x_step, y_step, y_end, x_end;
  17517. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  17518. default:
  17519. case TGATools._ORIGIN_UL:
  17520. x_start = 0;
  17521. x_step = 1;
  17522. x_end = header.width;
  17523. y_start = 0;
  17524. y_step = 1;
  17525. y_end = header.height;
  17526. break;
  17527. case TGATools._ORIGIN_BL:
  17528. x_start = 0;
  17529. x_step = 1;
  17530. x_end = header.width;
  17531. y_start = header.height - 1;
  17532. y_step = -1;
  17533. y_end = -1;
  17534. break;
  17535. case TGATools._ORIGIN_UR:
  17536. x_start = header.width - 1;
  17537. x_step = -1;
  17538. x_end = -1;
  17539. y_start = 0;
  17540. y_step = 1;
  17541. y_end = header.height;
  17542. break;
  17543. case TGATools._ORIGIN_BR:
  17544. x_start = header.width - 1;
  17545. x_step = -1;
  17546. x_end = -1;
  17547. y_start = header.height - 1;
  17548. y_step = -1;
  17549. y_end = -1;
  17550. break;
  17551. }
  17552. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  17553. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  17554. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  17555. };
  17556. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17557. var image = pixel_data, colormap = palettes;
  17558. var width = header.width, height = header.height;
  17559. var color, i = 0, x, y;
  17560. var imageData = new Uint8Array(width * height * 4);
  17561. for (y = y_start; y !== y_end; y += y_step) {
  17562. for (x = x_start; x !== x_end; x += x_step, i++) {
  17563. color = image[i];
  17564. imageData[(x + width * y) * 4 + 3] = 255;
  17565. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  17566. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  17567. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  17568. }
  17569. }
  17570. return imageData;
  17571. };
  17572. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17573. var image = pixel_data;
  17574. var width = header.width, height = header.height;
  17575. var color, i = 0, x, y;
  17576. var imageData = new Uint8Array(width * height * 4);
  17577. for (y = y_start; y !== y_end; y += y_step) {
  17578. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  17579. color = image[i + 0] + (image[i + 1] << 8);
  17580. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  17581. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  17582. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  17583. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  17584. }
  17585. }
  17586. return imageData;
  17587. };
  17588. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17589. var image = pixel_data;
  17590. var width = header.width, height = header.height;
  17591. var i = 0, x, y;
  17592. var imageData = new Uint8Array(width * height * 4);
  17593. for (y = y_start; y !== y_end; y += y_step) {
  17594. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  17595. imageData[(x + width * y) * 4 + 3] = 255;
  17596. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17597. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  17598. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  17599. }
  17600. }
  17601. return imageData;
  17602. };
  17603. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17604. var image = pixel_data;
  17605. var width = header.width, height = header.height;
  17606. var i = 0, x, y;
  17607. var imageData = new Uint8Array(width * height * 4);
  17608. for (y = y_start; y !== y_end; y += y_step) {
  17609. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  17610. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17611. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  17612. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  17613. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  17614. }
  17615. }
  17616. return imageData;
  17617. };
  17618. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17619. var image = pixel_data;
  17620. var width = header.width, height = header.height;
  17621. var color, i = 0, x, y;
  17622. var imageData = new Uint8Array(width * height * 4);
  17623. for (y = y_start; y !== y_end; y += y_step) {
  17624. for (x = x_start; x !== x_end; x += x_step, i++) {
  17625. color = image[i];
  17626. imageData[(x + width * y) * 4 + 0] = color;
  17627. imageData[(x + width * y) * 4 + 1] = color;
  17628. imageData[(x + width * y) * 4 + 2] = color;
  17629. imageData[(x + width * y) * 4 + 3] = 255;
  17630. }
  17631. }
  17632. return imageData;
  17633. };
  17634. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17635. var image = pixel_data;
  17636. var width = header.width, height = header.height;
  17637. var i = 0, x, y;
  17638. var imageData = new Uint8Array(width * height * 4);
  17639. for (y = y_start; y !== y_end; y += y_step) {
  17640. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  17641. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  17642. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  17643. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17644. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  17645. }
  17646. }
  17647. return imageData;
  17648. };
  17649. TGATools._TYPE_NO_DATA = 0;
  17650. TGATools._TYPE_INDEXED = 1;
  17651. TGATools._TYPE_RGB = 2;
  17652. TGATools._TYPE_GREY = 3;
  17653. TGATools._TYPE_RLE_INDEXED = 9;
  17654. TGATools._TYPE_RLE_RGB = 10;
  17655. TGATools._TYPE_RLE_GREY = 11;
  17656. TGATools._ORIGIN_MASK = 0x30;
  17657. TGATools._ORIGIN_SHIFT = 0x04;
  17658. TGATools._ORIGIN_BL = 0x00;
  17659. TGATools._ORIGIN_BR = 0x01;
  17660. TGATools._ORIGIN_UL = 0x02;
  17661. TGATools._ORIGIN_UR = 0x03;
  17662. return TGATools;
  17663. })();
  17664. Internals.TGATools = TGATools;
  17665. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17666. var Internals = BABYLON.Internals;
  17667. })(BABYLON || (BABYLON = {}));
  17668. var BABYLON;
  17669. (function (BABYLON) {
  17670. (function (Internals) {
  17671. var DDS_MAGIC = 0x20534444;
  17672. var DDSD_CAPS = 0x1, DDSD_HEIGHT = 0x2, DDSD_WIDTH = 0x4, DDSD_PITCH = 0x8, DDSD_PIXELFORMAT = 0x1000, DDSD_MIPMAPCOUNT = 0x20000, DDSD_LINEARSIZE = 0x80000, DDSD_DEPTH = 0x800000;
  17673. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  17674. var DDSCAPS2_CUBEMAP = 0x200, DDSCAPS2_CUBEMAP_POSITIVEX = 0x400, DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800, DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000, DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000, DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000, DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000, DDSCAPS2_VOLUME = 0x200000;
  17675. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  17676. function FourCCToInt32(value) {
  17677. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  17678. }
  17679. function Int32ToFourCC(value) {
  17680. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  17681. }
  17682. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  17683. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  17684. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  17685. var headerLengthInt = 31;
  17686. var off_magic = 0;
  17687. var off_size = 1;
  17688. var off_flags = 2;
  17689. var off_height = 3;
  17690. var off_width = 4;
  17691. var off_mipmapCount = 7;
  17692. var off_pfFlags = 20;
  17693. var off_pfFourCC = 21;
  17694. var off_RGBbpp = 22;
  17695. var off_RMask = 23;
  17696. var off_GMask = 24;
  17697. var off_BMask = 25;
  17698. var off_AMask = 26;
  17699. var off_caps1 = 27;
  17700. var off_caps2 = 28;
  17701. ;
  17702. var DDSTools = (function () {
  17703. function DDSTools() {
  17704. }
  17705. DDSTools.GetDDSInfo = function (arrayBuffer) {
  17706. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  17707. var mipmapCount = 1;
  17708. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  17709. mipmapCount = Math.max(1, header[off_mipmapCount]);
  17710. }
  17711. return {
  17712. width: header[off_width],
  17713. height: header[off_height],
  17714. mipmapCount: mipmapCount,
  17715. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  17716. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  17717. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  17718. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  17719. };
  17720. };
  17721. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17722. var byteArray = new Uint8Array(dataLength);
  17723. var srcData = new Uint8Array(arrayBuffer);
  17724. var index = 0;
  17725. for (var y = height - 1; y >= 0; y--) {
  17726. for (var x = 0; x < width; x++) {
  17727. var srcPos = dataOffset + (x + y * width) * 4;
  17728. byteArray[index + 2] = srcData[srcPos];
  17729. byteArray[index + 1] = srcData[srcPos + 1];
  17730. byteArray[index] = srcData[srcPos + 2];
  17731. byteArray[index + 3] = srcData[srcPos + 3];
  17732. index += 4;
  17733. }
  17734. }
  17735. return byteArray;
  17736. };
  17737. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17738. var byteArray = new Uint8Array(dataLength);
  17739. var srcData = new Uint8Array(arrayBuffer);
  17740. var index = 0;
  17741. for (var y = height - 1; y >= 0; y--) {
  17742. for (var x = 0; x < width; x++) {
  17743. var srcPos = dataOffset + (x + y * width) * 3;
  17744. byteArray[index + 2] = srcData[srcPos];
  17745. byteArray[index + 1] = srcData[srcPos + 1];
  17746. byteArray[index] = srcData[srcPos + 2];
  17747. index += 3;
  17748. }
  17749. }
  17750. return byteArray;
  17751. };
  17752. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17753. var byteArray = new Uint8Array(dataLength);
  17754. var srcData = new Uint8Array(arrayBuffer);
  17755. var index = 0;
  17756. for (var y = height - 1; y >= 0; y--) {
  17757. for (var x = 0; x < width; x++) {
  17758. var srcPos = dataOffset + (x + y * width);
  17759. byteArray[index] = srcData[srcPos];
  17760. index++;
  17761. }
  17762. }
  17763. return byteArray;
  17764. };
  17765. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  17766. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  17767. if (header[off_magic] != DDS_MAGIC) {
  17768. BABYLON.Tools.Error("Invalid magic number in DDS header");
  17769. return;
  17770. }
  17771. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  17772. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  17773. return;
  17774. }
  17775. if (info.isFourCC) {
  17776. fourCC = header[off_pfFourCC];
  17777. switch (fourCC) {
  17778. case FOURCC_DXT1:
  17779. blockBytes = 8;
  17780. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  17781. break;
  17782. case FOURCC_DXT3:
  17783. blockBytes = 16;
  17784. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  17785. break;
  17786. case FOURCC_DXT5:
  17787. blockBytes = 16;
  17788. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  17789. break;
  17790. default:
  17791. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  17792. return;
  17793. }
  17794. }
  17795. mipmapCount = 1;
  17796. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  17797. mipmapCount = Math.max(1, header[off_mipmapCount]);
  17798. }
  17799. var bpp = header[off_RGBbpp];
  17800. for (var face = 0; face < faces; face++) {
  17801. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  17802. width = header[off_width];
  17803. height = header[off_height];
  17804. dataOffset = header[off_size] + 4;
  17805. for (i = 0; i < mipmapCount; ++i) {
  17806. if (info.isRGB) {
  17807. if (bpp == 24) {
  17808. dataLength = width * height * 3;
  17809. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17810. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  17811. } else {
  17812. dataLength = width * height * 4;
  17813. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17814. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  17815. }
  17816. } else if (info.isLuminance) {
  17817. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  17818. var unpaddedRowSize = width;
  17819. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  17820. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  17821. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17822. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  17823. } else {
  17824. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  17825. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  17826. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  17827. }
  17828. dataOffset += dataLength;
  17829. width *= 0.5;
  17830. height *= 0.5;
  17831. width = Math.max(1.0, width);
  17832. height = Math.max(1.0, height);
  17833. }
  17834. }
  17835. };
  17836. return DDSTools;
  17837. })();
  17838. Internals.DDSTools = DDSTools;
  17839. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17840. var Internals = BABYLON.Internals;
  17841. })(BABYLON || (BABYLON = {}));
  17842. var BABYLON;
  17843. (function (BABYLON) {
  17844. var SmartArray = (function () {
  17845. function SmartArray(capacity) {
  17846. this.length = 0;
  17847. this._duplicateId = 0;
  17848. this.data = new Array(capacity);
  17849. this._id = SmartArray._GlobalId++;
  17850. }
  17851. SmartArray.prototype.push = function (value) {
  17852. this.data[this.length++] = value;
  17853. if (this.length > this.data.length) {
  17854. this.data.length *= 2;
  17855. }
  17856. if (!value.__smartArrayFlags) {
  17857. value.__smartArrayFlags = {};
  17858. }
  17859. value.__smartArrayFlags[this._id] = this._duplicateId;
  17860. };
  17861. SmartArray.prototype.pushNoDuplicate = function (value) {
  17862. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  17863. return;
  17864. }
  17865. this.push(value);
  17866. };
  17867. SmartArray.prototype.sort = function (compareFn) {
  17868. this.data.sort(compareFn);
  17869. };
  17870. SmartArray.prototype.reset = function () {
  17871. this.length = 0;
  17872. this._duplicateId++;
  17873. };
  17874. SmartArray.prototype.concat = function (array) {
  17875. if (array.length === 0) {
  17876. return;
  17877. }
  17878. if (this.length + array.length > this.data.length) {
  17879. this.data.length = (this.length + array.length) * 2;
  17880. }
  17881. for (var index = 0; index < array.length; index++) {
  17882. this.data[this.length++] = (array.data || array)[index];
  17883. }
  17884. };
  17885. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  17886. if (array.length === 0) {
  17887. return;
  17888. }
  17889. if (this.length + array.length > this.data.length) {
  17890. this.data.length = (this.length + array.length) * 2;
  17891. }
  17892. for (var index = 0; index < array.length; index++) {
  17893. var item = (array.data || array)[index];
  17894. this.pushNoDuplicate(item);
  17895. }
  17896. };
  17897. SmartArray.prototype.indexOf = function (value) {
  17898. var position = this.data.indexOf(value);
  17899. if (position >= this.length) {
  17900. return -1;
  17901. }
  17902. return position;
  17903. };
  17904. SmartArray._GlobalId = 0;
  17905. return SmartArray;
  17906. })();
  17907. BABYLON.SmartArray = SmartArray;
  17908. })(BABYLON || (BABYLON = {}));
  17909. var BABYLON;
  17910. (function (BABYLON) {
  17911. var CannonJSPlugin = (function () {
  17912. function CannonJSPlugin() {
  17913. this._registeredMeshes = [];
  17914. this._physicsMaterials = [];
  17915. this.updateBodyPosition = function (mesh) {
  17916. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17917. var registeredMesh = this._registeredMeshes[index];
  17918. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17919. var body = registeredMesh.body.body;
  17920. var center = mesh.getBoundingInfo().boundingBox.center;
  17921. body.position.set(center.x, center.z, center.y);
  17922. body.quaternion.x = mesh.rotationQuaternion.x;
  17923. body.quaternion.z = mesh.rotationQuaternion.y;
  17924. body.quaternion.y = mesh.rotationQuaternion.z;
  17925. body.quaternion.w = -mesh.rotationQuaternion.w;
  17926. return;
  17927. }
  17928. }
  17929. };
  17930. }
  17931. CannonJSPlugin.prototype.initialize = function (iterations) {
  17932. if (typeof iterations === "undefined") { iterations = 10; }
  17933. this._world = new CANNON.World();
  17934. this._world.broadphase = new CANNON.NaiveBroadphase();
  17935. this._world.solver.iterations = iterations;
  17936. };
  17937. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  17938. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17939. };
  17940. CannonJSPlugin.prototype.runOneStep = function (delta) {
  17941. this._world.step(delta);
  17942. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17943. var registeredMesh = this._registeredMeshes[index];
  17944. if (registeredMesh.isChild) {
  17945. continue;
  17946. }
  17947. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  17948. var deltaPos = registeredMesh.delta;
  17949. if (deltaPos) {
  17950. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  17951. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  17952. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  17953. } else {
  17954. registeredMesh.mesh.position.x = bodyX;
  17955. registeredMesh.mesh.position.y = bodyZ;
  17956. registeredMesh.mesh.position.z = bodyY;
  17957. }
  17958. if (!registeredMesh.mesh.rotationQuaternion) {
  17959. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17960. }
  17961. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  17962. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  17963. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  17964. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  17965. }
  17966. };
  17967. CannonJSPlugin.prototype.setGravity = function (gravity) {
  17968. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  17969. };
  17970. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17971. this.unregisterMesh(mesh);
  17972. mesh.computeWorldMatrix(true);
  17973. switch (impostor) {
  17974. case BABYLON.PhysicsEngine.SphereImpostor:
  17975. var bbox = mesh.getBoundingInfo().boundingBox;
  17976. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17977. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17978. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17979. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  17980. case BABYLON.PhysicsEngine.BoxImpostor:
  17981. bbox = mesh.getBoundingInfo().boundingBox;
  17982. var min = bbox.minimumWorld;
  17983. var max = bbox.maximumWorld;
  17984. var box = max.subtract(min).scale(0.5);
  17985. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  17986. case BABYLON.PhysicsEngine.PlaneImpostor:
  17987. return this._createPlane(mesh, options);
  17988. case BABYLON.PhysicsEngine.MeshImpostor:
  17989. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17990. var rawFaces = mesh.getIndices();
  17991. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  17992. }
  17993. return null;
  17994. };
  17995. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  17996. var shape = new CANNON.Sphere(radius);
  17997. if (!options) {
  17998. return shape;
  17999. }
  18000. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18001. };
  18002. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  18003. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  18004. if (!options) {
  18005. return shape;
  18006. }
  18007. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18008. };
  18009. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  18010. var shape = new CANNON.Plane();
  18011. if (!options) {
  18012. return shape;
  18013. }
  18014. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18015. };
  18016. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  18017. var verts = [], faces = [];
  18018. mesh.computeWorldMatrix(true);
  18019. for (var i = 0; i < rawVerts.length; i += 3) {
  18020. var transformed = BABYLON.Vector3.Zero();
  18021. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  18022. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  18023. }
  18024. for (var j = 0; j < rawFaces.length; j += 3) {
  18025. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  18026. }
  18027. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  18028. if (!options) {
  18029. return shape;
  18030. }
  18031. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18032. };
  18033. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  18034. var index;
  18035. var mat;
  18036. for (index = 0; index < this._physicsMaterials.length; index++) {
  18037. mat = this._physicsMaterials[index];
  18038. if (mat.friction === friction && mat.restitution === restitution) {
  18039. return mat;
  18040. }
  18041. }
  18042. var currentMat = new CANNON.Material();
  18043. currentMat.friction = friction;
  18044. currentMat.restitution = restitution;
  18045. this._physicsMaterials.push(currentMat);
  18046. for (index = 0; index < this._physicsMaterials.length; index++) {
  18047. mat = this._physicsMaterials[index];
  18048. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  18049. contactMaterial.contactEquationStiffness = 1e10;
  18050. contactMaterial.contactEquationRegularizationTime = 10;
  18051. this._world.addContactMaterial(contactMaterial);
  18052. }
  18053. return currentMat;
  18054. };
  18055. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  18056. var initialRotation = null;
  18057. if (mesh.rotationQuaternion) {
  18058. initialRotation = mesh.rotationQuaternion.clone();
  18059. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18060. }
  18061. var bbox = mesh.getBoundingInfo().boundingBox;
  18062. var deltaPosition = mesh.position.subtract(bbox.center);
  18063. var material = this._addMaterial(friction, restitution);
  18064. var body = new CANNON.RigidBody(mass, shape, material);
  18065. if (initialRotation) {
  18066. body.quaternion.x = initialRotation.x;
  18067. body.quaternion.z = initialRotation.y;
  18068. body.quaternion.y = initialRotation.z;
  18069. body.quaternion.w = -initialRotation.w;
  18070. }
  18071. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  18072. this._world.add(body);
  18073. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  18074. return body;
  18075. };
  18076. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  18077. var compoundShape = new CANNON.Compound();
  18078. for (var index = 0; index < parts.length; index++) {
  18079. var mesh = parts[index].mesh;
  18080. var shape = this.registerMesh(mesh, parts[index].impostor);
  18081. if (index == 0) {
  18082. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  18083. } else {
  18084. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  18085. }
  18086. }
  18087. var initialMesh = parts[0].mesh;
  18088. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  18089. body.parts = parts;
  18090. return body;
  18091. };
  18092. CannonJSPlugin.prototype._unbindBody = function (body) {
  18093. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18094. var registeredMesh = this._registeredMeshes[index];
  18095. if (registeredMesh.body === body) {
  18096. registeredMesh.body = null;
  18097. registeredMesh.delta = 0;
  18098. }
  18099. }
  18100. };
  18101. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  18102. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18103. var registeredMesh = this._registeredMeshes[index];
  18104. if (registeredMesh.mesh === mesh) {
  18105. if (registeredMesh.body) {
  18106. this._world.remove(registeredMesh.body);
  18107. this._unbindBody(registeredMesh.body);
  18108. }
  18109. this._registeredMeshes.splice(index, 1);
  18110. return;
  18111. }
  18112. }
  18113. };
  18114. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  18115. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  18116. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  18117. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18118. var registeredMesh = this._registeredMeshes[index];
  18119. if (registeredMesh.mesh === mesh) {
  18120. registeredMesh.body.applyImpulse(impulse, worldPoint);
  18121. return;
  18122. }
  18123. }
  18124. };
  18125. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  18126. var body1 = null, body2 = null;
  18127. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18128. var registeredMesh = this._registeredMeshes[index];
  18129. if (registeredMesh.mesh === mesh1) {
  18130. body1 = registeredMesh.body;
  18131. } else if (registeredMesh.mesh === mesh2) {
  18132. body2 = registeredMesh.body;
  18133. }
  18134. }
  18135. if (!body1 || !body2) {
  18136. return false;
  18137. }
  18138. var constraint = new CANNON.PointToPointConstraint(body1, new CANNON.Vec3(pivot1.x, pivot1.z, pivot1.y), body2, new CANNON.Vec3(pivot2.x, pivot2.z, pivot2.y));
  18139. this._world.addConstraint(constraint);
  18140. return true;
  18141. };
  18142. CannonJSPlugin.prototype.dispose = function () {
  18143. while (this._registeredMeshes.length) {
  18144. this.unregisterMesh(this._registeredMeshes[0].mesh);
  18145. }
  18146. };
  18147. CannonJSPlugin.prototype.isSupported = function () {
  18148. return window.CANNON !== undefined;
  18149. };
  18150. return CannonJSPlugin;
  18151. })();
  18152. BABYLON.CannonJSPlugin = CannonJSPlugin;
  18153. })(BABYLON || (BABYLON = {}));
  18154. var __extends = this.__extends || function (d, b) {
  18155. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18156. function __() { this.constructor = d; }
  18157. __.prototype = b.prototype;
  18158. d.prototype = new __();
  18159. };
  18160. var BABYLON;
  18161. (function (BABYLON) {
  18162. var Condition = (function () {
  18163. function Condition(actionManager) {
  18164. this._actionManager = actionManager;
  18165. }
  18166. Condition.prototype.isValid = function () {
  18167. return true;
  18168. };
  18169. Condition.prototype._getProperty = function (propertyPath) {
  18170. return this._actionManager._getProperty(propertyPath);
  18171. };
  18172. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  18173. return this._actionManager._getEffectiveTarget(target, propertyPath);
  18174. };
  18175. return Condition;
  18176. })();
  18177. BABYLON.Condition = Condition;
  18178. var ValueCondition = (function (_super) {
  18179. __extends(ValueCondition, _super);
  18180. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  18181. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  18182. _super.call(this, actionManager);
  18183. this.propertyPath = propertyPath;
  18184. this.value = value;
  18185. this.operator = operator;
  18186. this._target = this._getEffectiveTarget(target, this.propertyPath);
  18187. this._property = this._getProperty(this.propertyPath);
  18188. }
  18189. Object.defineProperty(ValueCondition, "IsEqual", {
  18190. get: function () {
  18191. return ValueCondition._IsEqual;
  18192. },
  18193. enumerable: true,
  18194. configurable: true
  18195. });
  18196. Object.defineProperty(ValueCondition, "IsDifferent", {
  18197. get: function () {
  18198. return ValueCondition._IsDifferent;
  18199. },
  18200. enumerable: true,
  18201. configurable: true
  18202. });
  18203. Object.defineProperty(ValueCondition, "IsGreater", {
  18204. get: function () {
  18205. return ValueCondition._IsGreater;
  18206. },
  18207. enumerable: true,
  18208. configurable: true
  18209. });
  18210. Object.defineProperty(ValueCondition, "IsLesser", {
  18211. get: function () {
  18212. return ValueCondition._IsLesser;
  18213. },
  18214. enumerable: true,
  18215. configurable: true
  18216. });
  18217. ValueCondition.prototype.isValid = function () {
  18218. switch (this.operator) {
  18219. case ValueCondition.IsGreater:
  18220. return this._target[this._property] > this.value;
  18221. case ValueCondition.IsLesser:
  18222. return this._target[this._property] < this.value;
  18223. case ValueCondition.IsEqual:
  18224. case ValueCondition.IsDifferent:
  18225. var check;
  18226. if (this.value.equals) {
  18227. check = this.value.equals(this._target[this._property]);
  18228. } else {
  18229. check = this.value === this._target[this._property];
  18230. }
  18231. return this.operator === ValueCondition.IsEqual ? check : !check;
  18232. }
  18233. return false;
  18234. };
  18235. ValueCondition._IsEqual = 0;
  18236. ValueCondition._IsDifferent = 1;
  18237. ValueCondition._IsGreater = 2;
  18238. ValueCondition._IsLesser = 3;
  18239. return ValueCondition;
  18240. })(Condition);
  18241. BABYLON.ValueCondition = ValueCondition;
  18242. var PredicateCondition = (function (_super) {
  18243. __extends(PredicateCondition, _super);
  18244. function PredicateCondition(actionManager, predicate) {
  18245. _super.call(this, actionManager);
  18246. this.predicate = predicate;
  18247. }
  18248. PredicateCondition.prototype.isValid = function () {
  18249. return this.predicate();
  18250. };
  18251. return PredicateCondition;
  18252. })(Condition);
  18253. BABYLON.PredicateCondition = PredicateCondition;
  18254. var StateCondition = (function (_super) {
  18255. __extends(StateCondition, _super);
  18256. function StateCondition(actionManager, target, value) {
  18257. _super.call(this, actionManager);
  18258. this.value = value;
  18259. this._target = target;
  18260. }
  18261. StateCondition.prototype.isValid = function () {
  18262. return this._target.state === this.value;
  18263. };
  18264. return StateCondition;
  18265. })(Condition);
  18266. BABYLON.StateCondition = StateCondition;
  18267. })(BABYLON || (BABYLON = {}));
  18268. var BABYLON;
  18269. (function (BABYLON) {
  18270. var Action = (function () {
  18271. function Action(triggerOptions, condition) {
  18272. this.triggerOptions = triggerOptions;
  18273. if (triggerOptions.parameter) {
  18274. this.trigger = triggerOptions.trigger;
  18275. this._triggerParameter = triggerOptions.parameter;
  18276. } else {
  18277. this.trigger = triggerOptions;
  18278. }
  18279. this._nextActiveAction = this;
  18280. this._condition = condition;
  18281. }
  18282. Action.prototype._prepare = function () {
  18283. };
  18284. Action.prototype.getTriggerParameter = function () {
  18285. return this._triggerParameter;
  18286. };
  18287. Action.prototype._executeCurrent = function (evt) {
  18288. if (this._condition) {
  18289. var currentRenderId = this._actionManager.getScene().getRenderId();
  18290. if (this._condition._evaluationId === currentRenderId) {
  18291. if (!this._condition._currentResult) {
  18292. return;
  18293. }
  18294. } else {
  18295. this._condition._evaluationId = currentRenderId;
  18296. if (!this._condition.isValid()) {
  18297. this._condition._currentResult = false;
  18298. return;
  18299. }
  18300. this._condition._currentResult = true;
  18301. }
  18302. }
  18303. this._nextActiveAction.execute(evt);
  18304. if (this._nextActiveAction._child) {
  18305. this._nextActiveAction = this._nextActiveAction._child;
  18306. } else {
  18307. this._nextActiveAction = this;
  18308. }
  18309. };
  18310. Action.prototype.execute = function (evt) {
  18311. };
  18312. Action.prototype.then = function (action) {
  18313. this._child = action;
  18314. action._actionManager = this._actionManager;
  18315. action._prepare();
  18316. return action;
  18317. };
  18318. Action.prototype._getProperty = function (propertyPath) {
  18319. return this._actionManager._getProperty(propertyPath);
  18320. };
  18321. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  18322. return this._actionManager._getEffectiveTarget(target, propertyPath);
  18323. };
  18324. return Action;
  18325. })();
  18326. BABYLON.Action = Action;
  18327. })(BABYLON || (BABYLON = {}));
  18328. var BABYLON;
  18329. (function (BABYLON) {
  18330. var ActionEvent = (function () {
  18331. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  18332. this.source = source;
  18333. this.pointerX = pointerX;
  18334. this.pointerY = pointerY;
  18335. this.meshUnderPointer = meshUnderPointer;
  18336. this.sourceEvent = sourceEvent;
  18337. }
  18338. ActionEvent.CreateNew = function (source) {
  18339. var scene = source.getScene();
  18340. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer);
  18341. };
  18342. ActionEvent.CreateNewFromScene = function (scene, evt) {
  18343. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  18344. };
  18345. return ActionEvent;
  18346. })();
  18347. BABYLON.ActionEvent = ActionEvent;
  18348. var ActionManager = (function () {
  18349. function ActionManager(scene) {
  18350. this.actions = new Array();
  18351. this._scene = scene;
  18352. scene._actionManagers.push(this);
  18353. }
  18354. Object.defineProperty(ActionManager, "NothingTrigger", {
  18355. get: function () {
  18356. return ActionManager._NothingTrigger;
  18357. },
  18358. enumerable: true,
  18359. configurable: true
  18360. });
  18361. Object.defineProperty(ActionManager, "OnPickTrigger", {
  18362. get: function () {
  18363. return ActionManager._OnPickTrigger;
  18364. },
  18365. enumerable: true,
  18366. configurable: true
  18367. });
  18368. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  18369. get: function () {
  18370. return ActionManager._OnLeftPickTrigger;
  18371. },
  18372. enumerable: true,
  18373. configurable: true
  18374. });
  18375. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  18376. get: function () {
  18377. return ActionManager._OnRightPickTrigger;
  18378. },
  18379. enumerable: true,
  18380. configurable: true
  18381. });
  18382. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  18383. get: function () {
  18384. return ActionManager._OnCenterPickTrigger;
  18385. },
  18386. enumerable: true,
  18387. configurable: true
  18388. });
  18389. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  18390. get: function () {
  18391. return ActionManager._OnPointerOverTrigger;
  18392. },
  18393. enumerable: true,
  18394. configurable: true
  18395. });
  18396. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  18397. get: function () {
  18398. return ActionManager._OnPointerOutTrigger;
  18399. },
  18400. enumerable: true,
  18401. configurable: true
  18402. });
  18403. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  18404. get: function () {
  18405. return ActionManager._OnEveryFrameTrigger;
  18406. },
  18407. enumerable: true,
  18408. configurable: true
  18409. });
  18410. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  18411. get: function () {
  18412. return ActionManager._OnIntersectionEnterTrigger;
  18413. },
  18414. enumerable: true,
  18415. configurable: true
  18416. });
  18417. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  18418. get: function () {
  18419. return ActionManager._OnIntersectionExitTrigger;
  18420. },
  18421. enumerable: true,
  18422. configurable: true
  18423. });
  18424. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  18425. get: function () {
  18426. return ActionManager._OnKeyDownTrigger;
  18427. },
  18428. enumerable: true,
  18429. configurable: true
  18430. });
  18431. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  18432. get: function () {
  18433. return ActionManager._OnKeyUpTrigger;
  18434. },
  18435. enumerable: true,
  18436. configurable: true
  18437. });
  18438. ActionManager.prototype.dispose = function () {
  18439. var index = this._scene._actionManagers.indexOf(this);
  18440. if (index > -1) {
  18441. this._scene._actionManagers.splice(index, 1);
  18442. }
  18443. };
  18444. ActionManager.prototype.getScene = function () {
  18445. return this._scene;
  18446. };
  18447. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  18448. for (var index = 0; index < this.actions.length; index++) {
  18449. var action = this.actions[index];
  18450. if (triggers.indexOf(action.trigger) > -1) {
  18451. return true;
  18452. }
  18453. }
  18454. return false;
  18455. };
  18456. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  18457. get: function () {
  18458. for (var index = 0; index < this.actions.length; index++) {
  18459. var action = this.actions[index];
  18460. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  18461. return true;
  18462. }
  18463. }
  18464. return false;
  18465. },
  18466. enumerable: true,
  18467. configurable: true
  18468. });
  18469. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  18470. get: function () {
  18471. for (var index = 0; index < this.actions.length; index++) {
  18472. var action = this.actions[index];
  18473. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  18474. return true;
  18475. }
  18476. }
  18477. return false;
  18478. },
  18479. enumerable: true,
  18480. configurable: true
  18481. });
  18482. ActionManager.prototype.registerAction = function (action) {
  18483. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  18484. if (this.getScene().actionManager !== this) {
  18485. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  18486. return null;
  18487. }
  18488. }
  18489. this.actions.push(action);
  18490. action._actionManager = this;
  18491. action._prepare();
  18492. return action;
  18493. };
  18494. ActionManager.prototype.processTrigger = function (trigger, evt) {
  18495. for (var index = 0; index < this.actions.length; index++) {
  18496. var action = this.actions[index];
  18497. if (action.trigger === trigger) {
  18498. if (trigger == ActionManager.OnKeyUpTrigger || trigger == ActionManager.OnKeyDownTrigger) {
  18499. var parameter = action.getTriggerParameter();
  18500. if (parameter) {
  18501. if (evt.sourceEvent.key !== parameter) {
  18502. continue;
  18503. }
  18504. }
  18505. }
  18506. action._executeCurrent(evt);
  18507. }
  18508. }
  18509. };
  18510. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  18511. var properties = propertyPath.split(".");
  18512. for (var index = 0; index < properties.length - 1; index++) {
  18513. target = target[properties[index]];
  18514. }
  18515. return target;
  18516. };
  18517. ActionManager.prototype._getProperty = function (propertyPath) {
  18518. var properties = propertyPath.split(".");
  18519. return properties[properties.length - 1];
  18520. };
  18521. ActionManager._NothingTrigger = 0;
  18522. ActionManager._OnPickTrigger = 1;
  18523. ActionManager._OnLeftPickTrigger = 2;
  18524. ActionManager._OnRightPickTrigger = 3;
  18525. ActionManager._OnCenterPickTrigger = 4;
  18526. ActionManager._OnPointerOverTrigger = 5;
  18527. ActionManager._OnPointerOutTrigger = 6;
  18528. ActionManager._OnEveryFrameTrigger = 7;
  18529. ActionManager._OnIntersectionEnterTrigger = 8;
  18530. ActionManager._OnIntersectionExitTrigger = 9;
  18531. ActionManager._OnKeyDownTrigger = 10;
  18532. ActionManager._OnKeyUpTrigger = 11;
  18533. return ActionManager;
  18534. })();
  18535. BABYLON.ActionManager = ActionManager;
  18536. })(BABYLON || (BABYLON = {}));
  18537. var __extends = this.__extends || function (d, b) {
  18538. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18539. function __() { this.constructor = d; }
  18540. __.prototype = b.prototype;
  18541. d.prototype = new __();
  18542. };
  18543. var BABYLON;
  18544. (function (BABYLON) {
  18545. var InterpolateValueAction = (function (_super) {
  18546. __extends(InterpolateValueAction, _super);
  18547. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  18548. if (typeof duration === "undefined") { duration = 1000; }
  18549. _super.call(this, triggerOptions, condition);
  18550. this.propertyPath = propertyPath;
  18551. this.value = value;
  18552. this.duration = duration;
  18553. this.stopOtherAnimations = stopOtherAnimations;
  18554. this._target = target;
  18555. }
  18556. InterpolateValueAction.prototype._prepare = function () {
  18557. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18558. this._property = this._getProperty(this.propertyPath);
  18559. };
  18560. InterpolateValueAction.prototype.execute = function () {
  18561. var scene = this._actionManager.getScene();
  18562. var keys = [
  18563. {
  18564. frame: 0,
  18565. value: this._target[this._property]
  18566. }, {
  18567. frame: 100,
  18568. value: this.value
  18569. }
  18570. ];
  18571. var dataType;
  18572. if (typeof this.value === "number") {
  18573. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  18574. } else if (this.value instanceof BABYLON.Color3) {
  18575. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  18576. } else if (this.value instanceof BABYLON.Vector3) {
  18577. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  18578. } else if (this.value instanceof BABYLON.Matrix) {
  18579. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  18580. } else if (this.value instanceof BABYLON.Quaternion) {
  18581. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  18582. } else {
  18583. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  18584. return;
  18585. }
  18586. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  18587. animation.setKeys(keys);
  18588. if (this.stopOtherAnimations) {
  18589. scene.stopAnimation(this._target);
  18590. }
  18591. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  18592. };
  18593. return InterpolateValueAction;
  18594. })(BABYLON.Action);
  18595. BABYLON.InterpolateValueAction = InterpolateValueAction;
  18596. })(BABYLON || (BABYLON = {}));
  18597. var __extends = this.__extends || function (d, b) {
  18598. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18599. function __() { this.constructor = d; }
  18600. __.prototype = b.prototype;
  18601. d.prototype = new __();
  18602. };
  18603. var BABYLON;
  18604. (function (BABYLON) {
  18605. var SwitchBooleanAction = (function (_super) {
  18606. __extends(SwitchBooleanAction, _super);
  18607. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  18608. _super.call(this, triggerOptions, condition);
  18609. this.propertyPath = propertyPath;
  18610. this._target = target;
  18611. }
  18612. SwitchBooleanAction.prototype._prepare = function () {
  18613. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18614. this._property = this._getProperty(this.propertyPath);
  18615. };
  18616. SwitchBooleanAction.prototype.execute = function () {
  18617. this._target[this._property] = !this._target[this._property];
  18618. };
  18619. return SwitchBooleanAction;
  18620. })(BABYLON.Action);
  18621. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  18622. var SetStateAction = (function (_super) {
  18623. __extends(SetStateAction, _super);
  18624. function SetStateAction(triggerOptions, target, value, condition) {
  18625. _super.call(this, triggerOptions, condition);
  18626. this.value = value;
  18627. this._target = target;
  18628. }
  18629. SetStateAction.prototype.execute = function () {
  18630. this._target.state = this.value;
  18631. };
  18632. return SetStateAction;
  18633. })(BABYLON.Action);
  18634. BABYLON.SetStateAction = SetStateAction;
  18635. var SetValueAction = (function (_super) {
  18636. __extends(SetValueAction, _super);
  18637. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  18638. _super.call(this, triggerOptions, condition);
  18639. this.propertyPath = propertyPath;
  18640. this.value = value;
  18641. this._target = target;
  18642. }
  18643. SetValueAction.prototype._prepare = function () {
  18644. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18645. this._property = this._getProperty(this.propertyPath);
  18646. };
  18647. SetValueAction.prototype.execute = function () {
  18648. this._target[this._property] = this.value;
  18649. };
  18650. return SetValueAction;
  18651. })(BABYLON.Action);
  18652. BABYLON.SetValueAction = SetValueAction;
  18653. var IncrementValueAction = (function (_super) {
  18654. __extends(IncrementValueAction, _super);
  18655. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  18656. _super.call(this, triggerOptions, condition);
  18657. this.propertyPath = propertyPath;
  18658. this.value = value;
  18659. this._target = target;
  18660. }
  18661. IncrementValueAction.prototype._prepare = function () {
  18662. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18663. this._property = this._getProperty(this.propertyPath);
  18664. if (typeof this._target[this._property] !== "number") {
  18665. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  18666. }
  18667. };
  18668. IncrementValueAction.prototype.execute = function () {
  18669. this._target[this._property] += this.value;
  18670. };
  18671. return IncrementValueAction;
  18672. })(BABYLON.Action);
  18673. BABYLON.IncrementValueAction = IncrementValueAction;
  18674. var PlayAnimationAction = (function (_super) {
  18675. __extends(PlayAnimationAction, _super);
  18676. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  18677. _super.call(this, triggerOptions, condition);
  18678. this.from = from;
  18679. this.to = to;
  18680. this.loop = loop;
  18681. this._target = target;
  18682. }
  18683. PlayAnimationAction.prototype._prepare = function () {
  18684. };
  18685. PlayAnimationAction.prototype.execute = function () {
  18686. var scene = this._actionManager.getScene();
  18687. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  18688. };
  18689. return PlayAnimationAction;
  18690. })(BABYLON.Action);
  18691. BABYLON.PlayAnimationAction = PlayAnimationAction;
  18692. var StopAnimationAction = (function (_super) {
  18693. __extends(StopAnimationAction, _super);
  18694. function StopAnimationAction(triggerOptions, target, condition) {
  18695. _super.call(this, triggerOptions, condition);
  18696. this._target = target;
  18697. }
  18698. StopAnimationAction.prototype._prepare = function () {
  18699. };
  18700. StopAnimationAction.prototype.execute = function () {
  18701. var scene = this._actionManager.getScene();
  18702. scene.stopAnimation(this._target);
  18703. };
  18704. return StopAnimationAction;
  18705. })(BABYLON.Action);
  18706. BABYLON.StopAnimationAction = StopAnimationAction;
  18707. var DoNothingAction = (function (_super) {
  18708. __extends(DoNothingAction, _super);
  18709. function DoNothingAction(triggerOptions, condition) {
  18710. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  18711. _super.call(this, triggerOptions, condition);
  18712. }
  18713. DoNothingAction.prototype.execute = function () {
  18714. };
  18715. return DoNothingAction;
  18716. })(BABYLON.Action);
  18717. BABYLON.DoNothingAction = DoNothingAction;
  18718. var CombineAction = (function (_super) {
  18719. __extends(CombineAction, _super);
  18720. function CombineAction(triggerOptions, children, condition) {
  18721. _super.call(this, triggerOptions, condition);
  18722. this.children = children;
  18723. }
  18724. CombineAction.prototype._prepare = function () {
  18725. for (var index = 0; index < this.children.length; index++) {
  18726. this.children[index]._actionManager = this._actionManager;
  18727. this.children[index]._prepare();
  18728. }
  18729. };
  18730. CombineAction.prototype.execute = function (evt) {
  18731. for (var index = 0; index < this.children.length; index++) {
  18732. this.children[index].execute(evt);
  18733. }
  18734. };
  18735. return CombineAction;
  18736. })(BABYLON.Action);
  18737. BABYLON.CombineAction = CombineAction;
  18738. var ExecuteCodeAction = (function (_super) {
  18739. __extends(ExecuteCodeAction, _super);
  18740. function ExecuteCodeAction(triggerOptions, func, condition) {
  18741. _super.call(this, triggerOptions, condition);
  18742. this.func = func;
  18743. }
  18744. ExecuteCodeAction.prototype.execute = function (evt) {
  18745. this.func(evt);
  18746. };
  18747. return ExecuteCodeAction;
  18748. })(BABYLON.Action);
  18749. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  18750. var SetParentAction = (function (_super) {
  18751. __extends(SetParentAction, _super);
  18752. function SetParentAction(triggerOptions, target, parent, condition) {
  18753. _super.call(this, triggerOptions, condition);
  18754. this._target = target;
  18755. this._parent = parent;
  18756. }
  18757. SetParentAction.prototype._prepare = function () {
  18758. };
  18759. SetParentAction.prototype.execute = function () {
  18760. if (this._target.parent === this._parent) {
  18761. return;
  18762. }
  18763. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  18764. invertParentWorldMatrix.invert();
  18765. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  18766. this._target.parent = this._parent;
  18767. };
  18768. return SetParentAction;
  18769. })(BABYLON.Action);
  18770. BABYLON.SetParentAction = SetParentAction;
  18771. })(BABYLON || (BABYLON = {}));
  18772. var __extends = this.__extends || function (d, b) {
  18773. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18774. function __() { this.constructor = d; }
  18775. __.prototype = b.prototype;
  18776. d.prototype = new __();
  18777. };
  18778. var BABYLON;
  18779. (function (BABYLON) {
  18780. var Geometry = (function () {
  18781. function Geometry(id, scene, vertexData, updatable, mesh) {
  18782. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18783. this._totalVertices = 0;
  18784. this._indices = [];
  18785. this.id = id;
  18786. this._engine = scene.getEngine();
  18787. this._meshes = [];
  18788. this._scene = scene;
  18789. if (vertexData) {
  18790. this.setAllVerticesData(vertexData, updatable);
  18791. } else {
  18792. this._totalVertices = 0;
  18793. this._indices = [];
  18794. }
  18795. if (mesh) {
  18796. this.applyToMesh(mesh);
  18797. }
  18798. }
  18799. Geometry.prototype.getScene = function () {
  18800. return this._scene;
  18801. };
  18802. Geometry.prototype.getEngine = function () {
  18803. return this._engine;
  18804. };
  18805. Geometry.prototype.isReady = function () {
  18806. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  18807. };
  18808. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  18809. vertexData.applyToGeometry(this, updatable);
  18810. };
  18811. Geometry.prototype.setVerticesData = function (kind, data, updatable) {
  18812. this._vertexBuffers = this._vertexBuffers || {};
  18813. if (this._vertexBuffers[kind]) {
  18814. this._vertexBuffers[kind].dispose();
  18815. }
  18816. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0);
  18817. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18818. var stride = this._vertexBuffers[kind].getStrideSize();
  18819. this._totalVertices = data.length / stride;
  18820. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  18821. var meshes = this._meshes;
  18822. var numOfMeshes = meshes.length;
  18823. for (var index = 0; index < numOfMeshes; index++) {
  18824. var mesh = meshes[index];
  18825. mesh._resetPointsArrayCache();
  18826. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18827. mesh._createGlobalSubMesh();
  18828. mesh.computeWorldMatrix(true);
  18829. }
  18830. }
  18831. };
  18832. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  18833. var vertexBuffer = this.getVertexBuffer(kind);
  18834. if (!vertexBuffer) {
  18835. return;
  18836. }
  18837. vertexBuffer.update(data);
  18838. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18839. var extend;
  18840. if (updateExtends) {
  18841. var stride = vertexBuffer.getStrideSize();
  18842. this._totalVertices = data.length / stride;
  18843. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  18844. }
  18845. var meshes = this._meshes;
  18846. var numOfMeshes = meshes.length;
  18847. for (var index = 0; index < numOfMeshes; index++) {
  18848. var mesh = meshes[index];
  18849. mesh._resetPointsArrayCache();
  18850. if (updateExtends) {
  18851. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18852. }
  18853. }
  18854. }
  18855. };
  18856. Geometry.prototype.getTotalVertices = function () {
  18857. if (!this.isReady()) {
  18858. return 0;
  18859. }
  18860. return this._totalVertices;
  18861. };
  18862. Geometry.prototype.getVerticesData = function (kind) {
  18863. var vertexBuffer = this.getVertexBuffer(kind);
  18864. if (!vertexBuffer) {
  18865. return null;
  18866. }
  18867. return vertexBuffer.getData();
  18868. };
  18869. Geometry.prototype.getVertexBuffer = function (kind) {
  18870. if (!this.isReady()) {
  18871. return null;
  18872. }
  18873. return this._vertexBuffers[kind];
  18874. };
  18875. Geometry.prototype.getVertexBuffers = function () {
  18876. if (!this.isReady()) {
  18877. return null;
  18878. }
  18879. return this._vertexBuffers;
  18880. };
  18881. Geometry.prototype.isVerticesDataPresent = function (kind) {
  18882. if (!this._vertexBuffers) {
  18883. if (this._delayInfo) {
  18884. return this._delayInfo.indexOf(kind) !== -1;
  18885. }
  18886. return false;
  18887. }
  18888. return this._vertexBuffers[kind] !== undefined;
  18889. };
  18890. Geometry.prototype.getVerticesDataKinds = function () {
  18891. var result = [];
  18892. if (!this._vertexBuffers && this._delayInfo) {
  18893. for (var kind in this._delayInfo) {
  18894. result.push(kind);
  18895. }
  18896. } else {
  18897. for (kind in this._vertexBuffers) {
  18898. result.push(kind);
  18899. }
  18900. }
  18901. return result;
  18902. };
  18903. Geometry.prototype.setIndices = function (indices) {
  18904. if (this._indexBuffer) {
  18905. this._engine._releaseBuffer(this._indexBuffer);
  18906. }
  18907. this._indices = indices;
  18908. if (this._meshes.length !== 0 && this._indices) {
  18909. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  18910. }
  18911. var meshes = this._meshes;
  18912. var numOfMeshes = meshes.length;
  18913. for (var index = 0; index < numOfMeshes; index++) {
  18914. meshes[index]._createGlobalSubMesh();
  18915. }
  18916. };
  18917. Geometry.prototype.getTotalIndices = function () {
  18918. if (!this.isReady()) {
  18919. return 0;
  18920. }
  18921. return this._indices.length;
  18922. };
  18923. Geometry.prototype.getIndices = function () {
  18924. if (!this.isReady()) {
  18925. return null;
  18926. }
  18927. return this._indices;
  18928. };
  18929. Geometry.prototype.getIndexBuffer = function () {
  18930. if (!this.isReady()) {
  18931. return null;
  18932. }
  18933. return this._indexBuffer;
  18934. };
  18935. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  18936. var meshes = this._meshes;
  18937. var index = meshes.indexOf(mesh);
  18938. if (index === -1) {
  18939. return;
  18940. }
  18941. for (var kind in this._vertexBuffers) {
  18942. this._vertexBuffers[kind].dispose();
  18943. }
  18944. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  18945. this._indexBuffer = null;
  18946. }
  18947. meshes.splice(index, 1);
  18948. mesh._geometry = null;
  18949. if (meshes.length == 0 && shouldDispose) {
  18950. this.dispose();
  18951. }
  18952. };
  18953. Geometry.prototype.applyToMesh = function (mesh) {
  18954. if (mesh._geometry === this) {
  18955. return;
  18956. }
  18957. var previousGeometry = mesh._geometry;
  18958. if (previousGeometry) {
  18959. previousGeometry.releaseForMesh(mesh);
  18960. }
  18961. var meshes = this._meshes;
  18962. mesh._geometry = this;
  18963. this._scene.pushGeometry(this);
  18964. meshes.push(mesh);
  18965. if (this.isReady()) {
  18966. this._applyToMesh(mesh);
  18967. } else {
  18968. mesh._boundingInfo = this._boundingInfo;
  18969. }
  18970. };
  18971. Geometry.prototype._applyToMesh = function (mesh) {
  18972. var numOfMeshes = this._meshes.length;
  18973. for (var kind in this._vertexBuffers) {
  18974. if (numOfMeshes === 1) {
  18975. this._vertexBuffers[kind].create();
  18976. }
  18977. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  18978. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18979. mesh._resetPointsArrayCache();
  18980. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  18981. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18982. mesh._createGlobalSubMesh();
  18983. }
  18984. }
  18985. if (numOfMeshes === 1 && this._indices) {
  18986. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  18987. }
  18988. if (this._indexBuffer) {
  18989. this._indexBuffer.references = numOfMeshes;
  18990. }
  18991. };
  18992. Geometry.prototype.load = function (scene, onLoaded) {
  18993. var _this = this;
  18994. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18995. return;
  18996. }
  18997. if (this.isReady()) {
  18998. if (onLoaded) {
  18999. onLoaded();
  19000. }
  19001. return;
  19002. }
  19003. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19004. scene._addPendingData(this);
  19005. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19006. _this._delayLoadingFunction(JSON.parse(data), _this);
  19007. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19008. _this._delayInfo = [];
  19009. scene._removePendingData(_this);
  19010. var meshes = _this._meshes;
  19011. var numOfMeshes = meshes.length;
  19012. for (var index = 0; index < numOfMeshes; index++) {
  19013. _this._applyToMesh(meshes[index]);
  19014. }
  19015. if (onLoaded) {
  19016. onLoaded();
  19017. }
  19018. }, function () {
  19019. }, scene.database);
  19020. };
  19021. Geometry.prototype.dispose = function () {
  19022. var meshes = this._meshes;
  19023. var numOfMeshes = meshes.length;
  19024. for (var index = 0; index < numOfMeshes; index++) {
  19025. this.releaseForMesh(meshes[index]);
  19026. }
  19027. this._meshes = [];
  19028. for (var kind in this._vertexBuffers) {
  19029. this._vertexBuffers[kind].dispose();
  19030. }
  19031. this._vertexBuffers = [];
  19032. this._totalVertices = 0;
  19033. if (this._indexBuffer) {
  19034. this._engine._releaseBuffer(this._indexBuffer);
  19035. }
  19036. this._indexBuffer = null;
  19037. this._indices = [];
  19038. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19039. this.delayLoadingFile = null;
  19040. this._delayLoadingFunction = null;
  19041. this._delayInfo = [];
  19042. this._boundingInfo = null;
  19043. var geometries = this._scene.getGeometries();
  19044. index = geometries.indexOf(this);
  19045. if (index > -1) {
  19046. geometries.splice(index, 1);
  19047. }
  19048. };
  19049. Geometry.prototype.copy = function (id) {
  19050. var vertexData = new BABYLON.VertexData();
  19051. vertexData.indices = [];
  19052. var indices = this.getIndices();
  19053. for (var index = 0; index < indices.length; index++) {
  19054. vertexData.indices.push(indices[index]);
  19055. }
  19056. var updatable = false;
  19057. var stopChecking = false;
  19058. for (var kind in this._vertexBuffers) {
  19059. vertexData.set(this.getVerticesData(kind), kind);
  19060. if (!stopChecking) {
  19061. updatable = this.getVertexBuffer(kind).isUpdatable();
  19062. stopChecking = !updatable;
  19063. }
  19064. }
  19065. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  19066. geometry.delayLoadState = this.delayLoadState;
  19067. geometry.delayLoadingFile = this.delayLoadingFile;
  19068. geometry._delayLoadingFunction = this._delayLoadingFunction;
  19069. for (kind in this._delayInfo) {
  19070. geometry._delayInfo = geometry._delayInfo || [];
  19071. geometry._delayInfo.push(kind);
  19072. }
  19073. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  19074. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19075. return geometry;
  19076. };
  19077. Geometry.ExtractFromMesh = function (mesh, id) {
  19078. var geometry = mesh._geometry;
  19079. if (!geometry) {
  19080. return null;
  19081. }
  19082. return geometry.copy(id);
  19083. };
  19084. Geometry.RandomId = function () {
  19085. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  19086. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  19087. return v.toString(16);
  19088. });
  19089. };
  19090. return Geometry;
  19091. })();
  19092. BABYLON.Geometry = Geometry;
  19093. (function (Geometry) {
  19094. (function (Primitives) {
  19095. var _Primitive = (function (_super) {
  19096. __extends(_Primitive, _super);
  19097. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  19098. this._beingRegenerated = true;
  19099. this._canBeRegenerated = canBeRegenerated;
  19100. _super.call(this, id, scene, vertexData, false, mesh);
  19101. this._beingRegenerated = false;
  19102. }
  19103. _Primitive.prototype.canBeRegenerated = function () {
  19104. return this._canBeRegenerated;
  19105. };
  19106. _Primitive.prototype.regenerate = function () {
  19107. if (!this._canBeRegenerated) {
  19108. return;
  19109. }
  19110. this._beingRegenerated = true;
  19111. this.setAllVerticesData(this._regenerateVertexData(), false);
  19112. this._beingRegenerated = false;
  19113. };
  19114. _Primitive.prototype.asNewGeometry = function (id) {
  19115. return _super.prototype.copy.call(this, id);
  19116. };
  19117. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  19118. if (!this._beingRegenerated) {
  19119. return;
  19120. }
  19121. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  19122. };
  19123. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  19124. if (!this._beingRegenerated) {
  19125. return;
  19126. }
  19127. _super.prototype.setVerticesData.call(this, kind, data, false);
  19128. };
  19129. _Primitive.prototype._regenerateVertexData = function () {
  19130. throw new Error("Abstract method");
  19131. };
  19132. _Primitive.prototype.copy = function (id) {
  19133. throw new Error("Must be overriden in sub-classes.");
  19134. };
  19135. return _Primitive;
  19136. })(Geometry);
  19137. Primitives._Primitive = _Primitive;
  19138. var Box = (function (_super) {
  19139. __extends(Box, _super);
  19140. function Box(id, scene, size, canBeRegenerated, mesh) {
  19141. this.size = size;
  19142. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19143. }
  19144. Box.prototype._regenerateVertexData = function () {
  19145. return BABYLON.VertexData.CreateBox(this.size);
  19146. };
  19147. Box.prototype.copy = function (id) {
  19148. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19149. };
  19150. return Box;
  19151. })(_Primitive);
  19152. Primitives.Box = Box;
  19153. var Sphere = (function (_super) {
  19154. __extends(Sphere, _super);
  19155. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  19156. this.segments = segments;
  19157. this.diameter = diameter;
  19158. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19159. }
  19160. Sphere.prototype._regenerateVertexData = function () {
  19161. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  19162. };
  19163. Sphere.prototype.copy = function (id) {
  19164. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  19165. };
  19166. return Sphere;
  19167. })(_Primitive);
  19168. Primitives.Sphere = Sphere;
  19169. var Cylinder = (function (_super) {
  19170. __extends(Cylinder, _super);
  19171. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  19172. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  19173. this.height = height;
  19174. this.diameterTop = diameterTop;
  19175. this.diameterBottom = diameterBottom;
  19176. this.tessellation = tessellation;
  19177. this.subdivisions = subdivisions;
  19178. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19179. }
  19180. Cylinder.prototype._regenerateVertexData = function () {
  19181. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  19182. };
  19183. Cylinder.prototype.copy = function (id) {
  19184. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  19185. };
  19186. return Cylinder;
  19187. })(_Primitive);
  19188. Primitives.Cylinder = Cylinder;
  19189. var Torus = (function (_super) {
  19190. __extends(Torus, _super);
  19191. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  19192. this.diameter = diameter;
  19193. this.thickness = thickness;
  19194. this.tessellation = tessellation;
  19195. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19196. }
  19197. Torus.prototype._regenerateVertexData = function () {
  19198. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  19199. };
  19200. Torus.prototype.copy = function (id) {
  19201. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  19202. };
  19203. return Torus;
  19204. })(_Primitive);
  19205. Primitives.Torus = Torus;
  19206. var Ground = (function (_super) {
  19207. __extends(Ground, _super);
  19208. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  19209. this.width = width;
  19210. this.height = height;
  19211. this.subdivisions = subdivisions;
  19212. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19213. }
  19214. Ground.prototype._regenerateVertexData = function () {
  19215. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  19216. };
  19217. Ground.prototype.copy = function (id) {
  19218. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  19219. };
  19220. return Ground;
  19221. })(_Primitive);
  19222. Primitives.Ground = Ground;
  19223. var TiledGround = (function (_super) {
  19224. __extends(TiledGround, _super);
  19225. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  19226. this.xmin = xmin;
  19227. this.zmin = zmin;
  19228. this.xmax = xmax;
  19229. this.zmax = zmax;
  19230. this.subdivisions = subdivisions;
  19231. this.precision = precision;
  19232. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19233. }
  19234. TiledGround.prototype._regenerateVertexData = function () {
  19235. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  19236. };
  19237. TiledGround.prototype.copy = function (id) {
  19238. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  19239. };
  19240. return TiledGround;
  19241. })(_Primitive);
  19242. Primitives.TiledGround = TiledGround;
  19243. var Plane = (function (_super) {
  19244. __extends(Plane, _super);
  19245. function Plane(id, scene, size, canBeRegenerated, mesh) {
  19246. this.size = size;
  19247. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19248. }
  19249. Plane.prototype._regenerateVertexData = function () {
  19250. return BABYLON.VertexData.CreatePlane(this.size);
  19251. };
  19252. Plane.prototype.copy = function (id) {
  19253. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19254. };
  19255. return Plane;
  19256. })(_Primitive);
  19257. Primitives.Plane = Plane;
  19258. var TorusKnot = (function (_super) {
  19259. __extends(TorusKnot, _super);
  19260. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  19261. this.radius = radius;
  19262. this.tube = tube;
  19263. this.radialSegments = radialSegments;
  19264. this.tubularSegments = tubularSegments;
  19265. this.p = p;
  19266. this.q = q;
  19267. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19268. }
  19269. TorusKnot.prototype._regenerateVertexData = function () {
  19270. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  19271. };
  19272. TorusKnot.prototype.copy = function (id) {
  19273. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  19274. };
  19275. return TorusKnot;
  19276. })(_Primitive);
  19277. Primitives.TorusKnot = TorusKnot;
  19278. })(Geometry.Primitives || (Geometry.Primitives = {}));
  19279. var Primitives = Geometry.Primitives;
  19280. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  19281. var Geometry = BABYLON.Geometry;
  19282. })(BABYLON || (BABYLON = {}));
  19283. var __extends = this.__extends || function (d, b) {
  19284. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19285. function __() { this.constructor = d; }
  19286. __.prototype = b.prototype;
  19287. d.prototype = new __();
  19288. };
  19289. var BABYLON;
  19290. (function (BABYLON) {
  19291. var Gamepads = (function () {
  19292. function Gamepads(ongamedpadconnected) {
  19293. var _this = this;
  19294. this.babylonGamepads = [];
  19295. this.oneGamepadConnected = false;
  19296. this.isMonitoring = false;
  19297. this.gamepadEventSupported = 'GamepadEvent' in window;
  19298. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  19299. this.buttonADataURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAA9aSURBVHja7FtpbBzneX7m3otcihSpm9Z9UJalxPKhVLZlp6ktNzEaxE0CtAnQAgnSoPWPBi3syuiPwordFi5Qt2haFygCoylSV4Vby6os1I3kOLYrS65kXXQoypJJSaFEUTyXy925+rzfzC6HFFlL1kpAIe7i5czO7H7zPs97ft8MtTAMcSu/dNzirxkCZgiYIWCGgBkCZgi4hV/mDR5fSxAt+0ZiX0ucDxMSTJLK+f83BFSA6TFgK75OclshouKBFbA+xaV4k7Z+fD6sNRlmjYFXQMu4NiUVS/oHe5/ecnHo3MYxd7QthN9UcsdW6FqEPwgDOFbqpAajL2VlTrTULzj4Ow8+s4+nipSxWMoxIUkyrl/pGswFtIR7WzHgDCX77K7vfHNkbOA+AryjYZadb27OIJdzCNZBKmXw4kbk35qPsTEfJbeEkZESentHMdBfGtY142gu1bDvqV/925f4tQJlNCaj4hXX7RHXS0AFuJEAXvfHr/zmk67vPjir0V68aFEe8xtuQ6O1FHlrEXLmHBiaDUtzYBlpNYjrF+GFZfhhCcPeBQy53ehzT+H8QBe6uwfRf7l8xjKsvX/y5X98jl8fThDhJ4i46QQkrS5I6v7oX7/++77vPtLUlFnZtnIRlubvxRxnHbJmE79sxD/SqG0oZk8MFarRqufUkQAFrxcXSkfx0eB+nOggKX2jHYZhvf79r/z4L2IiipO84aYRkASfefnAX695p3P3c9mM/UufuaMVdzRvxVx7A0xaWdOMqVULJ6Z3TZv6KmHo0ztK6CkfxpHe3Th0pAuF0fLbn1u+9cmv3vW77bE3fGoSPi0BVfAvvPEHm9rPv//iooWz5m9Z/wCWZx+Go9UrN48QTD9IGMZ1cJIzTPisRQclPMrhME4W9mDfB2+i+2z/+TXz7/z2E7/85+9OIuGGE6BV3H77zm/d33nx6Ktr18zFg2t+DQude2n1tLJ8tcJ90vDhpG5Am7qTkJAQErywiLOld7G3/d9xvL0Hy1vWPbbtS3//00Q4hDeaAFXintrx1fu7+jp2r13bgofX/gaazbVkJQdLT9P6VqRFDSu2hIgXlBUBLgtCr3cce47/CMePX0Rr08qtzz7+8k8TpfKGtcKq1jPZre7oObyjdWkGd628l7AXwvMCeL7HjO6qrS8S1E5kTE9tfbiur665ccU9EB1EF9Ep0WXesEZIJb9j5/b/XUtzNrt29Rw0og2lchmBVqLo8LSAHlCixbTpddGm8Y7pjkttCCUP+JQy3FiatNuxdvUx9F4ayopO/OL9sQeEN4oA/eHn577oWPbGVes11PsrUBxjDafze1Te1VzouqnK2TgmLQljQqmrnAsT+iaPVb5b2co7EC+QhBgUeM1R1AcrsGp9Jy6+4W8U3fZ8r+e3EnOI2uaAX3l+zgNB4O9rW5/B8tY5WGo9BtOrJ4uMfUl+uj0B8HTmPXj8Pex86xVEnTDBBSE2r78fX9i09RPyZfT2A5ceIMSPwDOH8JH7Kk5+fAHtR0Zh6MZ9e7534Wc3wgO0sXLhD9OpFOa0egjGMhguD8BgTJooMfPbV1h/umz25ondcFP90IzY2iTgrfY9uH31aqSc9CeSEHkBEyITv28M8XMGc2/z0HGCpWCs8BS/9sWrDYOrJuCBZ+vu5sUfXbicia5kYGzUw4DWTwJKbApSjHuTBBjT2H68zg0MD4KlEwabZi0Y7wd85u/3O9/B6sVrPlEXeiF9nMmRxPt6Qf4y/HyIbh3HwkdF1zefGt5fUwK8wP2WAGwh02MFE/5ogYr3Qg/STL0W3d8aB1ppa+Pw0uI2Tz6/134Mg+UoIGZlZ2HMLaJYHkPICr6//RBamvPj/UA4dYKsegGrXqAXMaqNsDT6SreOY5Gu/FptCeBFN+caAphGiKFiGaOjA3AJHoGt6r7GgNbjqjo5yQkBUVHQ8PaJExjiaZ2yue12nO27gCNdHSptvf/xGdw11I2UZSmvCIJgQiJMhoEfeqpNDvUSRvUB5hMX9fUecg0aBi+Hm2uaAz633bmbm1VN8+h07LfKJdkOkQB2fL4BTlsj8No4YLG2putMSjwjp3QNvZdH8YsiExV501isFjU30lpF7D8dVfCA8sFHp7BuWYtaIwiCsCrCSDVhh9IX8k0CoHsoMQ84FrfFAE3zQAK0VaLzO9tK79XKAxSj+aYALt3XLfNipZD1v492YexrE/sP0zBgUIQIoYaflAXbz16CzyY6YKqYl8uheTarRioD7xAxCQHUpv18L1Yud+Iloujtk4zQo9WZcKURqjbHclzKvj0Gvcw8UA6oY2WqonSuGQGb5I+TJgEFEsB4daXzc0eopabcX13W0BXwgAnRZL4Q62s8ppnR/pFz/QjF+tRvxeIsY/cizGwRt83P4czACL8HdA1JUivCNGVogvdkNkgaGDNe4CvXFyJ8n+B5XGLJ1FmJXJ53AzjZKgGbatkKL5c/liNWIPO8uM/4VO2uKCQZjLmBqQAGJ4EmI8NMabDTOuyUobYXmPlCEpiqA1IkYdWSBpjpEDl6wsrF9aAjqHNOPXDyXAGprAknY5B0btOGGk/GlfE1taqofCNuuYNIJ+omOiZ1rpUHtEYWjkpWoP5EWV2sb5isA7aIQTHHxaIniNADui8PIs0Eb6SY/Z0UQc+j+mXYuoM7Vy/Age7zkBUyCZGLhRLSOYcWpfXFA1wPhqup8JNKq5UkKeoqSHxPLSoqnUQtw5ioc60IyE/VkOji8mYE2nZELNgCXLaOkGDFJBg4OzCMDEcxCfAzS1pQX5fHSNDLClLGwmwzls6vQ09hGFJYegdZ1hha2bqIBNelB5Qjog02TzpFNVEquYpMuTSYr/lcQPKPJHoRQ8W1GYO3lDgpO9pPWTEZEQGnuodg5Hyk66Lyd8fKOQQ6gqyWict7GeuWz8HQyWEFw+bB7ksF3Nk2V1nfpZTLQqSLslzXlDmHpsQ1osVoy/Solwf/GpdErpaAQUqjWxL2GWcWaSfAMIis7RBwiuCdtD1OgmNHBJCg7r4uZBnbdjaaq+3YewB+USYicY8juYPnMtloqdCjG3f39eO+3JKIAFadSiiZigBdgdcqItMxsmZbIbvUIKlzzQjoEgLGRjU2KTp8AjRCkzEnAG0mtQh8Ku0oAqok8JzP+Lw0MkB3jpKjKpapaL5WKZxafDdBqoC6O8LtyMAQhoZdzG7MwLU8FUYKPINcl+qimismRj26v2I71I3jDxfdpM41I6CTsmG4X0djKyc8RYu9t0Vl2QJbBJ5xFPiICJIg1hdhR3fs5HnWeldleZXABLA98b7Y5HtjkgwNEtbTN4iFC5oI3I1CTsAbsfVjAizJB3Qbx9HphRp6eqr3TDprSYA0FI/3ntOxbpUNM2OjpEcE6HYEWkhIKw+ICeBxi+T09F1WZU+iJq2n8fRDf4Ymu3XSrcOIgg8H9uOFn31fNUVC0oddZ7B5YxtDwlTgo66SEici2fokwCJjju0hw7J54WypQsB7tSRAza+H+nld30Y+m2b7SS+Qn9PKFl1egRciHIfWpxC8x+7tdA97+3zUcNyWX4Ci/THOoD2x/hmlQTox+3gDjWYeg/4gmF853xjBpUsjaGnJR24fu36FNzX5pmfY7EPStlSLIgb6gwk616QRYk8tS88/l/2PT/loyqbQkEmhPpNGNp1CmvtieQHvONGtL4sdy9Hjp5kkpTWmSzM7L529hErHs0cCpt2qW00BymDV3JXSU8HkAXKIjtNnedxS48m4Mr5cR9YlMrx+XTqNRmbP2ZkMOjvHKir/PNa5pouiitFjH44iZ6YwO5tFAy+eo6SdpOUJyhBQTJR+HT9HYLJaFve0PqQmTQLaVOCdmIRIWE+wrmWTzG8iAugF7qgWjSWkGbYa32EjJQTkGFv5dBZNJKCeHdb77UPXZP1rWhKLZ4Rqjv2Fz86lLMNlpusCY9BnqTNUIyTgrVhhs7rVq2KoW2TSxWlXLOCqWX4svmpzZdEjWvgQcdVWPnu+i4ClUS+HyLIFnsVf/9eBduw8eKYy2D1XMxO8Jg+IB9wl+3s/uAC3qKMpXY88m/ecnUHaSis3Na8Ab1UtaCh3j1y+sm8m9o0J+9Fv9MR4Zhw6DufTWasOebsOs+xZKHJOtvtQtertulrwV+0BtH5yWvyW7CxubsCTX9+KUQZ4ga7qmdGUFmrya8QWHwcxlReMF8Mw4QETrR8oy7tq2ivH5Tvya8n8aXZMGc4An/nRDpy52FfR8b5KCJCImt8YkYF/KDtnegfwz3sPodGajQajCTk9z/4mQ6iphMWv9AA9IeMWdyYdn+gBkVc5amwHWV6lHvVaI2YZzfinN95Ngv/htcT/p31CRNbdV8l8e++xD5HPNeHxhx5Bgf18kTN5T1kvjBfEjGjBJCai4gnjHqAnlvqS8e9NeujEjEul/NokDbai4V/2voafHD1S0evdWLeb8ojMNyly5fS//ffbcD0L33j4K4RX4rtMh/UUGLXmr6BWXN9MEFAhYfzmZ6hcXI+TpISRH8061Ui68gTWGUJP4aU9P8ZrB39S+Xkx1ummPSMkbebnJcxU1jm4D5eGhvB7j32HJcpUJHhxLIfxTZpxwGa8eKrHC51a9Tmp+N5P1RsQ01cJAwEflHw8/+pfYn/HgaQ+n7/a1vd6k+BUS2XvVD401TXhu488gQ0r71QUuLJsrWT8mSYtfkBMm0BAmFhNrgDX4oRqqeaJMw4c6TyIv/qPP0Xf8KUJ6sXuP1XluuEEyGsD5TXKgsqBNQvW4RtbnkDb4ttJQlGt/IQqLMJE7tWqOSBZCSrL6dFSqq3AnzhzDC/tewHt5w4nr3suvgN0+P8o3TeegFe3vYDHtj+xhLt/Q3kkeW5d693YuuHXsWHZPcixW4tCwo+trVU9QEs8G6HFqW5kdBiHTu3H64dfxpGuK8r665Tv7tz2D6e/tP23cT0E1OA5QR2iiIbs1i9u/9qTPPC12CtwlIofjZVvW/BZ3LVsC5bPW4u5DQuxaPay2NpRIuy61IkLA+dw8hdHceDUPpw49z9TXUysvWPXtl3bQ4yQtMJ1a18DAsbvRO/atvM5DXXPPbp9yzP8+GXBXTkngKYBdTWvE5RXdm87+HQEfLh2T57UIAdM95Js9+04LKSDbLzG31+Omxpx9xfxKR6AukkhMP0aKuUHsag5VEzE3fGSddsUVu6KFzIE+H/iJry0mX+bu8VfMwTMEDBDwAwBMwTMEHALv/5XgAEASpR5N6rB30UAAAAASUVORK5CYII=";
  19300. this._callbackGamepadConnected = ongamedpadconnected;
  19301. if (this.gamepadSupportAvailable) {
  19302. if (this.gamepadEventSupported) {
  19303. window.addEventListener('gamepadconnected', function (evt) {
  19304. _this._onGamepadConnected(evt);
  19305. }, false);
  19306. window.addEventListener('gamepaddisconnected', function (evt) {
  19307. _this._onGamepadDisconnected(evt);
  19308. }, false);
  19309. } else {
  19310. this._startMonitoringGamepads();
  19311. }
  19312. if (!this.oneGamepadConnected) {
  19313. this._insertGamepadDOMInstructions();
  19314. }
  19315. } else {
  19316. this._insertGamepadDOMNotSupported();
  19317. }
  19318. }
  19319. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  19320. Gamepads.gamepadDOMInfo = document.createElement("div");
  19321. var buttonAImage = document.createElement("img");
  19322. buttonAImage.src = this.buttonADataURL;
  19323. var spanMessage = document.createElement("span");
  19324. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  19325. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  19326. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  19327. Gamepads.gamepadDOMInfo.style.position = "absolute";
  19328. Gamepads.gamepadDOMInfo.style.width = "100%";
  19329. Gamepads.gamepadDOMInfo.style.height = "48px";
  19330. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  19331. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  19332. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  19333. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  19334. buttonAImage.style.position = "relative";
  19335. buttonAImage.style.bottom = "8px";
  19336. spanMessage.style.position = "relative";
  19337. spanMessage.style.fontSize = "32px";
  19338. spanMessage.style.bottom = "32px";
  19339. spanMessage.style.color = "green";
  19340. document.body.appendChild(Gamepads.gamepadDOMInfo);
  19341. };
  19342. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  19343. Gamepads.gamepadDOMInfo = document.createElement("div");
  19344. var spanMessage = document.createElement("span");
  19345. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  19346. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  19347. Gamepads.gamepadDOMInfo.style.position = "absolute";
  19348. Gamepads.gamepadDOMInfo.style.width = "100%";
  19349. Gamepads.gamepadDOMInfo.style.height = "40px";
  19350. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  19351. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  19352. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  19353. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  19354. spanMessage.style.position = "relative";
  19355. spanMessage.style.fontSize = "32px";
  19356. spanMessage.style.color = "red";
  19357. document.body.appendChild(Gamepads.gamepadDOMInfo);
  19358. };
  19359. Gamepads.prototype.dispose = function () {
  19360. document.body.removeChild(Gamepads.gamepadDOMInfo);
  19361. };
  19362. Gamepads.prototype._onGamepadConnected = function (evt) {
  19363. var newGamepad = this._addNewGamepad(evt.gamepad);
  19364. if (this._callbackGamepadConnected)
  19365. this._callbackGamepadConnected(newGamepad);
  19366. this._startMonitoringGamepads();
  19367. };
  19368. Gamepads.prototype._addNewGamepad = function (gamepad) {
  19369. if (!this.oneGamepadConnected) {
  19370. this.oneGamepadConnected = true;
  19371. if (Gamepads.gamepadDOMInfo) {
  19372. document.body.removeChild(Gamepads.gamepadDOMInfo);
  19373. Gamepads.gamepadDOMInfo = null;
  19374. }
  19375. }
  19376. var newGamepad;
  19377. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  19378. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  19379. } else {
  19380. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  19381. }
  19382. this.babylonGamepads.push(newGamepad);
  19383. return newGamepad;
  19384. };
  19385. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  19386. for (var i in this.babylonGamepads) {
  19387. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  19388. this.babylonGamepads.splice(i, 1);
  19389. break;
  19390. }
  19391. }
  19392. if (this.babylonGamepads.length == 0) {
  19393. this._stopMonitoringGamepads();
  19394. }
  19395. };
  19396. Gamepads.prototype._startMonitoringGamepads = function () {
  19397. if (!this.isMonitoring) {
  19398. this.isMonitoring = true;
  19399. this._checkGamepadsStatus();
  19400. }
  19401. };
  19402. Gamepads.prototype._stopMonitoringGamepads = function () {
  19403. this.isMonitoring = false;
  19404. };
  19405. Gamepads.prototype._checkGamepadsStatus = function () {
  19406. var _this = this;
  19407. this._updateGamepadObjects();
  19408. for (var i in this.babylonGamepads) {
  19409. this.babylonGamepads[i].update();
  19410. }
  19411. if (this.isMonitoring) {
  19412. if (window.requestAnimationFrame) {
  19413. window.requestAnimationFrame(function () {
  19414. _this._checkGamepadsStatus();
  19415. });
  19416. } else if (window.mozRequestAnimationFrame) {
  19417. window.mozRequestAnimationFrame(function () {
  19418. _this._checkGamepadsStatus();
  19419. });
  19420. } else if (window.webkitRequestAnimationFrame) {
  19421. window.webkitRequestAnimationFrame(function () {
  19422. _this._checkGamepadsStatus();
  19423. });
  19424. }
  19425. }
  19426. };
  19427. Gamepads.prototype._updateGamepadObjects = function () {
  19428. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  19429. for (var i = 0; i < gamepads.length; i++) {
  19430. if (gamepads[i]) {
  19431. if (!(gamepads[i].index in this.babylonGamepads)) {
  19432. var newGamepad = this._addNewGamepad(gamepads[i]);
  19433. if (this._callbackGamepadConnected) {
  19434. this._callbackGamepadConnected(newGamepad);
  19435. }
  19436. } else {
  19437. this.babylonGamepads[i].browserGamepad = gamepads[i];
  19438. }
  19439. }
  19440. }
  19441. };
  19442. return Gamepads;
  19443. })();
  19444. BABYLON.Gamepads = Gamepads;
  19445. var StickValues = (function () {
  19446. function StickValues(x, y) {
  19447. this.x = x;
  19448. this.y = y;
  19449. }
  19450. return StickValues;
  19451. })();
  19452. BABYLON.StickValues = StickValues;
  19453. var Gamepad = (function () {
  19454. function Gamepad(id, index, browserGamepad) {
  19455. this.id = id;
  19456. this.index = index;
  19457. this.browserGamepad = browserGamepad;
  19458. if (this.browserGamepad.axes.length >= 2) {
  19459. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  19460. }
  19461. if (this.browserGamepad.axes.length >= 4) {
  19462. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  19463. }
  19464. }
  19465. Gamepad.prototype.onleftstickchanged = function (callback) {
  19466. this._onleftstickchanged = callback;
  19467. };
  19468. Gamepad.prototype.onrightstickchanged = function (callback) {
  19469. this._onrightstickchanged = callback;
  19470. };
  19471. Object.defineProperty(Gamepad.prototype, "leftStick", {
  19472. get: function () {
  19473. return this._leftStick;
  19474. },
  19475. set: function (newValues) {
  19476. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  19477. this._onleftstickchanged(newValues);
  19478. }
  19479. this._leftStick = newValues;
  19480. },
  19481. enumerable: true,
  19482. configurable: true
  19483. });
  19484. Object.defineProperty(Gamepad.prototype, "rightStick", {
  19485. get: function () {
  19486. return this._rightStick;
  19487. },
  19488. set: function (newValues) {
  19489. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  19490. this._onrightstickchanged(newValues);
  19491. }
  19492. this._rightStick = newValues;
  19493. },
  19494. enumerable: true,
  19495. configurable: true
  19496. });
  19497. Gamepad.prototype.update = function () {
  19498. if (this._leftStick) {
  19499. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  19500. }
  19501. if (this._rightStick) {
  19502. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  19503. }
  19504. };
  19505. return Gamepad;
  19506. })();
  19507. BABYLON.Gamepad = Gamepad;
  19508. var GenericPad = (function (_super) {
  19509. __extends(GenericPad, _super);
  19510. function GenericPad(id, index, gamepad) {
  19511. _super.call(this, id, index, gamepad);
  19512. this.id = id;
  19513. this.index = index;
  19514. this.gamepad = gamepad;
  19515. this._buttons = new Array(gamepad.buttons.length);
  19516. }
  19517. GenericPad.prototype.onbuttondown = function (callback) {
  19518. this._onbuttondown = callback;
  19519. };
  19520. GenericPad.prototype.onbuttonup = function (callback) {
  19521. this._onbuttonup = callback;
  19522. };
  19523. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  19524. if (newValue !== currentValue) {
  19525. if (this._onbuttondown && newValue === 1) {
  19526. this._onbuttondown(buttonIndex);
  19527. }
  19528. if (this._onbuttonup && newValue === 0) {
  19529. this._onbuttonup(buttonIndex);
  19530. }
  19531. }
  19532. return newValue;
  19533. };
  19534. GenericPad.prototype.update = function () {
  19535. _super.prototype.update.call(this);
  19536. for (var index = 0; index < this._buttons.length; index++) {
  19537. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  19538. }
  19539. };
  19540. return GenericPad;
  19541. })(Gamepad);
  19542. BABYLON.GenericPad = GenericPad;
  19543. (function (Xbox360Button) {
  19544. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  19545. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  19546. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  19547. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  19548. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  19549. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  19550. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  19551. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  19552. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  19553. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  19554. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  19555. var Xbox360Button = BABYLON.Xbox360Button;
  19556. (function (Xbox360Dpad) {
  19557. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  19558. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  19559. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  19560. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  19561. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  19562. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  19563. var Xbox360Pad = (function (_super) {
  19564. __extends(Xbox360Pad, _super);
  19565. function Xbox360Pad() {
  19566. _super.apply(this, arguments);
  19567. this._leftTrigger = 0;
  19568. this._rightTrigger = 0;
  19569. this._buttonA = 0;
  19570. this._buttonB = 0;
  19571. this._buttonX = 0;
  19572. this._buttonY = 0;
  19573. this._buttonBack = 0;
  19574. this._buttonStart = 0;
  19575. this._buttonLB = 0;
  19576. this._buttonRB = 0;
  19577. this._buttonLeftStick = 0;
  19578. this._buttonRightStick = 0;
  19579. this._dPadUp = 0;
  19580. this._dPadDown = 0;
  19581. this._dPadLeft = 0;
  19582. this._dPadRight = 0;
  19583. }
  19584. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  19585. this._onlefttriggerchanged = callback;
  19586. };
  19587. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  19588. this._onrighttriggerchanged = callback;
  19589. };
  19590. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  19591. get: function () {
  19592. return this._leftTrigger;
  19593. },
  19594. set: function (newValue) {
  19595. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  19596. this._onlefttriggerchanged(newValue);
  19597. }
  19598. this._leftTrigger = newValue;
  19599. },
  19600. enumerable: true,
  19601. configurable: true
  19602. });
  19603. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  19604. get: function () {
  19605. return this._rightTrigger;
  19606. },
  19607. set: function (newValue) {
  19608. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  19609. this._onrighttriggerchanged(newValue);
  19610. }
  19611. this._rightTrigger = newValue;
  19612. },
  19613. enumerable: true,
  19614. configurable: true
  19615. });
  19616. Xbox360Pad.prototype.onbuttondown = function (callback) {
  19617. this._onbuttondown = callback;
  19618. };
  19619. Xbox360Pad.prototype.onbuttonup = function (callback) {
  19620. this._onbuttonup = callback;
  19621. };
  19622. Xbox360Pad.prototype.ondpaddown = function (callback) {
  19623. this._ondpaddown = callback;
  19624. };
  19625. Xbox360Pad.prototype.ondpadup = function (callback) {
  19626. this._ondpadup = callback;
  19627. };
  19628. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  19629. if (newValue !== currentValue) {
  19630. if (this._onbuttondown && newValue === 1) {
  19631. this._onbuttondown(buttonType);
  19632. }
  19633. if (this._onbuttonup && newValue === 0) {
  19634. this._onbuttonup(buttonType);
  19635. }
  19636. }
  19637. return newValue;
  19638. };
  19639. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  19640. if (newValue !== currentValue) {
  19641. if (this._ondpaddown && newValue === 1) {
  19642. this._ondpaddown(buttonType);
  19643. }
  19644. if (this._ondpadup && newValue === 0) {
  19645. this._ondpadup(buttonType);
  19646. }
  19647. }
  19648. return newValue;
  19649. };
  19650. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  19651. get: function () {
  19652. return this._buttonA;
  19653. },
  19654. set: function (value) {
  19655. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  19656. },
  19657. enumerable: true,
  19658. configurable: true
  19659. });
  19660. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  19661. get: function () {
  19662. return this._buttonB;
  19663. },
  19664. set: function (value) {
  19665. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  19666. },
  19667. enumerable: true,
  19668. configurable: true
  19669. });
  19670. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  19671. get: function () {
  19672. return this._buttonX;
  19673. },
  19674. set: function (value) {
  19675. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  19676. },
  19677. enumerable: true,
  19678. configurable: true
  19679. });
  19680. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  19681. get: function () {
  19682. return this._buttonY;
  19683. },
  19684. set: function (value) {
  19685. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  19686. },
  19687. enumerable: true,
  19688. configurable: true
  19689. });
  19690. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  19691. get: function () {
  19692. return this._buttonStart;
  19693. },
  19694. set: function (value) {
  19695. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  19696. },
  19697. enumerable: true,
  19698. configurable: true
  19699. });
  19700. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  19701. get: function () {
  19702. return this._buttonBack;
  19703. },
  19704. set: function (value) {
  19705. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  19706. },
  19707. enumerable: true,
  19708. configurable: true
  19709. });
  19710. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  19711. get: function () {
  19712. return this._buttonLB;
  19713. },
  19714. set: function (value) {
  19715. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  19716. },
  19717. enumerable: true,
  19718. configurable: true
  19719. });
  19720. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  19721. get: function () {
  19722. return this._buttonRB;
  19723. },
  19724. set: function (value) {
  19725. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  19726. },
  19727. enumerable: true,
  19728. configurable: true
  19729. });
  19730. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  19731. get: function () {
  19732. return this._buttonLeftStick;
  19733. },
  19734. set: function (value) {
  19735. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  19736. },
  19737. enumerable: true,
  19738. configurable: true
  19739. });
  19740. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  19741. get: function () {
  19742. return this._buttonRightStick;
  19743. },
  19744. set: function (value) {
  19745. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  19746. },
  19747. enumerable: true,
  19748. configurable: true
  19749. });
  19750. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  19751. get: function () {
  19752. return this._dPadUp;
  19753. },
  19754. set: function (value) {
  19755. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  19756. },
  19757. enumerable: true,
  19758. configurable: true
  19759. });
  19760. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  19761. get: function () {
  19762. return this._dPadDown;
  19763. },
  19764. set: function (value) {
  19765. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  19766. },
  19767. enumerable: true,
  19768. configurable: true
  19769. });
  19770. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  19771. get: function () {
  19772. return this._dPadLeft;
  19773. },
  19774. set: function (value) {
  19775. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  19776. },
  19777. enumerable: true,
  19778. configurable: true
  19779. });
  19780. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  19781. get: function () {
  19782. return this._dPadRight;
  19783. },
  19784. set: function (value) {
  19785. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  19786. },
  19787. enumerable: true,
  19788. configurable: true
  19789. });
  19790. Xbox360Pad.prototype.update = function () {
  19791. _super.prototype.update.call(this);
  19792. this.buttonA = this.browserGamepad.buttons[0].value;
  19793. this.buttonB = this.browserGamepad.buttons[1].value;
  19794. this.buttonX = this.browserGamepad.buttons[2].value;
  19795. this.buttonY = this.browserGamepad.buttons[3].value;
  19796. this.buttonLB = this.browserGamepad.buttons[4].value;
  19797. this.buttonRB = this.browserGamepad.buttons[5].value;
  19798. this.leftTrigger = this.browserGamepad.buttons[6].value;
  19799. this.rightTrigger = this.browserGamepad.buttons[7].value;
  19800. this.buttonBack = this.browserGamepad.buttons[8].value;
  19801. this.buttonStart = this.browserGamepad.buttons[9].value;
  19802. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  19803. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  19804. this.dPadUp = this.browserGamepad.buttons[12].value;
  19805. this.dPadDown = this.browserGamepad.buttons[13].value;
  19806. this.dPadLeft = this.browserGamepad.buttons[14].value;
  19807. this.dPadRight = this.browserGamepad.buttons[15].value;
  19808. };
  19809. return Xbox360Pad;
  19810. })(Gamepad);
  19811. BABYLON.Xbox360Pad = Xbox360Pad;
  19812. })(BABYLON || (BABYLON = {}));
  19813. var __extends = this.__extends || function (d, b) {
  19814. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19815. function __() { this.constructor = d; }
  19816. __.prototype = b.prototype;
  19817. d.prototype = new __();
  19818. };
  19819. var BABYLON;
  19820. (function (BABYLON) {
  19821. var GamepadCamera = (function (_super) {
  19822. __extends(GamepadCamera, _super);
  19823. function GamepadCamera(name, position, scene) {
  19824. var _this = this;
  19825. _super.call(this, name, position, scene);
  19826. this.angularSensibility = 200;
  19827. this.moveSensibility = 75;
  19828. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  19829. _this._onNewGameConnected(gamepad);
  19830. });
  19831. }
  19832. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  19833. if (gamepad.index === 0) {
  19834. this._gamepad = gamepad;
  19835. }
  19836. };
  19837. GamepadCamera.prototype._checkInputs = function () {
  19838. if (!this._gamepad) {
  19839. return;
  19840. }
  19841. var LSValues = this._gamepad.leftStick;
  19842. var normalizedLX = LSValues.x / this.moveSensibility;
  19843. var normalizedLY = LSValues.y / this.moveSensibility;
  19844. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  19845. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  19846. var RSValues = this._gamepad.rightStick;
  19847. var normalizedRX = RSValues.x / this.angularSensibility;
  19848. var normalizedRY = RSValues.y / this.angularSensibility;
  19849. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  19850. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  19851. ;
  19852. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19853. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  19854. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19855. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  19856. };
  19857. GamepadCamera.prototype.dispose = function () {
  19858. this._gamepads.dispose();
  19859. _super.prototype.dispose.call(this);
  19860. };
  19861. return GamepadCamera;
  19862. })(BABYLON.FreeCamera);
  19863. BABYLON.GamepadCamera = GamepadCamera;
  19864. })(BABYLON || (BABYLON = {}));
  19865. var __extends = this.__extends || function (d, b) {
  19866. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19867. function __() { this.constructor = d; }
  19868. __.prototype = b.prototype;
  19869. d.prototype = new __();
  19870. };
  19871. var BABYLON;
  19872. (function (BABYLON) {
  19873. var LinesMesh = (function (_super) {
  19874. __extends(LinesMesh, _super);
  19875. function LinesMesh(name, scene, updatable) {
  19876. if (typeof updatable === "undefined") { updatable = false; }
  19877. _super.call(this, name, scene);
  19878. this.color = new BABYLON.Color3(1, 1, 1);
  19879. this.alpha = 1;
  19880. this._indices = new Array();
  19881. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  19882. attributes: ["position"],
  19883. uniforms: ["worldViewProjection", "color"],
  19884. needAlphaBlending: true
  19885. });
  19886. }
  19887. Object.defineProperty(LinesMesh.prototype, "material", {
  19888. get: function () {
  19889. return this._colorShader;
  19890. },
  19891. enumerable: true,
  19892. configurable: true
  19893. });
  19894. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  19895. get: function () {
  19896. return false;
  19897. },
  19898. enumerable: true,
  19899. configurable: true
  19900. });
  19901. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  19902. get: function () {
  19903. return false;
  19904. },
  19905. enumerable: true,
  19906. configurable: true
  19907. });
  19908. LinesMesh.prototype._bind = function (subMesh, effect, wireframe) {
  19909. var engine = this.getScene().getEngine();
  19910. var indexToBind = this._geometry.getIndexBuffer();
  19911. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  19912. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  19913. };
  19914. LinesMesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  19915. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19916. return;
  19917. }
  19918. var engine = this.getScene().getEngine();
  19919. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  19920. };
  19921. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  19922. return null;
  19923. };
  19924. LinesMesh.prototype.dispose = function (doNotRecurse) {
  19925. this._colorShader.dispose();
  19926. _super.prototype.dispose.call(this, doNotRecurse);
  19927. };
  19928. return LinesMesh;
  19929. })(BABYLON.Mesh);
  19930. BABYLON.LinesMesh = LinesMesh;
  19931. })(BABYLON || (BABYLON = {}));
  19932. var BABYLON;
  19933. (function (BABYLON) {
  19934. var OutlineRenderer = (function () {
  19935. function OutlineRenderer(scene) {
  19936. this._scene = scene;
  19937. }
  19938. OutlineRenderer.prototype.render = function (subMesh, batch) {
  19939. var scene = this._scene;
  19940. var engine = this._scene.getEngine();
  19941. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  19942. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  19943. return;
  19944. }
  19945. var mesh = subMesh.getRenderingMesh();
  19946. var material = subMesh.getMaterial();
  19947. engine.enableEffect(this._effect);
  19948. this._effect.setFloat("offset", mesh.outlineWidth);
  19949. this._effect.setColor3("color", mesh.outlineColor);
  19950. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19951. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  19952. if (useBones) {
  19953. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19954. }
  19955. mesh._bind(subMesh, this._effect, false);
  19956. if (material && material.needAlphaTesting()) {
  19957. var alphaTexture = material.getAlphaTestTexture();
  19958. this._effect.setTexture("diffuseSampler", alphaTexture);
  19959. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  19960. }
  19961. if (hardwareInstancedRendering) {
  19962. mesh._renderWithInstances(subMesh, false, batch, this._effect, engine);
  19963. } else {
  19964. if (batch.renderSelf[subMesh._id]) {
  19965. this._effect.setMatrix("world", mesh.getWorldMatrix());
  19966. mesh._draw(subMesh, true);
  19967. }
  19968. if (batch.visibleInstances[subMesh._id]) {
  19969. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19970. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19971. this._effect.setMatrix("world", instance.getWorldMatrix());
  19972. mesh._draw(subMesh, true);
  19973. }
  19974. }
  19975. }
  19976. };
  19977. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  19978. var defines = [];
  19979. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  19980. var mesh = subMesh.getMesh();
  19981. var material = subMesh.getMaterial();
  19982. if (material && material.needAlphaTesting()) {
  19983. defines.push("#define ALPHATEST");
  19984. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19985. attribs.push(BABYLON.VertexBuffer.UVKind);
  19986. defines.push("#define UV1");
  19987. }
  19988. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19989. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19990. defines.push("#define UV2");
  19991. }
  19992. }
  19993. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19994. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19995. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19996. defines.push("#define BONES");
  19997. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  19998. }
  19999. if (useInstances) {
  20000. defines.push("#define INSTANCES");
  20001. attribs.push("world0");
  20002. attribs.push("world1");
  20003. attribs.push("world2");
  20004. attribs.push("world3");
  20005. }
  20006. var join = defines.join("\n");
  20007. if (this._cachedDefines != join) {
  20008. this._cachedDefines = join;
  20009. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  20010. }
  20011. return this._effect.isReady();
  20012. };
  20013. return OutlineRenderer;
  20014. })();
  20015. BABYLON.OutlineRenderer = OutlineRenderer;
  20016. })(BABYLON || (BABYLON = {}));
  20017. var BABYLON;
  20018. (function (BABYLON) {
  20019. var MeshAssetTask = (function () {
  20020. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  20021. this.name = name;
  20022. this.meshesNames = meshesNames;
  20023. this.rootUrl = rootUrl;
  20024. this.sceneFilename = sceneFilename;
  20025. this.isCompleted = false;
  20026. }
  20027. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20028. var _this = this;
  20029. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  20030. _this.loadedMeshes = meshes;
  20031. _this.loadedParticleSystems = particleSystems;
  20032. _this.loadedSkeletons = skeletons;
  20033. _this.isCompleted = true;
  20034. if (_this.onSuccess) {
  20035. _this.onSuccess(_this);
  20036. }
  20037. onSuccess();
  20038. }, null, function () {
  20039. if (_this.onError) {
  20040. _this.onError(_this);
  20041. }
  20042. onError();
  20043. });
  20044. };
  20045. return MeshAssetTask;
  20046. })();
  20047. BABYLON.MeshAssetTask = MeshAssetTask;
  20048. var TextFileAssetTask = (function () {
  20049. function TextFileAssetTask(name, url) {
  20050. this.name = name;
  20051. this.url = url;
  20052. this.isCompleted = false;
  20053. }
  20054. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20055. var _this = this;
  20056. BABYLON.Tools.LoadFile(this.url, function (data) {
  20057. _this.text = data;
  20058. _this.isCompleted = true;
  20059. if (_this.onSuccess) {
  20060. _this.onSuccess(_this);
  20061. }
  20062. onSuccess();
  20063. }, null, scene.database, false, function () {
  20064. if (_this.onError) {
  20065. _this.onError(_this);
  20066. }
  20067. onError();
  20068. });
  20069. };
  20070. return TextFileAssetTask;
  20071. })();
  20072. BABYLON.TextFileAssetTask = TextFileAssetTask;
  20073. var BinaryFileAssetTask = (function () {
  20074. function BinaryFileAssetTask(name, url) {
  20075. this.name = name;
  20076. this.url = url;
  20077. this.isCompleted = false;
  20078. }
  20079. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20080. var _this = this;
  20081. BABYLON.Tools.LoadFile(this.url, function (data) {
  20082. _this.data = data;
  20083. _this.isCompleted = true;
  20084. if (_this.onSuccess) {
  20085. _this.onSuccess(_this);
  20086. }
  20087. onSuccess();
  20088. }, null, scene.database, true, function () {
  20089. if (_this.onError) {
  20090. _this.onError(_this);
  20091. }
  20092. onError();
  20093. });
  20094. };
  20095. return BinaryFileAssetTask;
  20096. })();
  20097. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  20098. var ImageAssetTask = (function () {
  20099. function ImageAssetTask(name, url) {
  20100. this.name = name;
  20101. this.url = url;
  20102. this.isCompleted = false;
  20103. }
  20104. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20105. var _this = this;
  20106. var img = new Image();
  20107. img.onload = function () {
  20108. _this.image = img;
  20109. _this.isCompleted = true;
  20110. if (_this.onSuccess) {
  20111. _this.onSuccess(_this);
  20112. }
  20113. onSuccess();
  20114. };
  20115. img.onerror = function () {
  20116. if (_this.onError) {
  20117. _this.onError(_this);
  20118. }
  20119. onError();
  20120. };
  20121. img.src = this.url;
  20122. };
  20123. return ImageAssetTask;
  20124. })();
  20125. BABYLON.ImageAssetTask = ImageAssetTask;
  20126. var AssetsManager = (function () {
  20127. function AssetsManager(scene) {
  20128. this._tasks = new Array();
  20129. this._waitingTasksCount = 0;
  20130. this.useDefaultLoadingScreen = true;
  20131. this._scene = scene;
  20132. }
  20133. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  20134. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  20135. this._tasks.push(task);
  20136. return task;
  20137. };
  20138. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  20139. var task = new TextFileAssetTask(taskName, url);
  20140. this._tasks.push(task);
  20141. return task;
  20142. };
  20143. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  20144. var task = new BinaryFileAssetTask(taskName, url);
  20145. this._tasks.push(task);
  20146. return task;
  20147. };
  20148. AssetsManager.prototype.addImageTask = function (taskName, url) {
  20149. var task = new ImageAssetTask(taskName, url);
  20150. this._tasks.push(task);
  20151. return task;
  20152. };
  20153. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  20154. this._waitingTasksCount--;
  20155. if (this._waitingTasksCount === 0) {
  20156. if (this.onFinish) {
  20157. this.onFinish(this._tasks);
  20158. }
  20159. this._scene.getEngine().hideLoadingUI();
  20160. }
  20161. };
  20162. AssetsManager.prototype._runTask = function (task) {
  20163. var _this = this;
  20164. task.run(this._scene, function () {
  20165. if (_this.onTaskSuccess) {
  20166. _this.onTaskSuccess(task);
  20167. }
  20168. _this._decreaseWaitingTasksCount();
  20169. }, function () {
  20170. if (_this.onTaskError) {
  20171. _this.onTaskError(task);
  20172. }
  20173. _this._decreaseWaitingTasksCount();
  20174. });
  20175. };
  20176. AssetsManager.prototype.reset = function () {
  20177. this._tasks = new Array();
  20178. return this;
  20179. };
  20180. AssetsManager.prototype.load = function () {
  20181. this._waitingTasksCount = this._tasks.length;
  20182. if (this._waitingTasksCount === 0) {
  20183. if (this.onFinish) {
  20184. this.onFinish(this._tasks);
  20185. }
  20186. return this;
  20187. }
  20188. if (this.useDefaultLoadingScreen) {
  20189. this._scene.getEngine().displayLoadingUI();
  20190. }
  20191. for (var index = 0; index < this._tasks.length; index++) {
  20192. var task = this._tasks[index];
  20193. this._runTask(task);
  20194. }
  20195. return this;
  20196. };
  20197. return AssetsManager;
  20198. })();
  20199. BABYLON.AssetsManager = AssetsManager;
  20200. })(BABYLON || (BABYLON = {}));
  20201. var __extends = this.__extends || function (d, b) {
  20202. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20203. function __() { this.constructor = d; }
  20204. __.prototype = b.prototype;
  20205. d.prototype = new __();
  20206. };
  20207. var BABYLON;
  20208. (function (BABYLON) {
  20209. var VRDeviceOrientationCamera = (function (_super) {
  20210. __extends(VRDeviceOrientationCamera, _super);
  20211. function VRDeviceOrientationCamera(name, position, scene) {
  20212. _super.call(this, name, position, scene);
  20213. this._alpha = 0;
  20214. this._beta = 0;
  20215. this._gamma = 0;
  20216. }
  20217. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  20218. this._alpha = +evt.alpha | 0;
  20219. this._beta = +evt.beta | 0;
  20220. this._gamma = +evt.gamma | 0;
  20221. if (this._gamma < 0) {
  20222. this._gamma = 90 + this._gamma;
  20223. } else {
  20224. this._gamma = 270 - this._gamma;
  20225. }
  20226. this.rotation.x = this._gamma / 180.0 * Math.PI;
  20227. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  20228. this.rotation.z = this._beta / 180.0 * Math.PI;
  20229. };
  20230. return VRDeviceOrientationCamera;
  20231. })(BABYLON.OculusCamera);
  20232. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  20233. })(BABYLON || (BABYLON = {}));
  20234. var __extends = this.__extends || function (d, b) {
  20235. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20236. function __() { this.constructor = d; }
  20237. __.prototype = b.prototype;
  20238. d.prototype = new __();
  20239. };
  20240. var BABYLON;
  20241. (function (BABYLON) {
  20242. var WebVRCamera = (function (_super) {
  20243. __extends(WebVRCamera, _super);
  20244. function WebVRCamera(name, position, scene) {
  20245. _super.call(this, name, position, scene);
  20246. this._hmdDevice = null;
  20247. this._sensorDevice = null;
  20248. this._cacheState = null;
  20249. this._cacheQuaternion = new BABYLON.Quaternion();
  20250. this._cacheRotation = BABYLON.Vector3.Zero();
  20251. this._vrEnabled = false;
  20252. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  20253. }
  20254. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  20255. var size = devices.length;
  20256. var i = 0;
  20257. this._sensorDevice = null;
  20258. this._hmdDevice = null;
  20259. while (i > 0 && this._hmdDevice === null) {
  20260. if (devices[i] instanceof HMDVRDevice) {
  20261. this._hmdDevice = devices[i];
  20262. }
  20263. i++;
  20264. }
  20265. i = 0;
  20266. while (i > 0 && this._sensorDevice === null) {
  20267. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  20268. this._sensorDevice = devices[i];
  20269. }
  20270. i++;
  20271. }
  20272. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  20273. };
  20274. WebVRCamera.prototype._update = function () {
  20275. if (this._vrEnabled) {
  20276. this._cacheState = this._sensorDevice.getState();
  20277. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  20278. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  20279. this.rotation.x = -this._cacheRotation.z;
  20280. this.rotation.y = -this._cacheRotation.y;
  20281. this.rotation.z = this._cacheRotation.x;
  20282. }
  20283. _super.prototype._update.call(this);
  20284. };
  20285. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  20286. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20287. if (navigator.getVRDevices) {
  20288. navigator.getVRDevices().then(this._getWebVRDevices);
  20289. } else if (navigator.mozGetVRDevices) {
  20290. navigator.mozGetVRDevices(this._getWebVRDevices);
  20291. }
  20292. };
  20293. WebVRCamera.prototype.detachControl = function (element) {
  20294. _super.prototype.detachControl.call(this, element);
  20295. this._vrEnabled = false;
  20296. };
  20297. return WebVRCamera;
  20298. })(BABYLON.OculusCamera);
  20299. BABYLON.WebVRCamera = WebVRCamera;
  20300. })(BABYLON || (BABYLON = {}));