babylon.1.14-debug.js 1.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087
  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.subtractInPlace = function (otherVector) {
  238. this.x -= otherVector.x;
  239. this.y -= otherVector.y;
  240. };
  241. Vector2.prototype.multiplyInPlace = function (otherVector) {
  242. this.x *= otherVector.x;
  243. this.y *= otherVector.y;
  244. };
  245. Vector2.prototype.multiply = function (otherVector) {
  246. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  247. };
  248. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  249. result.x = this.x * otherVector.x;
  250. result.y = this.y * otherVector.y;
  251. };
  252. Vector2.prototype.multiplyByFloats = function (x, y) {
  253. return new Vector2(this.x * x, this.y * y);
  254. };
  255. Vector2.prototype.divide = function (otherVector) {
  256. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  257. };
  258. Vector2.prototype.divideToRef = function (otherVector, result) {
  259. result.x = this.x / otherVector.x;
  260. result.y = this.y / otherVector.y;
  261. };
  262. Vector2.prototype.negate = function () {
  263. return new Vector2(-this.x, -this.y);
  264. };
  265. Vector2.prototype.scaleInPlace = function (scale) {
  266. this.x *= scale;
  267. this.y *= scale;
  268. return this;
  269. };
  270. Vector2.prototype.scale = function (scale) {
  271. return new Vector2(this.x * scale, this.y * scale);
  272. };
  273. Vector2.prototype.equals = function (otherVector) {
  274. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  275. };
  276. Vector2.prototype.length = function () {
  277. return Math.sqrt(this.x * this.x + this.y * this.y);
  278. };
  279. Vector2.prototype.lengthSquared = function () {
  280. return (this.x * this.x + this.y * this.y);
  281. };
  282. Vector2.prototype.normalize = function () {
  283. var len = this.length();
  284. if (len === 0)
  285. return this;
  286. var num = 1.0 / len;
  287. this.x *= num;
  288. this.y *= num;
  289. return this;
  290. };
  291. Vector2.prototype.clone = function () {
  292. return new Vector2(this.x, this.y);
  293. };
  294. Vector2.Zero = function () {
  295. return new Vector2(0, 0);
  296. };
  297. Vector2.FromArray = function (array, offset) {
  298. if (!offset) {
  299. offset = 0;
  300. }
  301. return new Vector2(array[offset], array[offset + 1]);
  302. };
  303. Vector2.FromArrayToRef = function (array, offset, result) {
  304. result.x = array[offset];
  305. result.y = array[offset + 1];
  306. };
  307. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  308. var squared = amount * amount;
  309. var cubed = amount * squared;
  310. 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));
  311. 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));
  312. return new Vector2(x, y);
  313. };
  314. Vector2.Clamp = function (value, min, max) {
  315. var x = value.x;
  316. x = (x > max.x) ? max.x : x;
  317. x = (x < min.x) ? min.x : x;
  318. var y = value.y;
  319. y = (y > max.y) ? max.y : y;
  320. y = (y < min.y) ? min.y : y;
  321. return new Vector2(x, y);
  322. };
  323. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  324. var squared = amount * amount;
  325. var cubed = amount * squared;
  326. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  327. var part2 = (-2.0 * cubed) + (3.0 * squared);
  328. var part3 = (cubed - (2.0 * squared)) + amount;
  329. var part4 = cubed - squared;
  330. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  331. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  332. return new Vector2(x, y);
  333. };
  334. Vector2.Lerp = function (start, end, amount) {
  335. var x = start.x + ((end.x - start.x) * amount);
  336. var y = start.y + ((end.y - start.y) * amount);
  337. return new Vector2(x, y);
  338. };
  339. Vector2.Dot = function (left, right) {
  340. return left.x * right.x + left.y * right.y;
  341. };
  342. Vector2.Normalize = function (vector) {
  343. var newVector = vector.clone();
  344. newVector.normalize();
  345. return newVector;
  346. };
  347. Vector2.Minimize = function (left, right) {
  348. var x = (left.x < right.x) ? left.x : right.x;
  349. var y = (left.y < right.y) ? left.y : right.y;
  350. return new Vector2(x, y);
  351. };
  352. Vector2.Maximize = function (left, right) {
  353. var x = (left.x > right.x) ? left.x : right.x;
  354. var y = (left.y > right.y) ? left.y : right.y;
  355. return new Vector2(x, y);
  356. };
  357. Vector2.Transform = function (vector, transformation) {
  358. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  359. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  360. return new Vector2(x, y);
  361. };
  362. Vector2.Distance = function (value1, value2) {
  363. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  364. };
  365. Vector2.DistanceSquared = function (value1, value2) {
  366. var x = value1.x - value2.x;
  367. var y = value1.y - value2.y;
  368. return (x * x) + (y * y);
  369. };
  370. return Vector2;
  371. })();
  372. BABYLON.Vector2 = Vector2;
  373. var Vector3 = (function () {
  374. function Vector3(x, y, z) {
  375. this.x = x;
  376. this.y = y;
  377. this.z = z;
  378. }
  379. Vector3.prototype.toString = function () {
  380. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  381. };
  382. Vector3.prototype.asArray = function () {
  383. var result = [];
  384. this.toArray(result, 0);
  385. return result;
  386. };
  387. Vector3.prototype.toArray = function (array, index) {
  388. if (index === undefined) {
  389. index = 0;
  390. }
  391. array[index] = this.x;
  392. array[index + 1] = this.y;
  393. array[index + 2] = this.z;
  394. };
  395. Vector3.prototype.addInPlace = function (otherVector) {
  396. this.x += otherVector.x;
  397. this.y += otherVector.y;
  398. this.z += otherVector.z;
  399. };
  400. Vector3.prototype.add = function (otherVector) {
  401. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  402. };
  403. Vector3.prototype.addToRef = function (otherVector, result) {
  404. result.x = this.x + otherVector.x;
  405. result.y = this.y + otherVector.y;
  406. result.z = this.z + otherVector.z;
  407. };
  408. Vector3.prototype.subtractInPlace = function (otherVector) {
  409. this.x -= otherVector.x;
  410. this.y -= otherVector.y;
  411. this.z -= otherVector.z;
  412. };
  413. Vector3.prototype.subtract = function (otherVector) {
  414. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  415. };
  416. Vector3.prototype.subtractToRef = function (otherVector, result) {
  417. result.x = this.x - otherVector.x;
  418. result.y = this.y - otherVector.y;
  419. result.z = this.z - otherVector.z;
  420. };
  421. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  422. return new Vector3(this.x - x, this.y - y, this.z - z);
  423. };
  424. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  425. result.x = this.x - x;
  426. result.y = this.y - y;
  427. result.z = this.z - z;
  428. };
  429. Vector3.prototype.negate = function () {
  430. return new Vector3(-this.x, -this.y, -this.z);
  431. };
  432. Vector3.prototype.scaleInPlace = function (scale) {
  433. this.x *= scale;
  434. this.y *= scale;
  435. this.z *= scale;
  436. return this;
  437. };
  438. Vector3.prototype.scale = function (scale) {
  439. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  440. };
  441. Vector3.prototype.scaleToRef = function (scale, result) {
  442. result.x = this.x * scale;
  443. result.y = this.y * scale;
  444. result.z = this.z * scale;
  445. };
  446. Vector3.prototype.equals = function (otherVector) {
  447. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  448. };
  449. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  450. 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;
  451. };
  452. Vector3.prototype.equalsToFloats = function (x, y, z) {
  453. return this.x === x && this.y === y && this.z === z;
  454. };
  455. Vector3.prototype.multiplyInPlace = function (otherVector) {
  456. this.x *= otherVector.x;
  457. this.y *= otherVector.y;
  458. this.z *= otherVector.z;
  459. };
  460. Vector3.prototype.multiply = function (otherVector) {
  461. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  462. };
  463. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  464. result.x = this.x * otherVector.x;
  465. result.y = this.y * otherVector.y;
  466. result.z = this.z * otherVector.z;
  467. };
  468. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  469. return new Vector3(this.x * x, this.y * y, this.z * z);
  470. };
  471. Vector3.prototype.divide = function (otherVector) {
  472. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  473. };
  474. Vector3.prototype.divideToRef = function (otherVector, result) {
  475. result.x = this.x / otherVector.x;
  476. result.y = this.y / otherVector.y;
  477. result.z = this.z / otherVector.z;
  478. };
  479. Vector3.prototype.MinimizeInPlace = function (other) {
  480. if (other.x < this.x)
  481. this.x = other.x;
  482. if (other.y < this.y)
  483. this.y = other.y;
  484. if (other.z < this.z)
  485. this.z = other.z;
  486. };
  487. Vector3.prototype.MaximizeInPlace = function (other) {
  488. if (other.x > this.x)
  489. this.x = other.x;
  490. if (other.y > this.y)
  491. this.y = other.y;
  492. if (other.z > this.z)
  493. this.z = other.z;
  494. };
  495. Vector3.prototype.length = function () {
  496. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  497. };
  498. Vector3.prototype.lengthSquared = function () {
  499. return (this.x * this.x + this.y * this.y + this.z * this.z);
  500. };
  501. Vector3.prototype.normalize = function () {
  502. var len = this.length();
  503. if (len === 0)
  504. return this;
  505. var num = 1.0 / len;
  506. this.x *= num;
  507. this.y *= num;
  508. this.z *= num;
  509. return this;
  510. };
  511. Vector3.prototype.clone = function () {
  512. return new Vector3(this.x, this.y, this.z);
  513. };
  514. Vector3.prototype.copyFrom = function (source) {
  515. this.x = source.x;
  516. this.y = source.y;
  517. this.z = source.z;
  518. };
  519. Vector3.prototype.copyFromFloats = function (x, y, z) {
  520. this.x = x;
  521. this.y = y;
  522. this.z = z;
  523. };
  524. Vector3.FromArray = function (array, offset) {
  525. if (!offset) {
  526. offset = 0;
  527. }
  528. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  529. };
  530. Vector3.FromArrayToRef = function (array, offset, result) {
  531. result.x = array[offset];
  532. result.y = array[offset + 1];
  533. result.z = array[offset + 2];
  534. };
  535. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  536. result.x = array[offset];
  537. result.y = array[offset + 1];
  538. result.z = array[offset + 2];
  539. };
  540. Vector3.FromFloatsToRef = function (x, y, z, result) {
  541. result.x = x;
  542. result.y = y;
  543. result.z = z;
  544. };
  545. Vector3.Zero = function () {
  546. return new Vector3(0, 0, 0);
  547. };
  548. Vector3.Up = function () {
  549. return new Vector3(0, 1.0, 0);
  550. };
  551. Vector3.TransformCoordinates = function (vector, transformation) {
  552. var result = Vector3.Zero();
  553. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  554. return result;
  555. };
  556. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  557. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  558. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  559. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  560. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  561. result.x = x / w;
  562. result.y = y / w;
  563. result.z = z / w;
  564. };
  565. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  566. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  567. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  568. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  569. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  570. result.x = rx / rw;
  571. result.y = ry / rw;
  572. result.z = rz / rw;
  573. };
  574. Vector3.TransformNormal = function (vector, transformation) {
  575. var result = Vector3.Zero();
  576. Vector3.TransformNormalToRef(vector, transformation, result);
  577. return result;
  578. };
  579. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  580. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  581. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  582. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  583. };
  584. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  585. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  586. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  587. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  588. };
  589. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  590. var squared = amount * amount;
  591. var cubed = amount * squared;
  592. 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));
  593. 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));
  594. 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));
  595. return new Vector3(x, y, z);
  596. };
  597. Vector3.Clamp = function (value, min, max) {
  598. var x = value.x;
  599. x = (x > max.x) ? max.x : x;
  600. x = (x < min.x) ? min.x : x;
  601. var y = value.y;
  602. y = (y > max.y) ? max.y : y;
  603. y = (y < min.y) ? min.y : y;
  604. var z = value.z;
  605. z = (z > max.z) ? max.z : z;
  606. z = (z < min.z) ? min.z : z;
  607. return new Vector3(x, y, z);
  608. };
  609. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  610. var squared = amount * amount;
  611. var cubed = amount * squared;
  612. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  613. var part2 = (-2.0 * cubed) + (3.0 * squared);
  614. var part3 = (cubed - (2.0 * squared)) + amount;
  615. var part4 = cubed - squared;
  616. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  617. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  618. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  619. return new Vector3(x, y, z);
  620. };
  621. Vector3.Lerp = function (start, end, amount) {
  622. var x = start.x + ((end.x - start.x) * amount);
  623. var y = start.y + ((end.y - start.y) * amount);
  624. var z = start.z + ((end.z - start.z) * amount);
  625. return new Vector3(x, y, z);
  626. };
  627. Vector3.Dot = function (left, right) {
  628. return (left.x * right.x + left.y * right.y + left.z * right.z);
  629. };
  630. Vector3.Cross = function (left, right) {
  631. var result = Vector3.Zero();
  632. Vector3.CrossToRef(left, right, result);
  633. return result;
  634. };
  635. Vector3.CrossToRef = function (left, right, result) {
  636. result.x = left.y * right.z - left.z * right.y;
  637. result.y = left.z * right.x - left.x * right.z;
  638. result.z = left.x * right.y - left.y * right.x;
  639. };
  640. Vector3.Normalize = function (vector) {
  641. var result = Vector3.Zero();
  642. Vector3.NormalizeToRef(vector, result);
  643. return result;
  644. };
  645. Vector3.NormalizeToRef = function (vector, result) {
  646. result.copyFrom(vector);
  647. result.normalize();
  648. };
  649. Vector3.Project = function (vector, world, transform, viewport) {
  650. var cw = viewport.width;
  651. var ch = viewport.height;
  652. var cx = viewport.x;
  653. var cy = viewport.y;
  654. 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);
  655. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  656. return Vector3.TransformCoordinates(vector, finalMatrix);
  657. };
  658. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  659. var matrix = world.multiply(view).multiply(projection);
  660. matrix.invert();
  661. source.x = source.x / viewportWidth * 2 - 1;
  662. source.y = -(source.y / viewportHeight * 2 - 1);
  663. var vector = BABYLON.Vector3.TransformCoordinates(source, matrix);
  664. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  665. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  666. vector = vector.scale(1.0 / num);
  667. }
  668. return vector;
  669. };
  670. Vector3.Minimize = function (left, right) {
  671. var min = left.clone();
  672. min.MinimizeInPlace(right);
  673. return min;
  674. };
  675. Vector3.Maximize = function (left, right) {
  676. var max = left.clone();
  677. max.MaximizeInPlace(right);
  678. return max;
  679. };
  680. Vector3.Distance = function (value1, value2) {
  681. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  682. };
  683. Vector3.DistanceSquared = function (value1, value2) {
  684. var x = value1.x - value2.x;
  685. var y = value1.y - value2.y;
  686. var z = value1.z - value2.z;
  687. return (x * x) + (y * y) + (z * z);
  688. };
  689. Vector3.Center = function (value1, value2) {
  690. var center = value1.add(value2);
  691. center.scaleInPlace(0.5);
  692. return center;
  693. };
  694. return Vector3;
  695. })();
  696. BABYLON.Vector3 = Vector3;
  697. var Quaternion = (function () {
  698. function Quaternion(x, y, z, w) {
  699. if (typeof x === "undefined") { x = 0; }
  700. if (typeof y === "undefined") { y = 0; }
  701. if (typeof z === "undefined") { z = 0; }
  702. if (typeof w === "undefined") { w = 1; }
  703. this.x = x;
  704. this.y = y;
  705. this.z = z;
  706. this.w = w;
  707. }
  708. Quaternion.prototype.toString = function () {
  709. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  710. };
  711. Quaternion.prototype.asArray = function () {
  712. return [this.x, this.y, this.z, this.w];
  713. };
  714. Quaternion.prototype.equals = function (otherQuaternion) {
  715. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  716. };
  717. Quaternion.prototype.clone = function () {
  718. return new Quaternion(this.x, this.y, this.z, this.w);
  719. };
  720. Quaternion.prototype.copyFrom = function (other) {
  721. this.x = other.x;
  722. this.y = other.y;
  723. this.z = other.z;
  724. this.w = other.w;
  725. };
  726. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  727. this.x = x;
  728. this.y = y;
  729. this.z = z;
  730. this.w = w;
  731. };
  732. Quaternion.prototype.add = function (other) {
  733. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  734. };
  735. Quaternion.prototype.subtract = function (other) {
  736. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  737. };
  738. Quaternion.prototype.scale = function (value) {
  739. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  740. };
  741. Quaternion.prototype.multiply = function (q1) {
  742. var result = new Quaternion(0, 0, 0, 1.0);
  743. this.multiplyToRef(q1, result);
  744. return result;
  745. };
  746. Quaternion.prototype.multiplyToRef = function (q1, result) {
  747. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  748. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  749. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  750. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  751. };
  752. Quaternion.prototype.length = function () {
  753. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  754. };
  755. Quaternion.prototype.normalize = function () {
  756. var length = 1.0 / this.length();
  757. this.x *= length;
  758. this.y *= length;
  759. this.z *= length;
  760. this.w *= length;
  761. };
  762. Quaternion.prototype.toEulerAngles = function () {
  763. var result = Vector3.Zero();
  764. this.toEulerAnglesToRef(result);
  765. return result;
  766. };
  767. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  768. var qx = this.x;
  769. var qy = this.y;
  770. var qz = this.z;
  771. var qw = this.w;
  772. var sqx = qx * qx;
  773. var sqy = qy * qy;
  774. var sqz = qz * qz;
  775. var yaw = Math.atan2(2.0 * (qy * qw - qx * qz), 1.0 - 2.0 * (sqy + sqz));
  776. var pitch = Math.asin(2.0 * (qx * qy + qz * qw));
  777. var roll = Math.atan2(2.0 * (qx * qw - qy * qz), 1.0 - 2.0 * (sqx + sqz));
  778. var gimbaLockTest = qx * qy + qz * qw;
  779. if (gimbaLockTest > 0.499) {
  780. yaw = 2.0 * Math.atan2(qx, qw);
  781. roll = 0;
  782. } else if (gimbaLockTest < -0.499) {
  783. yaw = -2.0 * Math.atan2(qx, qw);
  784. roll = 0;
  785. }
  786. result.x = pitch;
  787. result.y = yaw;
  788. result.z = roll;
  789. };
  790. Quaternion.prototype.toRotationMatrix = function (result) {
  791. var xx = this.x * this.x;
  792. var yy = this.y * this.y;
  793. var zz = this.z * this.z;
  794. var xy = this.x * this.y;
  795. var zw = this.z * this.w;
  796. var zx = this.z * this.x;
  797. var yw = this.y * this.w;
  798. var yz = this.y * this.z;
  799. var xw = this.x * this.w;
  800. result.m[0] = 1.0 - (2.0 * (yy + zz));
  801. result.m[1] = 2.0 * (xy + zw);
  802. result.m[2] = 2.0 * (zx - yw);
  803. result.m[3] = 0;
  804. result.m[4] = 2.0 * (xy - zw);
  805. result.m[5] = 1.0 - (2.0 * (zz + xx));
  806. result.m[6] = 2.0 * (yz + xw);
  807. result.m[7] = 0;
  808. result.m[8] = 2.0 * (zx + yw);
  809. result.m[9] = 2.0 * (yz - xw);
  810. result.m[10] = 1.0 - (2.0 * (yy + xx));
  811. result.m[11] = 0;
  812. result.m[12] = 0;
  813. result.m[13] = 0;
  814. result.m[14] = 0;
  815. result.m[15] = 1.0;
  816. };
  817. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  818. var data = matrix.m;
  819. var m11 = data[0], m12 = data[4], m13 = data[8];
  820. var m21 = data[1], m22 = data[5], m23 = data[9];
  821. var m31 = data[2], m32 = data[6], m33 = data[10];
  822. var trace = m11 + m22 + m33;
  823. var s;
  824. if (trace > 0) {
  825. s = 0.5 / Math.sqrt(trace + 1.0);
  826. this.w = 0.25 / s;
  827. this.x = (m32 - m23) * s;
  828. this.y = (m13 - m31) * s;
  829. this.z = (m21 - m12) * s;
  830. return;
  831. }
  832. if (m11 > m22 && m11 > m33) {
  833. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  834. this.w = (m32 - m23) / s;
  835. this.x = 0.25 * s;
  836. this.y = (m12 + m21) / s;
  837. this.z = (m13 + m31) / s;
  838. return;
  839. }
  840. if (m22 > m33) {
  841. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  842. this.w = (m13 - m31) / s;
  843. this.x = (m12 + m21) / s;
  844. this.y = 0.25 * s;
  845. this.z = (m23 + m32) / s;
  846. return;
  847. }
  848. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  849. this.w = (m21 - m12) / s;
  850. this.x = (m13 + m31) / s;
  851. this.y = (m23 + m32) / s;
  852. this.z = 0.25 * s;
  853. };
  854. Quaternion.Inverse = function (q) {
  855. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  856. };
  857. Quaternion.RotationAxis = function (axis, angle) {
  858. var result = new Quaternion();
  859. var sin = Math.sin(angle / 2);
  860. result.w = Math.cos(angle / 2);
  861. result.x = axis.x * sin;
  862. result.y = axis.y * sin;
  863. result.z = axis.z * sin;
  864. return result;
  865. };
  866. Quaternion.FromArray = function (array, offset) {
  867. if (!offset) {
  868. offset = 0;
  869. }
  870. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  871. };
  872. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  873. var result = new Quaternion();
  874. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  875. return result;
  876. };
  877. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  878. var halfRoll = roll * 0.5;
  879. var halfPitch = pitch * 0.5;
  880. var halfYaw = yaw * 0.5;
  881. var sinRoll = Math.sin(halfRoll);
  882. var cosRoll = Math.cos(halfRoll);
  883. var sinPitch = Math.sin(halfPitch);
  884. var cosPitch = Math.cos(halfPitch);
  885. var sinYaw = Math.sin(halfYaw);
  886. var cosYaw = Math.cos(halfYaw);
  887. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  888. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  889. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  890. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  891. };
  892. Quaternion.Slerp = function (left, right, amount) {
  893. var num2;
  894. var num3;
  895. var num = amount;
  896. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  897. var flag = false;
  898. if (num4 < 0) {
  899. flag = true;
  900. num4 = -num4;
  901. }
  902. if (num4 > 0.999999) {
  903. num3 = 1 - num;
  904. num2 = flag ? -num : num;
  905. } else {
  906. var num5 = Math.acos(num4);
  907. var num6 = (1.0 / Math.sin(num5));
  908. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  909. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  910. }
  911. 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));
  912. };
  913. return Quaternion;
  914. })();
  915. BABYLON.Quaternion = Quaternion;
  916. var Matrix = (function () {
  917. function Matrix() {
  918. this.m = new Float32Array(16);
  919. }
  920. Matrix.prototype.isIdentity = function () {
  921. if (this.m[0] != 1.0 || this.m[5] != 1.0 || this.m[10] != 1.0 || this.m[15] != 1.0)
  922. return false;
  923. 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)
  924. return false;
  925. return true;
  926. };
  927. Matrix.prototype.determinant = function () {
  928. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  929. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  930. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  931. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  932. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  933. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  934. 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))));
  935. };
  936. Matrix.prototype.toArray = function () {
  937. return this.m;
  938. };
  939. Matrix.prototype.asArray = function () {
  940. return this.toArray();
  941. };
  942. Matrix.prototype.invert = function () {
  943. this.invertToRef(this);
  944. };
  945. Matrix.prototype.invertToRef = function (other) {
  946. var l1 = this.m[0];
  947. var l2 = this.m[1];
  948. var l3 = this.m[2];
  949. var l4 = this.m[3];
  950. var l5 = this.m[4];
  951. var l6 = this.m[5];
  952. var l7 = this.m[6];
  953. var l8 = this.m[7];
  954. var l9 = this.m[8];
  955. var l10 = this.m[9];
  956. var l11 = this.m[10];
  957. var l12 = this.m[11];
  958. var l13 = this.m[12];
  959. var l14 = this.m[13];
  960. var l15 = this.m[14];
  961. var l16 = this.m[15];
  962. var l17 = (l11 * l16) - (l12 * l15);
  963. var l18 = (l10 * l16) - (l12 * l14);
  964. var l19 = (l10 * l15) - (l11 * l14);
  965. var l20 = (l9 * l16) - (l12 * l13);
  966. var l21 = (l9 * l15) - (l11 * l13);
  967. var l22 = (l9 * l14) - (l10 * l13);
  968. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  969. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  970. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  971. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  972. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  973. var l28 = (l7 * l16) - (l8 * l15);
  974. var l29 = (l6 * l16) - (l8 * l14);
  975. var l30 = (l6 * l15) - (l7 * l14);
  976. var l31 = (l5 * l16) - (l8 * l13);
  977. var l32 = (l5 * l15) - (l7 * l13);
  978. var l33 = (l5 * l14) - (l6 * l13);
  979. var l34 = (l7 * l12) - (l8 * l11);
  980. var l35 = (l6 * l12) - (l8 * l10);
  981. var l36 = (l6 * l11) - (l7 * l10);
  982. var l37 = (l5 * l12) - (l8 * l9);
  983. var l38 = (l5 * l11) - (l7 * l9);
  984. var l39 = (l5 * l10) - (l6 * l9);
  985. other.m[0] = l23 * l27;
  986. other.m[4] = l24 * l27;
  987. other.m[8] = l25 * l27;
  988. other.m[12] = l26 * l27;
  989. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  990. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  991. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  992. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  993. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  994. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  995. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  996. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  997. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  998. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  999. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1000. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1001. };
  1002. Matrix.prototype.setTranslation = function (vector3) {
  1003. this.m[12] = vector3.x;
  1004. this.m[13] = vector3.y;
  1005. this.m[14] = vector3.z;
  1006. };
  1007. Matrix.prototype.multiply = function (other) {
  1008. var result = new Matrix();
  1009. this.multiplyToRef(other, result);
  1010. return result;
  1011. };
  1012. Matrix.prototype.copyFrom = function (other) {
  1013. for (var index = 0; index < 16; index++) {
  1014. this.m[index] = other.m[index];
  1015. }
  1016. };
  1017. Matrix.prototype.copyToArray = function (array, offset) {
  1018. if (typeof offset === "undefined") { offset = 0; }
  1019. for (var index = 0; index < 16; index++) {
  1020. array[offset + index] = this.m[index];
  1021. }
  1022. };
  1023. Matrix.prototype.multiplyToRef = function (other, result) {
  1024. this.multiplyToArray(other, result.m, 0);
  1025. };
  1026. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1027. var tm0 = this.m[0];
  1028. var tm1 = this.m[1];
  1029. var tm2 = this.m[2];
  1030. var tm3 = this.m[3];
  1031. var tm4 = this.m[4];
  1032. var tm5 = this.m[5];
  1033. var tm6 = this.m[6];
  1034. var tm7 = this.m[7];
  1035. var tm8 = this.m[8];
  1036. var tm9 = this.m[9];
  1037. var tm10 = this.m[10];
  1038. var tm11 = this.m[11];
  1039. var tm12 = this.m[12];
  1040. var tm13 = this.m[13];
  1041. var tm14 = this.m[14];
  1042. var tm15 = this.m[15];
  1043. var om0 = other.m[0];
  1044. var om1 = other.m[1];
  1045. var om2 = other.m[2];
  1046. var om3 = other.m[3];
  1047. var om4 = other.m[4];
  1048. var om5 = other.m[5];
  1049. var om6 = other.m[6];
  1050. var om7 = other.m[7];
  1051. var om8 = other.m[8];
  1052. var om9 = other.m[9];
  1053. var om10 = other.m[10];
  1054. var om11 = other.m[11];
  1055. var om12 = other.m[12];
  1056. var om13 = other.m[13];
  1057. var om14 = other.m[14];
  1058. var om15 = other.m[15];
  1059. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1060. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1061. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1062. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1063. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1064. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1065. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1066. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1067. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1068. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1069. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1070. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1071. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1072. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1073. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1074. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1075. };
  1076. Matrix.prototype.equals = function (value) {
  1077. 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]);
  1078. };
  1079. Matrix.prototype.clone = function () {
  1080. 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]);
  1081. };
  1082. Matrix.FromArray = function (array, offset) {
  1083. var result = new Matrix();
  1084. if (!offset) {
  1085. offset = 0;
  1086. }
  1087. Matrix.FromArrayToRef(array, offset, result);
  1088. return result;
  1089. };
  1090. Matrix.FromArrayToRef = function (array, offset, result) {
  1091. for (var index = 0; index < 16; index++) {
  1092. result.m[index] = array[index + offset];
  1093. }
  1094. };
  1095. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1096. result.m[0] = initialM11;
  1097. result.m[1] = initialM12;
  1098. result.m[2] = initialM13;
  1099. result.m[3] = initialM14;
  1100. result.m[4] = initialM21;
  1101. result.m[5] = initialM22;
  1102. result.m[6] = initialM23;
  1103. result.m[7] = initialM24;
  1104. result.m[8] = initialM31;
  1105. result.m[9] = initialM32;
  1106. result.m[10] = initialM33;
  1107. result.m[11] = initialM34;
  1108. result.m[12] = initialM41;
  1109. result.m[13] = initialM42;
  1110. result.m[14] = initialM43;
  1111. result.m[15] = initialM44;
  1112. };
  1113. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1114. var result = new Matrix();
  1115. result.m[0] = initialM11;
  1116. result.m[1] = initialM12;
  1117. result.m[2] = initialM13;
  1118. result.m[3] = initialM14;
  1119. result.m[4] = initialM21;
  1120. result.m[5] = initialM22;
  1121. result.m[6] = initialM23;
  1122. result.m[7] = initialM24;
  1123. result.m[8] = initialM31;
  1124. result.m[9] = initialM32;
  1125. result.m[10] = initialM33;
  1126. result.m[11] = initialM34;
  1127. result.m[12] = initialM41;
  1128. result.m[13] = initialM42;
  1129. result.m[14] = initialM43;
  1130. result.m[15] = initialM44;
  1131. return result;
  1132. };
  1133. Matrix.Identity = function () {
  1134. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1135. };
  1136. Matrix.IdentityToRef = function (result) {
  1137. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1138. };
  1139. Matrix.Zero = function () {
  1140. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1141. };
  1142. Matrix.RotationX = function (angle) {
  1143. var result = new Matrix();
  1144. Matrix.RotationXToRef(angle, result);
  1145. return result;
  1146. };
  1147. Matrix.RotationXToRef = function (angle, result) {
  1148. var s = Math.sin(angle);
  1149. var c = Math.cos(angle);
  1150. result.m[0] = 1.0;
  1151. result.m[15] = 1.0;
  1152. result.m[5] = c;
  1153. result.m[10] = c;
  1154. result.m[9] = -s;
  1155. result.m[6] = s;
  1156. result.m[1] = 0;
  1157. result.m[2] = 0;
  1158. result.m[3] = 0;
  1159. result.m[4] = 0;
  1160. result.m[7] = 0;
  1161. result.m[8] = 0;
  1162. result.m[11] = 0;
  1163. result.m[12] = 0;
  1164. result.m[13] = 0;
  1165. result.m[14] = 0;
  1166. };
  1167. Matrix.RotationY = function (angle) {
  1168. var result = new Matrix();
  1169. Matrix.RotationYToRef(angle, result);
  1170. return result;
  1171. };
  1172. Matrix.RotationYToRef = function (angle, result) {
  1173. var s = Math.sin(angle);
  1174. var c = Math.cos(angle);
  1175. result.m[5] = 1.0;
  1176. result.m[15] = 1.0;
  1177. result.m[0] = c;
  1178. result.m[2] = -s;
  1179. result.m[8] = s;
  1180. result.m[10] = c;
  1181. result.m[1] = 0;
  1182. result.m[3] = 0;
  1183. result.m[4] = 0;
  1184. result.m[6] = 0;
  1185. result.m[7] = 0;
  1186. result.m[9] = 0;
  1187. result.m[11] = 0;
  1188. result.m[12] = 0;
  1189. result.m[13] = 0;
  1190. result.m[14] = 0;
  1191. };
  1192. Matrix.RotationZ = function (angle) {
  1193. var result = new Matrix();
  1194. Matrix.RotationZToRef(angle, result);
  1195. return result;
  1196. };
  1197. Matrix.RotationZToRef = function (angle, result) {
  1198. var s = Math.sin(angle);
  1199. var c = Math.cos(angle);
  1200. result.m[10] = 1.0;
  1201. result.m[15] = 1.0;
  1202. result.m[0] = c;
  1203. result.m[1] = s;
  1204. result.m[4] = -s;
  1205. result.m[5] = c;
  1206. result.m[2] = 0;
  1207. result.m[3] = 0;
  1208. result.m[6] = 0;
  1209. result.m[7] = 0;
  1210. result.m[8] = 0;
  1211. result.m[9] = 0;
  1212. result.m[11] = 0;
  1213. result.m[12] = 0;
  1214. result.m[13] = 0;
  1215. result.m[14] = 0;
  1216. };
  1217. Matrix.RotationAxis = function (axis, angle) {
  1218. var s = Math.sin(-angle);
  1219. var c = Math.cos(-angle);
  1220. var c1 = 1 - c;
  1221. axis.normalize();
  1222. var result = Matrix.Zero();
  1223. result.m[0] = (axis.x * axis.x) * c1 + c;
  1224. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1225. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1226. result.m[3] = 0.0;
  1227. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1228. result.m[5] = (axis.y * axis.y) * c1 + c;
  1229. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1230. result.m[7] = 0.0;
  1231. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1232. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1233. result.m[10] = (axis.z * axis.z) * c1 + c;
  1234. result.m[11] = 0.0;
  1235. result.m[15] = 1.0;
  1236. return result;
  1237. };
  1238. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1239. var result = new Matrix();
  1240. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1241. return result;
  1242. };
  1243. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1244. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1245. this._tempQuaternion.toRotationMatrix(result);
  1246. };
  1247. Matrix.Scaling = function (x, y, z) {
  1248. var result = Matrix.Zero();
  1249. Matrix.ScalingToRef(x, y, z, result);
  1250. return result;
  1251. };
  1252. Matrix.ScalingToRef = function (x, y, z, result) {
  1253. result.m[0] = x;
  1254. result.m[1] = 0;
  1255. result.m[2] = 0;
  1256. result.m[3] = 0;
  1257. result.m[4] = 0;
  1258. result.m[5] = y;
  1259. result.m[6] = 0;
  1260. result.m[7] = 0;
  1261. result.m[8] = 0;
  1262. result.m[9] = 0;
  1263. result.m[10] = z;
  1264. result.m[11] = 0;
  1265. result.m[12] = 0;
  1266. result.m[13] = 0;
  1267. result.m[14] = 0;
  1268. result.m[15] = 1.0;
  1269. };
  1270. Matrix.Translation = function (x, y, z) {
  1271. var result = Matrix.Identity();
  1272. Matrix.TranslationToRef(x, y, z, result);
  1273. return result;
  1274. };
  1275. Matrix.TranslationToRef = function (x, y, z, result) {
  1276. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1277. };
  1278. Matrix.LookAtLH = function (eye, target, up) {
  1279. var result = Matrix.Zero();
  1280. Matrix.LookAtLHToRef(eye, target, up, result);
  1281. return result;
  1282. };
  1283. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1284. target.subtractToRef(eye, this._zAxis);
  1285. this._zAxis.normalize();
  1286. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1287. this._xAxis.normalize();
  1288. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1289. this._yAxis.normalize();
  1290. var ex = -Vector3.Dot(this._xAxis, eye);
  1291. var ey = -Vector3.Dot(this._yAxis, eye);
  1292. var ez = -Vector3.Dot(this._zAxis, eye);
  1293. 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);
  1294. };
  1295. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1296. var hw = 2.0 / width;
  1297. var hh = 2.0 / height;
  1298. var id = 1.0 / (zfar - znear);
  1299. var nid = znear / (znear - zfar);
  1300. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1301. };
  1302. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1303. var matrix = Matrix.Zero();
  1304. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1305. return matrix;
  1306. };
  1307. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1308. result.m[0] = 2.0 / (right - left);
  1309. result.m[1] = result.m[2] = result.m[3] = 0;
  1310. result.m[5] = 2.0 / (top - bottom);
  1311. result.m[4] = result.m[6] = result.m[7] = 0;
  1312. result.m[10] = -1.0 / (znear - zfar);
  1313. result.m[8] = result.m[9] = result.m[11] = 0;
  1314. result.m[12] = (left + right) / (left - right);
  1315. result.m[13] = (top + bottom) / (bottom - top);
  1316. result.m[14] = znear / (znear - zfar);
  1317. result.m[15] = 1.0;
  1318. };
  1319. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1320. var matrix = Matrix.Zero();
  1321. matrix.m[0] = (2.0 * znear) / width;
  1322. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1323. matrix.m[5] = (2.0 * znear) / height;
  1324. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1325. matrix.m[10] = -zfar / (znear - zfar);
  1326. matrix.m[8] = matrix.m[9] = 0.0;
  1327. matrix.m[11] = 1.0;
  1328. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1329. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1330. return matrix;
  1331. };
  1332. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1333. var matrix = Matrix.Zero();
  1334. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1335. return matrix;
  1336. };
  1337. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1338. var tan = 1.0 / (Math.tan(fov * 0.5));
  1339. result.m[0] = tan / aspect;
  1340. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1341. result.m[5] = tan;
  1342. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1343. result.m[8] = result.m[9] = 0.0;
  1344. result.m[10] = -zfar / (znear - zfar);
  1345. result.m[11] = 1.0;
  1346. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1347. result.m[14] = (znear * zfar) / (znear - zfar);
  1348. };
  1349. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1350. var cw = viewport.width;
  1351. var ch = viewport.height;
  1352. var cx = viewport.x;
  1353. var cy = viewport.y;
  1354. 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);
  1355. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1356. };
  1357. Matrix.Transpose = function (matrix) {
  1358. var result = new Matrix();
  1359. result.m[0] = matrix.m[0];
  1360. result.m[1] = matrix.m[4];
  1361. result.m[2] = matrix.m[8];
  1362. result.m[3] = matrix.m[12];
  1363. result.m[4] = matrix.m[1];
  1364. result.m[5] = matrix.m[5];
  1365. result.m[6] = matrix.m[9];
  1366. result.m[7] = matrix.m[13];
  1367. result.m[8] = matrix.m[2];
  1368. result.m[9] = matrix.m[6];
  1369. result.m[10] = matrix.m[10];
  1370. result.m[11] = matrix.m[14];
  1371. result.m[12] = matrix.m[3];
  1372. result.m[13] = matrix.m[7];
  1373. result.m[14] = matrix.m[11];
  1374. result.m[15] = matrix.m[15];
  1375. return result;
  1376. };
  1377. Matrix.Reflection = function (plane) {
  1378. var matrix = new Matrix();
  1379. Matrix.ReflectionToRef(plane, matrix);
  1380. return matrix;
  1381. };
  1382. Matrix.ReflectionToRef = function (plane, result) {
  1383. plane.normalize();
  1384. var x = plane.normal.x;
  1385. var y = plane.normal.y;
  1386. var z = plane.normal.z;
  1387. var temp = -2 * x;
  1388. var temp2 = -2 * y;
  1389. var temp3 = -2 * z;
  1390. result.m[0] = (temp * x) + 1;
  1391. result.m[1] = temp2 * x;
  1392. result.m[2] = temp3 * x;
  1393. result.m[3] = 0.0;
  1394. result.m[4] = temp * y;
  1395. result.m[5] = (temp2 * y) + 1;
  1396. result.m[6] = temp3 * y;
  1397. result.m[7] = 0.0;
  1398. result.m[8] = temp * z;
  1399. result.m[9] = temp2 * z;
  1400. result.m[10] = (temp3 * z) + 1;
  1401. result.m[11] = 0.0;
  1402. result.m[12] = temp * plane.d;
  1403. result.m[13] = temp2 * plane.d;
  1404. result.m[14] = temp3 * plane.d;
  1405. result.m[15] = 1.0;
  1406. };
  1407. Matrix._tempQuaternion = new Quaternion();
  1408. Matrix._xAxis = Vector3.Zero();
  1409. Matrix._yAxis = Vector3.Zero();
  1410. Matrix._zAxis = Vector3.Zero();
  1411. return Matrix;
  1412. })();
  1413. BABYLON.Matrix = Matrix;
  1414. var Plane = (function () {
  1415. function Plane(a, b, c, d) {
  1416. this.normal = new Vector3(a, b, c);
  1417. this.d = d;
  1418. }
  1419. Plane.prototype.asArray = function () {
  1420. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1421. };
  1422. Plane.prototype.clone = function () {
  1423. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1424. };
  1425. Plane.prototype.normalize = function () {
  1426. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1427. var magnitude = 0;
  1428. if (norm != 0) {
  1429. magnitude = 1.0 / norm;
  1430. }
  1431. this.normal.x *= magnitude;
  1432. this.normal.y *= magnitude;
  1433. this.normal.z *= magnitude;
  1434. this.d *= magnitude;
  1435. };
  1436. Plane.prototype.transform = function (transformation) {
  1437. var transposedMatrix = BABYLON.Matrix.Transpose(transformation);
  1438. var x = this.normal.x;
  1439. var y = this.normal.y;
  1440. var z = this.normal.z;
  1441. var d = this.d;
  1442. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1443. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1444. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1445. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1446. return new BABYLON.Plane(normalX, normalY, normalZ, finalD);
  1447. };
  1448. Plane.prototype.dotCoordinate = function (point) {
  1449. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1450. };
  1451. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1452. var x1 = point2.x - point1.x;
  1453. var y1 = point2.y - point1.y;
  1454. var z1 = point2.z - point1.z;
  1455. var x2 = point3.x - point1.x;
  1456. var y2 = point3.y - point1.y;
  1457. var z2 = point3.z - point1.z;
  1458. var yz = (y1 * z2) - (z1 * y2);
  1459. var xz = (z1 * x2) - (x1 * z2);
  1460. var xy = (x1 * y2) - (y1 * x2);
  1461. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1462. var invPyth;
  1463. if (pyth != 0) {
  1464. invPyth = 1.0 / pyth;
  1465. } else {
  1466. invPyth = 0;
  1467. }
  1468. this.normal.x = yz * invPyth;
  1469. this.normal.y = xz * invPyth;
  1470. this.normal.z = xy * invPyth;
  1471. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1472. };
  1473. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1474. var dot = Vector3.Dot(this.normal, direction);
  1475. return (dot <= epsilon);
  1476. };
  1477. Plane.prototype.signedDistanceTo = function (point) {
  1478. return Vector3.Dot(point, this.normal) + this.d;
  1479. };
  1480. Plane.FromArray = function (array) {
  1481. return new BABYLON.Plane(array[0], array[1], array[2], array[3]);
  1482. };
  1483. Plane.FromPoints = function (point1, point2, point3) {
  1484. var result = new BABYLON.Plane(0, 0, 0, 0);
  1485. result.copyFromPoints(point1, point2, point3);
  1486. return result;
  1487. };
  1488. Plane.FromPositionAndNormal = function (origin, normal) {
  1489. var result = new BABYLON.Plane(0, 0, 0, 0);
  1490. normal.normalize();
  1491. result.normal = normal;
  1492. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1493. return result;
  1494. };
  1495. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1496. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1497. return Vector3.Dot(point, normal) + d;
  1498. };
  1499. return Plane;
  1500. })();
  1501. BABYLON.Plane = Plane;
  1502. var Viewport = (function () {
  1503. function Viewport(x, y, width, height) {
  1504. this.x = x;
  1505. this.y = y;
  1506. this.width = width;
  1507. this.height = height;
  1508. }
  1509. Viewport.prototype.toGlobal = function (engine) {
  1510. var width = engine.getRenderWidth();
  1511. var height = engine.getRenderHeight();
  1512. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1513. };
  1514. return Viewport;
  1515. })();
  1516. BABYLON.Viewport = Viewport;
  1517. var Frustum = (function () {
  1518. function Frustum() {
  1519. }
  1520. Frustum.GetPlanes = function (transform) {
  1521. var frustumPlanes = [];
  1522. for (var index = 0; index < 6; index++) {
  1523. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1524. }
  1525. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1526. return frustumPlanes;
  1527. };
  1528. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1529. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1530. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1531. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1532. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1533. frustumPlanes[0].normalize();
  1534. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1535. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1536. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1537. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1538. frustumPlanes[1].normalize();
  1539. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1540. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1541. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1542. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1543. frustumPlanes[2].normalize();
  1544. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1545. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1546. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1547. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1548. frustumPlanes[3].normalize();
  1549. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1550. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1551. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1552. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1553. frustumPlanes[4].normalize();
  1554. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1555. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1556. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1557. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1558. frustumPlanes[5].normalize();
  1559. };
  1560. return Frustum;
  1561. })();
  1562. BABYLON.Frustum = Frustum;
  1563. var Ray = (function () {
  1564. function Ray(origin, direction) {
  1565. this.origin = origin;
  1566. this.direction = direction;
  1567. }
  1568. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1569. var d = 0.0;
  1570. var maxValue = Number.MAX_VALUE;
  1571. if (Math.abs(this.direction.x) < 0.0000001) {
  1572. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1573. return false;
  1574. }
  1575. } else {
  1576. var inv = 1.0 / this.direction.x;
  1577. var min = (minimum.x - this.origin.x) * inv;
  1578. var max = (maximum.x - this.origin.x) * inv;
  1579. if (min > max) {
  1580. var temp = min;
  1581. min = max;
  1582. max = temp;
  1583. }
  1584. d = Math.max(min, d);
  1585. maxValue = Math.min(max, maxValue);
  1586. if (d > maxValue) {
  1587. return false;
  1588. }
  1589. }
  1590. if (Math.abs(this.direction.y) < 0.0000001) {
  1591. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1592. return false;
  1593. }
  1594. } else {
  1595. inv = 1.0 / this.direction.y;
  1596. min = (minimum.y - this.origin.y) * inv;
  1597. max = (maximum.y - this.origin.y) * inv;
  1598. if (min > max) {
  1599. temp = min;
  1600. min = max;
  1601. max = temp;
  1602. }
  1603. d = Math.max(min, d);
  1604. maxValue = Math.min(max, maxValue);
  1605. if (d > maxValue) {
  1606. return false;
  1607. }
  1608. }
  1609. if (Math.abs(this.direction.z) < 0.0000001) {
  1610. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1611. return false;
  1612. }
  1613. } else {
  1614. inv = 1.0 / this.direction.z;
  1615. min = (minimum.z - this.origin.z) * inv;
  1616. max = (maximum.z - this.origin.z) * inv;
  1617. if (min > max) {
  1618. temp = min;
  1619. min = max;
  1620. max = temp;
  1621. }
  1622. d = Math.max(min, d);
  1623. maxValue = Math.min(max, maxValue);
  1624. if (d > maxValue) {
  1625. return false;
  1626. }
  1627. }
  1628. return true;
  1629. };
  1630. Ray.prototype.intersectsBox = function (box) {
  1631. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1632. };
  1633. Ray.prototype.intersectsSphere = function (sphere) {
  1634. var x = sphere.center.x - this.origin.x;
  1635. var y = sphere.center.y - this.origin.y;
  1636. var z = sphere.center.z - this.origin.z;
  1637. var pyth = (x * x) + (y * y) + (z * z);
  1638. var rr = sphere.radius * sphere.radius;
  1639. if (pyth <= rr) {
  1640. return true;
  1641. }
  1642. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1643. if (dot < 0.0) {
  1644. return false;
  1645. }
  1646. var temp = pyth - (dot * dot);
  1647. return temp <= rr;
  1648. };
  1649. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1650. if (!this._edge1) {
  1651. this._edge1 = BABYLON.Vector3.Zero();
  1652. this._edge2 = BABYLON.Vector3.Zero();
  1653. this._pvec = BABYLON.Vector3.Zero();
  1654. this._tvec = BABYLON.Vector3.Zero();
  1655. this._qvec = BABYLON.Vector3.Zero();
  1656. }
  1657. vertex1.subtractToRef(vertex0, this._edge1);
  1658. vertex2.subtractToRef(vertex0, this._edge2);
  1659. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1660. var det = Vector3.Dot(this._edge1, this._pvec);
  1661. if (det === 0) {
  1662. return null;
  1663. }
  1664. var invdet = 1 / det;
  1665. this.origin.subtractToRef(vertex0, this._tvec);
  1666. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1667. if (bu < 0 || bu > 1.0) {
  1668. return null;
  1669. }
  1670. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1671. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1672. if (bv < 0 || bu + bv > 1.0) {
  1673. return null;
  1674. }
  1675. return new BABYLON.IntersectionInfo(bu, bv, Vector3.Dot(this._edge2, this._qvec) * invdet);
  1676. };
  1677. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1678. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1679. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1680. var direction = end.subtract(start);
  1681. direction.normalize();
  1682. return new Ray(start, direction);
  1683. };
  1684. Ray.Transform = function (ray, matrix) {
  1685. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  1686. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  1687. return new Ray(newOrigin, newDirection);
  1688. };
  1689. return Ray;
  1690. })();
  1691. BABYLON.Ray = Ray;
  1692. (function (Space) {
  1693. Space[Space["LOCAL"] = 0] = "LOCAL";
  1694. Space[Space["WORLD"] = 1] = "WORLD";
  1695. })(BABYLON.Space || (BABYLON.Space = {}));
  1696. var Space = BABYLON.Space;
  1697. var Axis = (function () {
  1698. function Axis() {
  1699. }
  1700. Axis.X = new BABYLON.Vector3(1, 0, 0);
  1701. Axis.Y = new BABYLON.Vector3(0, 1, 0);
  1702. Axis.Z = new BABYLON.Vector3(0, 0, 1);
  1703. return Axis;
  1704. })();
  1705. BABYLON.Axis = Axis;
  1706. ;
  1707. })(BABYLON || (BABYLON = {}));
  1708. var BABYLON;
  1709. (function (BABYLON) {
  1710. var screenshotCanvas;
  1711. var fpsRange = 60;
  1712. var previousFramesDuration = [];
  1713. var fps = 60;
  1714. var deltaTime = 0;
  1715. var cloneValue = function (source, destinationObject) {
  1716. if (!source)
  1717. return null;
  1718. if (source instanceof BABYLON.Mesh) {
  1719. return null;
  1720. }
  1721. if (source instanceof BABYLON.SubMesh) {
  1722. return source.clone(destinationObject);
  1723. } else if (source.clone) {
  1724. return source.clone();
  1725. }
  1726. return null;
  1727. };
  1728. var Tools = (function () {
  1729. function Tools() {
  1730. }
  1731. Tools.GetFilename = function (path) {
  1732. var index = path.lastIndexOf("/");
  1733. if (index < 0)
  1734. return path;
  1735. return path.substring(index + 1);
  1736. };
  1737. Tools.GetDOMTextContent = function (element) {
  1738. var result = "";
  1739. var child = element.firstChild;
  1740. while (child) {
  1741. if (child.nodeType == 3) {
  1742. result += child.textContent;
  1743. }
  1744. child = child.nextSibling;
  1745. }
  1746. return result;
  1747. };
  1748. Tools.ToDegrees = function (angle) {
  1749. return angle * 180 / Math.PI;
  1750. };
  1751. Tools.ToRadians = function (angle) {
  1752. return angle * Math.PI / 180;
  1753. };
  1754. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  1755. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1756. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1757. for (var index = indexStart; index < indexStart + indexCount; index++) {
  1758. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  1759. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1760. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1761. }
  1762. return {
  1763. minimum: minimum,
  1764. maximum: maximum
  1765. };
  1766. };
  1767. Tools.ExtractMinAndMax = function (positions, start, count) {
  1768. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1769. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1770. for (var index = start; index < start + count; index++) {
  1771. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  1772. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1773. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1774. }
  1775. return {
  1776. minimum: minimum,
  1777. maximum: maximum
  1778. };
  1779. };
  1780. Tools.MakeArray = function (obj, allowsNullUndefined) {
  1781. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  1782. return undefined;
  1783. return Array.isArray(obj) ? obj : [obj];
  1784. };
  1785. Tools.GetPointerPrefix = function () {
  1786. var eventPrefix = "pointer";
  1787. if (!navigator.pointerEnabled) {
  1788. eventPrefix = "mouse";
  1789. }
  1790. return eventPrefix;
  1791. };
  1792. Tools.QueueNewFrame = function (func) {
  1793. if (window.requestAnimationFrame)
  1794. window.requestAnimationFrame(func);
  1795. else if (window.msRequestAnimationFrame)
  1796. window.msRequestAnimationFrame(func);
  1797. else if (window.webkitRequestAnimationFrame)
  1798. window.webkitRequestAnimationFrame(func);
  1799. else if (window.mozRequestAnimationFrame)
  1800. window.mozRequestAnimationFrame(func);
  1801. else if (window.oRequestAnimationFrame)
  1802. window.oRequestAnimationFrame(func);
  1803. else {
  1804. window.setTimeout(func, 16);
  1805. }
  1806. };
  1807. Tools.RequestFullscreen = function (element) {
  1808. if (element.requestFullscreen)
  1809. element.requestFullscreen();
  1810. else if (element.msRequestFullscreen)
  1811. element.msRequestFullscreen();
  1812. else if (element.webkitRequestFullscreen)
  1813. element.webkitRequestFullscreen();
  1814. else if (element.mozRequestFullScreen)
  1815. element.mozRequestFullScreen();
  1816. };
  1817. Tools.ExitFullscreen = function () {
  1818. if (document.exitFullscreen) {
  1819. document.exitFullscreen();
  1820. } else if (document.mozCancelFullScreen) {
  1821. document.mozCancelFullScreen();
  1822. } else if (document.webkitCancelFullScreen) {
  1823. document.webkitCancelFullScreen();
  1824. } else if (document.msCancelFullScreen) {
  1825. document.msCancelFullScreen();
  1826. }
  1827. };
  1828. Tools.CleanUrl = function (url) {
  1829. url = url.replace(/#/mg, "%23");
  1830. return url;
  1831. };
  1832. Tools.LoadImage = function (url, onload, onerror, database) {
  1833. url = Tools.CleanUrl(url);
  1834. var img = new Image();
  1835. if (url.substr(0, 5) != "data:")
  1836. img.crossOrigin = 'anonymous';
  1837. img.onload = function () {
  1838. onload(img);
  1839. };
  1840. img.onerror = function (err) {
  1841. onerror(img, err);
  1842. };
  1843. var noIndexedDB = function () {
  1844. img.src = url;
  1845. };
  1846. var loadFromIndexedDB = function () {
  1847. database.loadImageFromDB(url, img);
  1848. };
  1849. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  1850. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1851. } else {
  1852. if (url.indexOf("file:") === -1) {
  1853. noIndexedDB();
  1854. } else {
  1855. try {
  1856. var textureName = url.substring(5);
  1857. var blobURL;
  1858. try {
  1859. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  1860. } catch (ex) {
  1861. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  1862. }
  1863. img.src = blobURL;
  1864. } catch (e) {
  1865. Tools.Log("Error while trying to load texture: " + textureName);
  1866. img.src = null;
  1867. }
  1868. }
  1869. }
  1870. return img;
  1871. };
  1872. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  1873. url = Tools.CleanUrl(url);
  1874. var noIndexedDB = function () {
  1875. var request = new XMLHttpRequest();
  1876. var loadUrl = Tools.BaseUrl + url;
  1877. request.open('GET', loadUrl, true);
  1878. if (useArrayBuffer) {
  1879. request.responseType = "arraybuffer";
  1880. }
  1881. request.onprogress = progressCallBack;
  1882. request.onreadystatechange = function () {
  1883. if (request.readyState == 4) {
  1884. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  1885. callback(!useArrayBuffer ? request.responseText : request.response);
  1886. } else {
  1887. if (onError) {
  1888. onError();
  1889. } else {
  1890. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  1891. }
  1892. }
  1893. }
  1894. };
  1895. request.send(null);
  1896. };
  1897. var loadFromIndexedDB = function () {
  1898. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  1899. };
  1900. if (url.indexOf("file:") !== -1) {
  1901. var fileName = url.substring(5);
  1902. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  1903. } else {
  1904. if (database && database.enableSceneOffline) {
  1905. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1906. } else {
  1907. noIndexedDB();
  1908. }
  1909. }
  1910. };
  1911. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  1912. var reader = new FileReader();
  1913. reader.onload = function (e) {
  1914. callback(e.target.result);
  1915. };
  1916. reader.onprogress = progressCallback;
  1917. reader.readAsDataURL(fileToLoad);
  1918. };
  1919. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  1920. var reader = new FileReader();
  1921. reader.onload = function (e) {
  1922. callback(e.target.result);
  1923. };
  1924. reader.onprogress = progressCallBack;
  1925. if (!useArrayBuffer) {
  1926. reader.readAsText(fileToLoad);
  1927. } else {
  1928. reader.readAsArrayBuffer(fileToLoad);
  1929. }
  1930. };
  1931. Tools.CheckExtends = function (v, min, max) {
  1932. if (v.x < min.x)
  1933. min.x = v.x;
  1934. if (v.y < min.y)
  1935. min.y = v.y;
  1936. if (v.z < min.z)
  1937. min.z = v.z;
  1938. if (v.x > max.x)
  1939. max.x = v.x;
  1940. if (v.y > max.y)
  1941. max.y = v.y;
  1942. if (v.z > max.z)
  1943. max.z = v.z;
  1944. };
  1945. Tools.WithinEpsilon = function (a, b) {
  1946. var num = a - b;
  1947. return -1.401298E-45 <= num && num <= 1.401298E-45;
  1948. };
  1949. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  1950. for (var prop in source) {
  1951. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  1952. continue;
  1953. }
  1954. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  1955. continue;
  1956. }
  1957. var sourceValue = source[prop];
  1958. var typeOfSourceValue = typeof sourceValue;
  1959. if (typeOfSourceValue == "function") {
  1960. continue;
  1961. }
  1962. if (typeOfSourceValue == "object") {
  1963. if (sourceValue instanceof Array) {
  1964. destination[prop] = [];
  1965. if (sourceValue.length > 0) {
  1966. if (typeof sourceValue[0] == "object") {
  1967. for (var index = 0; index < sourceValue.length; index++) {
  1968. var clonedValue = cloneValue(sourceValue[index], destination);
  1969. if (destination[prop].indexOf(clonedValue) === -1) {
  1970. destination[prop].push(clonedValue);
  1971. }
  1972. }
  1973. } else {
  1974. destination[prop] = sourceValue.slice(0);
  1975. }
  1976. }
  1977. } else {
  1978. destination[prop] = cloneValue(sourceValue, destination);
  1979. }
  1980. } else {
  1981. destination[prop] = sourceValue;
  1982. }
  1983. }
  1984. };
  1985. Tools.IsEmpty = function (obj) {
  1986. for (var i in obj) {
  1987. return false;
  1988. }
  1989. return true;
  1990. };
  1991. Tools.RegisterTopRootEvents = function (events) {
  1992. for (var index = 0; index < events.length; index++) {
  1993. var event = events[index];
  1994. window.addEventListener(event.name, event.handler, false);
  1995. try {
  1996. if (window.parent) {
  1997. window.parent.addEventListener(event.name, event.handler, false);
  1998. }
  1999. } catch (e) {
  2000. }
  2001. }
  2002. };
  2003. Tools.UnregisterTopRootEvents = function (events) {
  2004. for (var index = 0; index < events.length; index++) {
  2005. var event = events[index];
  2006. window.removeEventListener(event.name, event.handler);
  2007. try {
  2008. if (window.parent) {
  2009. window.parent.removeEventListener(event.name, event.handler);
  2010. }
  2011. } catch (e) {
  2012. }
  2013. }
  2014. };
  2015. Tools.GetFps = function () {
  2016. return fps;
  2017. };
  2018. Tools.GetDeltaTime = function () {
  2019. return deltaTime;
  2020. };
  2021. Tools._MeasureFps = function () {
  2022. previousFramesDuration.push((new Date).getTime());
  2023. var length = previousFramesDuration.length;
  2024. if (length >= 2) {
  2025. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  2026. }
  2027. if (length >= fpsRange) {
  2028. if (length > fpsRange) {
  2029. previousFramesDuration.splice(0, 1);
  2030. length = previousFramesDuration.length;
  2031. }
  2032. var sum = 0;
  2033. for (var id = 0; id < length - 1; id++) {
  2034. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  2035. }
  2036. fps = 1000.0 / (sum / (length - 1));
  2037. }
  2038. };
  2039. Tools.CreateScreenshot = function (engine, camera, size) {
  2040. var width;
  2041. var height;
  2042. var scene = camera.getScene();
  2043. var previousCamera = null;
  2044. if (scene.activeCamera !== camera) {
  2045. previousCamera = scene.activeCamera;
  2046. scene.activeCamera = camera;
  2047. }
  2048. if (size.precision) {
  2049. width = Math.round(engine.getRenderWidth() * size.precision);
  2050. height = Math.round(width / engine.getAspectRatio(camera));
  2051. size = { width: width, height: height };
  2052. } else if (size.width && size.height) {
  2053. width = size.width;
  2054. height = size.height;
  2055. } else if (size.width && !size.height) {
  2056. width = size.width;
  2057. height = Math.round(width / engine.getAspectRatio(camera));
  2058. size = { width: width, height: height };
  2059. } else if (size.height && !size.width) {
  2060. height = size.height;
  2061. width = Math.round(height * engine.getAspectRatio(camera));
  2062. size = { width: width, height: height };
  2063. } else if (!isNaN(size)) {
  2064. height = size;
  2065. width = size;
  2066. } else {
  2067. Tools.Error("Invalid 'size' parameter !");
  2068. return;
  2069. }
  2070. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2071. texture.renderList = engine.scenes[0].meshes;
  2072. texture.onAfterRender = function () {
  2073. var numberOfChannelsByLine = width * 4;
  2074. var halfHeight = height / 2;
  2075. var data = engine.readPixels(0, 0, width, height);
  2076. for (var i = 0; i < halfHeight; i++) {
  2077. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2078. var currentCell = j + i * numberOfChannelsByLine;
  2079. var targetLine = height - i - 1;
  2080. var targetCell = j + targetLine * numberOfChannelsByLine;
  2081. var temp = data[currentCell];
  2082. data[currentCell] = data[targetCell];
  2083. data[targetCell] = temp;
  2084. }
  2085. }
  2086. if (!screenshotCanvas) {
  2087. screenshotCanvas = document.createElement('canvas');
  2088. }
  2089. screenshotCanvas.width = width;
  2090. screenshotCanvas.height = height;
  2091. var context = screenshotCanvas.getContext('2d');
  2092. var imageData = context.createImageData(width, height);
  2093. imageData.data.set(data);
  2094. context.putImageData(imageData, 0, 0);
  2095. var base64Image = screenshotCanvas.toDataURL();
  2096. if (("download" in document.createElement("a"))) {
  2097. var a = window.document.createElement("a");
  2098. a.href = base64Image;
  2099. var date = new Date();
  2100. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2101. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2102. window.document.body.appendChild(a);
  2103. a.addEventListener("click", function () {
  2104. a.parentElement.removeChild(a);
  2105. });
  2106. a.click();
  2107. } else {
  2108. var newWindow = window.open("");
  2109. var img = newWindow.document.createElement("img");
  2110. img.src = base64Image;
  2111. newWindow.document.body.appendChild(img);
  2112. }
  2113. };
  2114. texture.render(true);
  2115. texture.dispose();
  2116. if (previousCamera) {
  2117. scene.activeCamera = previousCamera;
  2118. }
  2119. };
  2120. Tools.ValidateXHRData = function (xhr, dataType) {
  2121. if (typeof dataType === "undefined") { dataType = 7; }
  2122. try {
  2123. if (dataType & 1) {
  2124. if (xhr.responseText && xhr.responseText.length > 0) {
  2125. return true;
  2126. } else if (dataType === 1) {
  2127. return false;
  2128. }
  2129. }
  2130. if (dataType & 2) {
  2131. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2132. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2133. return true;
  2134. } else if (dataType === 2) {
  2135. return false;
  2136. }
  2137. }
  2138. if (dataType & 4) {
  2139. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2140. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2141. return true;
  2142. } else {
  2143. return false;
  2144. }
  2145. }
  2146. } catch (e) {
  2147. }
  2148. return false;
  2149. };
  2150. Object.defineProperty(Tools, "NoneLogLevel", {
  2151. get: function () {
  2152. return Tools._NoneLogLevel;
  2153. },
  2154. enumerable: true,
  2155. configurable: true
  2156. });
  2157. Object.defineProperty(Tools, "MessageLogLevel", {
  2158. get: function () {
  2159. return Tools._MessageLogLevel;
  2160. },
  2161. enumerable: true,
  2162. configurable: true
  2163. });
  2164. Object.defineProperty(Tools, "WarningLogLevel", {
  2165. get: function () {
  2166. return Tools._WarningLogLevel;
  2167. },
  2168. enumerable: true,
  2169. configurable: true
  2170. });
  2171. Object.defineProperty(Tools, "ErrorLogLevel", {
  2172. get: function () {
  2173. return Tools._ErrorLogLevel;
  2174. },
  2175. enumerable: true,
  2176. configurable: true
  2177. });
  2178. Object.defineProperty(Tools, "AllLogLevel", {
  2179. get: function () {
  2180. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2181. },
  2182. enumerable: true,
  2183. configurable: true
  2184. });
  2185. Tools._FormatMessage = function (message) {
  2186. var padStr = function (i) {
  2187. return (i < 10) ? "0" + i : "" + i;
  2188. };
  2189. var date = new Date();
  2190. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2191. };
  2192. Tools._LogDisabled = function (message) {
  2193. };
  2194. Tools._LogEnabled = function (message) {
  2195. console.log(Tools._FormatMessage(message));
  2196. };
  2197. Tools._WarnDisabled = function (message) {
  2198. };
  2199. Tools._WarnEnabled = function (message) {
  2200. console.warn(Tools._FormatMessage(message));
  2201. };
  2202. Tools._ErrorDisabled = function (message) {
  2203. };
  2204. Tools._ErrorEnabled = function (message) {
  2205. console.error(Tools._FormatMessage(message));
  2206. };
  2207. Object.defineProperty(Tools, "LogLevels", {
  2208. set: function (level) {
  2209. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2210. Tools.Log = Tools._LogEnabled;
  2211. } else {
  2212. Tools.Log = Tools._LogDisabled;
  2213. }
  2214. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2215. Tools.Warn = Tools._WarnEnabled;
  2216. } else {
  2217. Tools.Warn = Tools._WarnDisabled;
  2218. }
  2219. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2220. Tools.Error = Tools._ErrorEnabled;
  2221. } else {
  2222. Tools.Error = Tools._ErrorDisabled;
  2223. }
  2224. },
  2225. enumerable: true,
  2226. configurable: true
  2227. });
  2228. Tools.BaseUrl = "";
  2229. Tools.GetExponantOfTwo = function (value, max) {
  2230. var count = 1;
  2231. do {
  2232. count *= 2;
  2233. } while(count < value);
  2234. if (count > max)
  2235. count = max;
  2236. return count;
  2237. };
  2238. Tools._NoneLogLevel = 0;
  2239. Tools._MessageLogLevel = 1;
  2240. Tools._WarningLogLevel = 2;
  2241. Tools._ErrorLogLevel = 4;
  2242. Tools.Log = Tools._LogEnabled;
  2243. Tools.Warn = Tools._WarnEnabled;
  2244. Tools.Error = Tools._ErrorEnabled;
  2245. return Tools;
  2246. })();
  2247. BABYLON.Tools = Tools;
  2248. })(BABYLON || (BABYLON = {}));
  2249. var BABYLON;
  2250. (function (BABYLON) {
  2251. var _DepthCullingState = (function () {
  2252. function _DepthCullingState() {
  2253. this._isDepthTestDirty = false;
  2254. this._isDepthMaskDirty = false;
  2255. this._isDepthFuncDirty = false;
  2256. this._isCullFaceDirty = false;
  2257. this._isCullDirty = false;
  2258. }
  2259. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2260. get: function () {
  2261. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2262. },
  2263. enumerable: true,
  2264. configurable: true
  2265. });
  2266. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2267. get: function () {
  2268. return this._cullFace;
  2269. },
  2270. set: function (value) {
  2271. if (this._cullFace === value) {
  2272. return;
  2273. }
  2274. this._cullFace = value;
  2275. this._isCullFaceDirty = true;
  2276. },
  2277. enumerable: true,
  2278. configurable: true
  2279. });
  2280. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2281. get: function () {
  2282. return this._cull;
  2283. },
  2284. set: function (value) {
  2285. if (this._cull === value) {
  2286. return;
  2287. }
  2288. this._cull = value;
  2289. this._isCullDirty = true;
  2290. },
  2291. enumerable: true,
  2292. configurable: true
  2293. });
  2294. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2295. get: function () {
  2296. return this._depthFunc;
  2297. },
  2298. set: function (value) {
  2299. if (this._depthFunc === value) {
  2300. return;
  2301. }
  2302. this._depthFunc = value;
  2303. this._isDepthFuncDirty = true;
  2304. },
  2305. enumerable: true,
  2306. configurable: true
  2307. });
  2308. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2309. get: function () {
  2310. return this._depthMask;
  2311. },
  2312. set: function (value) {
  2313. if (this._depthMask === value) {
  2314. return;
  2315. }
  2316. this._depthMask = value;
  2317. this._isDepthMaskDirty = true;
  2318. },
  2319. enumerable: true,
  2320. configurable: true
  2321. });
  2322. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  2323. get: function () {
  2324. return this._depthTest;
  2325. },
  2326. set: function (value) {
  2327. if (this._depthTest === value) {
  2328. return;
  2329. }
  2330. this._depthTest = value;
  2331. this._isDepthTestDirty = true;
  2332. },
  2333. enumerable: true,
  2334. configurable: true
  2335. });
  2336. _DepthCullingState.prototype.reset = function () {
  2337. this._depthMask = true;
  2338. this._depthTest = true;
  2339. this._depthFunc = null;
  2340. this._cull = null;
  2341. this._cullFace = null;
  2342. this._isDepthTestDirty = true;
  2343. this._isDepthMaskDirty = true;
  2344. this._isDepthFuncDirty = false;
  2345. this._isCullFaceDirty = false;
  2346. this._isCullDirty = false;
  2347. };
  2348. _DepthCullingState.prototype.apply = function (gl) {
  2349. if (!this.isDirty) {
  2350. return;
  2351. }
  2352. if (this._isCullDirty) {
  2353. if (this.cull === true) {
  2354. gl.enable(gl.CULL_FACE);
  2355. } else if (this.cull === false) {
  2356. gl.disable(gl.CULL_FACE);
  2357. }
  2358. this._isCullDirty = false;
  2359. }
  2360. if (this._isCullFaceDirty) {
  2361. gl.cullFace(this.cullFace);
  2362. this._isCullFaceDirty = false;
  2363. }
  2364. if (this._isDepthMaskDirty) {
  2365. gl.depthMask(this.depthMask);
  2366. this._isDepthMaskDirty = false;
  2367. }
  2368. if (this._isDepthTestDirty) {
  2369. if (this.depthTest === true) {
  2370. gl.enable(gl.DEPTH_TEST);
  2371. } else if (this.depthTest === false) {
  2372. gl.disable(gl.DEPTH_TEST);
  2373. }
  2374. this._isDepthTestDirty = false;
  2375. }
  2376. if (this._isDepthFuncDirty) {
  2377. gl.depthFunc(this.depthFunc);
  2378. this._isDepthFuncDirty = false;
  2379. }
  2380. };
  2381. return _DepthCullingState;
  2382. })();
  2383. BABYLON._DepthCullingState = _DepthCullingState;
  2384. var _AlphaState = (function () {
  2385. function _AlphaState() {
  2386. this._isAlphaBlendDirty = false;
  2387. this._isBlendFunctionParametersDirty = false;
  2388. this._alphaBlend = false;
  2389. this._blendFunctionParameters = new Array(4);
  2390. }
  2391. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  2392. get: function () {
  2393. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  2394. },
  2395. enumerable: true,
  2396. configurable: true
  2397. });
  2398. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  2399. get: function () {
  2400. return this._alphaBlend;
  2401. },
  2402. set: function (value) {
  2403. if (this._alphaBlend === value) {
  2404. return;
  2405. }
  2406. this._alphaBlend = value;
  2407. this._isAlphaBlendDirty = true;
  2408. },
  2409. enumerable: true,
  2410. configurable: true
  2411. });
  2412. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  2413. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  2414. return;
  2415. }
  2416. this._blendFunctionParameters[0] = value0;
  2417. this._blendFunctionParameters[1] = value1;
  2418. this._blendFunctionParameters[2] = value2;
  2419. this._blendFunctionParameters[3] = value3;
  2420. this._isBlendFunctionParametersDirty = true;
  2421. };
  2422. _AlphaState.prototype.reset = function () {
  2423. this._alphaBlend = false;
  2424. this._blendFunctionParameters[0] = null;
  2425. this._blendFunctionParameters[1] = null;
  2426. this._blendFunctionParameters[2] = null;
  2427. this._blendFunctionParameters[3] = null;
  2428. this._isAlphaBlendDirty = true;
  2429. this._isBlendFunctionParametersDirty = false;
  2430. };
  2431. _AlphaState.prototype.apply = function (gl) {
  2432. if (!this.isDirty) {
  2433. return;
  2434. }
  2435. if (this._isAlphaBlendDirty) {
  2436. if (this._alphaBlend === true) {
  2437. gl.enable(gl.BLEND);
  2438. } else if (this._alphaBlend === false) {
  2439. gl.disable(gl.BLEND);
  2440. }
  2441. this._isAlphaBlendDirty = false;
  2442. }
  2443. if (this._isBlendFunctionParametersDirty) {
  2444. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  2445. this._isBlendFunctionParametersDirty = false;
  2446. }
  2447. };
  2448. return _AlphaState;
  2449. })();
  2450. BABYLON._AlphaState = _AlphaState;
  2451. var compileShader = function (gl, source, type, defines) {
  2452. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2453. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  2454. gl.compileShader(shader);
  2455. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2456. throw new Error(gl.getShaderInfoLog(shader));
  2457. }
  2458. return shader;
  2459. };
  2460. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  2461. var magFilter = gl.NEAREST;
  2462. var minFilter = gl.NEAREST;
  2463. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  2464. magFilter = gl.LINEAR;
  2465. if (generateMipMaps) {
  2466. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2467. } else {
  2468. minFilter = gl.LINEAR;
  2469. }
  2470. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  2471. magFilter = gl.LINEAR;
  2472. if (generateMipMaps) {
  2473. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2474. } else {
  2475. minFilter = gl.LINEAR;
  2476. }
  2477. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  2478. magFilter = gl.NEAREST;
  2479. if (generateMipMaps) {
  2480. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2481. } else {
  2482. minFilter = gl.NEAREST;
  2483. }
  2484. }
  2485. return {
  2486. min: minFilter,
  2487. mag: magFilter
  2488. };
  2489. };
  2490. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  2491. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  2492. var engine = scene.getEngine();
  2493. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  2494. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  2495. gl.bindTexture(gl.TEXTURE_2D, texture);
  2496. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2497. processFunction(potWidth, potHeight);
  2498. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  2499. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2500. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2501. if (!noMipmap && !isCompressed) {
  2502. gl.generateMipmap(gl.TEXTURE_2D);
  2503. }
  2504. gl.bindTexture(gl.TEXTURE_2D, null);
  2505. engine._activeTexturesCache = [];
  2506. texture._baseWidth = width;
  2507. texture._baseHeight = height;
  2508. texture._width = potWidth;
  2509. texture._height = potHeight;
  2510. texture.isReady = true;
  2511. scene._removePendingData(texture);
  2512. };
  2513. var cascadeLoad = function (rootUrl, index, loadedImages, scene, onfinish, extensions) {
  2514. var img;
  2515. var onload = function () {
  2516. loadedImages.push(img);
  2517. scene._removePendingData(img);
  2518. if (index != extensions.length - 1) {
  2519. cascadeLoad(rootUrl, index + 1, loadedImages, scene, onfinish, extensions);
  2520. } else {
  2521. onfinish(loadedImages);
  2522. }
  2523. };
  2524. var onerror = function () {
  2525. scene._removePendingData(img);
  2526. };
  2527. img = BABYLON.Tools.LoadImage(rootUrl + extensions[index], onload, onerror, scene.database);
  2528. scene._addPendingData(img);
  2529. };
  2530. var EngineCapabilities = (function () {
  2531. function EngineCapabilities() {
  2532. }
  2533. return EngineCapabilities;
  2534. })();
  2535. BABYLON.EngineCapabilities = EngineCapabilities;
  2536. var Engine = (function () {
  2537. function Engine(canvas, antialias, options) {
  2538. var _this = this;
  2539. this.isFullscreen = false;
  2540. this.isPointerLock = false;
  2541. this.forceWireframe = false;
  2542. this.cullBackFaces = true;
  2543. this.renderEvenInBackground = true;
  2544. this.scenes = new Array();
  2545. this._windowIsBackground = false;
  2546. this._runningLoop = false;
  2547. this._loadingDivBackgroundColor = "black";
  2548. this._depthCullingState = new _DepthCullingState();
  2549. this._alphaState = new _AlphaState();
  2550. this._loadedTexturesCache = new Array();
  2551. this._activeTexturesCache = new Array();
  2552. this._compiledEffects = {};
  2553. this._renderingCanvas = canvas;
  2554. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2555. options = options || {};
  2556. options.antialias = antialias;
  2557. try {
  2558. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  2559. } catch (e) {
  2560. throw new Error("WebGL not supported");
  2561. }
  2562. if (!this._gl) {
  2563. throw new Error("WebGL not supported");
  2564. }
  2565. this._onBlur = function () {
  2566. _this._windowIsBackground = true;
  2567. };
  2568. this._onFocus = function () {
  2569. _this._windowIsBackground = false;
  2570. };
  2571. window.addEventListener("blur", this._onBlur);
  2572. window.addEventListener("focus", this._onFocus);
  2573. this._workingCanvas = document.createElement("canvas");
  2574. this._workingContext = this._workingCanvas.getContext("2d");
  2575. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  2576. this.resize();
  2577. this._caps = new EngineCapabilities();
  2578. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  2579. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  2580. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  2581. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  2582. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  2583. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  2584. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  2585. 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');
  2586. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  2587. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  2588. this.setDepthBuffer(true);
  2589. this.setDepthFunctionToLessOrEqual();
  2590. this.setDepthWrite(true);
  2591. this._onFullscreenChange = function () {
  2592. if (document.fullscreen !== undefined) {
  2593. _this.isFullscreen = document.fullscreen;
  2594. } else if (document.mozFullScreen !== undefined) {
  2595. _this.isFullscreen = document.mozFullScreen;
  2596. } else if (document.webkitIsFullScreen !== undefined) {
  2597. _this.isFullscreen = document.webkitIsFullScreen;
  2598. } else if (document.msIsFullScreen !== undefined) {
  2599. _this.isFullscreen = document.msIsFullScreen;
  2600. }
  2601. if (_this.isFullscreen && _this._pointerLockRequested) {
  2602. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  2603. if (canvas.requestPointerLock) {
  2604. canvas.requestPointerLock();
  2605. }
  2606. }
  2607. };
  2608. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  2609. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  2610. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  2611. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  2612. this._onPointerLockChange = function () {
  2613. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  2614. };
  2615. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  2616. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  2617. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  2618. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  2619. }
  2620. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  2621. get: function () {
  2622. return Engine._ALPHA_DISABLE;
  2623. },
  2624. enumerable: true,
  2625. configurable: true
  2626. });
  2627. Object.defineProperty(Engine, "ALPHA_ADD", {
  2628. get: function () {
  2629. return Engine._ALPHA_ADD;
  2630. },
  2631. enumerable: true,
  2632. configurable: true
  2633. });
  2634. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  2635. get: function () {
  2636. return Engine._ALPHA_COMBINE;
  2637. },
  2638. enumerable: true,
  2639. configurable: true
  2640. });
  2641. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  2642. get: function () {
  2643. return Engine._DELAYLOADSTATE_NONE;
  2644. },
  2645. enumerable: true,
  2646. configurable: true
  2647. });
  2648. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  2649. get: function () {
  2650. return Engine._DELAYLOADSTATE_LOADED;
  2651. },
  2652. enumerable: true,
  2653. configurable: true
  2654. });
  2655. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  2656. get: function () {
  2657. return Engine._DELAYLOADSTATE_LOADING;
  2658. },
  2659. enumerable: true,
  2660. configurable: true
  2661. });
  2662. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  2663. get: function () {
  2664. return Engine._DELAYLOADSTATE_NOTLOADED;
  2665. },
  2666. enumerable: true,
  2667. configurable: true
  2668. });
  2669. Object.defineProperty(Engine, "Version", {
  2670. get: function () {
  2671. return "1.14.0";
  2672. },
  2673. enumerable: true,
  2674. configurable: true
  2675. });
  2676. Engine.prototype.getAspectRatio = function (camera) {
  2677. var viewport = camera.viewport;
  2678. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  2679. };
  2680. Engine.prototype.getRenderWidth = function () {
  2681. if (this._currentRenderTarget) {
  2682. return this._currentRenderTarget._width;
  2683. }
  2684. return this._renderingCanvas.width;
  2685. };
  2686. Engine.prototype.getRenderHeight = function () {
  2687. if (this._currentRenderTarget) {
  2688. return this._currentRenderTarget._height;
  2689. }
  2690. return this._renderingCanvas.height;
  2691. };
  2692. Engine.prototype.getRenderingCanvas = function () {
  2693. return this._renderingCanvas;
  2694. };
  2695. Engine.prototype.getRenderingCanvasClientRect = function () {
  2696. return this._renderingCanvas.getBoundingClientRect();
  2697. };
  2698. Engine.prototype.setHardwareScalingLevel = function (level) {
  2699. this._hardwareScalingLevel = level;
  2700. this.resize();
  2701. };
  2702. Engine.prototype.getHardwareScalingLevel = function () {
  2703. return this._hardwareScalingLevel;
  2704. };
  2705. Engine.prototype.getLoadedTexturesCache = function () {
  2706. return this._loadedTexturesCache;
  2707. };
  2708. Engine.prototype.getCaps = function () {
  2709. return this._caps;
  2710. };
  2711. Engine.prototype.setDepthFunctionToGreater = function () {
  2712. this._depthCullingState.depthFunc = this._gl.GREATER;
  2713. };
  2714. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  2715. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  2716. };
  2717. Engine.prototype.setDepthFunctionToLess = function () {
  2718. this._depthCullingState.depthFunc = this._gl.LESS;
  2719. };
  2720. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  2721. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  2722. };
  2723. Engine.prototype.stopRenderLoop = function () {
  2724. this._renderFunction = null;
  2725. this._runningLoop = false;
  2726. };
  2727. Engine.prototype._renderLoop = function () {
  2728. var _this = this;
  2729. var shouldRender = true;
  2730. if (!this.renderEvenInBackground && this._windowIsBackground) {
  2731. shouldRender = false;
  2732. }
  2733. if (shouldRender) {
  2734. this.beginFrame();
  2735. if (this._renderFunction) {
  2736. this._renderFunction();
  2737. }
  2738. this.endFrame();
  2739. }
  2740. if (this._runningLoop) {
  2741. BABYLON.Tools.QueueNewFrame(function () {
  2742. _this._renderLoop();
  2743. });
  2744. }
  2745. };
  2746. Engine.prototype.runRenderLoop = function (renderFunction) {
  2747. var _this = this;
  2748. this._runningLoop = true;
  2749. this._renderFunction = renderFunction;
  2750. BABYLON.Tools.QueueNewFrame(function () {
  2751. _this._renderLoop();
  2752. });
  2753. };
  2754. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  2755. if (this.isFullscreen) {
  2756. BABYLON.Tools.ExitFullscreen();
  2757. } else {
  2758. this._pointerLockRequested = requestPointerLock;
  2759. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  2760. }
  2761. };
  2762. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  2763. this.applyStates();
  2764. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  2765. if (this._depthCullingState.depthMask) {
  2766. this._gl.clearDepth(1.0);
  2767. }
  2768. var mode = 0;
  2769. if (backBuffer)
  2770. mode |= this._gl.COLOR_BUFFER_BIT;
  2771. if (depthStencil && this._depthCullingState.depthMask)
  2772. mode |= this._gl.DEPTH_BUFFER_BIT;
  2773. this._gl.clear(mode);
  2774. };
  2775. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  2776. var width = requiredWidth || this._renderingCanvas.width;
  2777. var height = requiredHeight || this._renderingCanvas.height;
  2778. var x = viewport.x || 0;
  2779. var y = viewport.y || 0;
  2780. this._cachedViewport = viewport;
  2781. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  2782. };
  2783. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  2784. this._cachedViewport = null;
  2785. this._gl.viewport(x, y, width, height);
  2786. };
  2787. Engine.prototype.beginFrame = function () {
  2788. BABYLON.Tools._MeasureFps();
  2789. };
  2790. Engine.prototype.endFrame = function () {
  2791. this.flushFramebuffer();
  2792. };
  2793. Engine.prototype.resize = function () {
  2794. this._renderingCanvas.width = this._renderingCanvas.clientWidth / this._hardwareScalingLevel;
  2795. this._renderingCanvas.height = this._renderingCanvas.clientHeight / this._hardwareScalingLevel;
  2796. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2797. };
  2798. Engine.prototype.bindFramebuffer = function (texture) {
  2799. this._currentRenderTarget = texture;
  2800. var gl = this._gl;
  2801. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  2802. this._gl.viewport(0, 0, texture._width, texture._height);
  2803. this.wipeCaches();
  2804. };
  2805. Engine.prototype.unBindFramebuffer = function (texture) {
  2806. this._currentRenderTarget = null;
  2807. if (texture.generateMipMaps) {
  2808. var gl = this._gl;
  2809. gl.bindTexture(gl.TEXTURE_2D, texture);
  2810. gl.generateMipmap(gl.TEXTURE_2D);
  2811. gl.bindTexture(gl.TEXTURE_2D, null);
  2812. }
  2813. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2814. };
  2815. Engine.prototype.flushFramebuffer = function () {
  2816. this._gl.flush();
  2817. };
  2818. Engine.prototype.restoreDefaultFramebuffer = function () {
  2819. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2820. this.setViewport(this._cachedViewport);
  2821. this.wipeCaches();
  2822. };
  2823. Engine.prototype._resetVertexBufferBinding = function () {
  2824. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  2825. this._cachedVertexBuffers = null;
  2826. };
  2827. Engine.prototype.createVertexBuffer = function (vertices) {
  2828. var vbo = this._gl.createBuffer();
  2829. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2830. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  2831. this._resetVertexBufferBinding();
  2832. vbo.references = 1;
  2833. return vbo;
  2834. };
  2835. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  2836. var vbo = this._gl.createBuffer();
  2837. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2838. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2839. this._resetVertexBufferBinding();
  2840. vbo.references = 1;
  2841. return vbo;
  2842. };
  2843. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, length) {
  2844. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2845. if (vertices instanceof Float32Array) {
  2846. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  2847. } else {
  2848. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  2849. }
  2850. this._resetVertexBufferBinding();
  2851. };
  2852. Engine.prototype._resetIndexBufferBinding = function () {
  2853. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  2854. this._cachedIndexBuffer = null;
  2855. };
  2856. Engine.prototype.createIndexBuffer = function (indices) {
  2857. var vbo = this._gl.createBuffer();
  2858. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  2859. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  2860. this._resetIndexBufferBinding();
  2861. vbo.references = 1;
  2862. return vbo;
  2863. };
  2864. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  2865. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  2866. this._cachedVertexBuffers = vertexBuffer;
  2867. this._cachedEffectForVertexBuffers = effect;
  2868. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2869. var offset = 0;
  2870. for (var index = 0; index < vertexDeclaration.length; index++) {
  2871. var order = effect.getAttributeLocation(index);
  2872. if (order >= 0) {
  2873. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  2874. }
  2875. offset += vertexDeclaration[index] * 4;
  2876. }
  2877. }
  2878. if (this._cachedIndexBuffer !== indexBuffer) {
  2879. this._cachedIndexBuffer = indexBuffer;
  2880. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  2881. }
  2882. };
  2883. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  2884. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  2885. this._cachedVertexBuffers = vertexBuffers;
  2886. this._cachedEffectForVertexBuffers = effect;
  2887. var attributes = effect.getAttributesNames();
  2888. for (var index = 0; index < attributes.length; index++) {
  2889. var order = effect.getAttributeLocation(index);
  2890. if (order >= 0) {
  2891. var vertexBuffer = vertexBuffers[attributes[index]];
  2892. if (!vertexBuffer) {
  2893. continue;
  2894. }
  2895. var stride = vertexBuffer.getStrideSize();
  2896. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  2897. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  2898. }
  2899. }
  2900. }
  2901. if (this._cachedIndexBuffer !== indexBuffer) {
  2902. this._cachedIndexBuffer = indexBuffer;
  2903. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  2904. }
  2905. };
  2906. Engine.prototype._releaseBuffer = function (buffer) {
  2907. buffer.references--;
  2908. if (buffer.references === 0) {
  2909. this._gl.deleteBuffer(buffer);
  2910. return true;
  2911. }
  2912. return false;
  2913. };
  2914. Engine.prototype.createInstancesBuffer = function (capacity) {
  2915. var buffer = this._gl.createBuffer();
  2916. buffer.capacity = capacity;
  2917. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  2918. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2919. return buffer;
  2920. };
  2921. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  2922. this._gl.deleteBuffer(buffer);
  2923. };
  2924. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  2925. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  2926. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2927. for (var index = 0; index < 4; index++) {
  2928. var offsetLocation = offsetLocations[index];
  2929. this._gl.enableVertexAttribArray(offsetLocation);
  2930. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  2931. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  2932. }
  2933. };
  2934. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  2935. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  2936. for (var index = 0; index < 4; index++) {
  2937. var offsetLocation = offsetLocations[index];
  2938. this._gl.disableVertexAttribArray(offsetLocation);
  2939. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  2940. }
  2941. };
  2942. Engine.prototype.applyStates = function () {
  2943. this._depthCullingState.apply(this._gl);
  2944. this._alphaState.apply(this._gl);
  2945. };
  2946. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  2947. this.applyStates();
  2948. if (instancesCount) {
  2949. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2, instancesCount);
  2950. return;
  2951. }
  2952. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  2953. };
  2954. Engine.prototype._releaseEffect = function (effect) {
  2955. if (this._compiledEffects[effect._key]) {
  2956. delete this._compiledEffects[effect._key];
  2957. if (effect.getProgram()) {
  2958. this._gl.deleteProgram(effect.getProgram());
  2959. }
  2960. }
  2961. };
  2962. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  2963. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  2964. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  2965. var name = vertex + "+" + fragment + "@" + defines;
  2966. if (this._compiledEffects[name]) {
  2967. return this._compiledEffects[name];
  2968. }
  2969. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  2970. effect._key = name;
  2971. this._compiledEffects[name] = effect;
  2972. return effect;
  2973. };
  2974. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  2975. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  2976. if (typeof samplers === "undefined") { samplers = []; }
  2977. if (typeof defines === "undefined") { defines = ""; }
  2978. return this.createEffect({
  2979. vertex: "particles",
  2980. fragmentElement: fragmentName
  2981. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  2982. };
  2983. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  2984. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  2985. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  2986. var shaderProgram = this._gl.createProgram();
  2987. this._gl.attachShader(shaderProgram, vertexShader);
  2988. this._gl.attachShader(shaderProgram, fragmentShader);
  2989. this._gl.linkProgram(shaderProgram);
  2990. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  2991. if (!linked) {
  2992. var error = this._gl.getProgramInfoLog(shaderProgram);
  2993. if (error) {
  2994. throw new Error(error);
  2995. }
  2996. }
  2997. this._gl.deleteShader(vertexShader);
  2998. this._gl.deleteShader(fragmentShader);
  2999. return shaderProgram;
  3000. };
  3001. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3002. var results = [];
  3003. for (var index = 0; index < uniformsNames.length; index++) {
  3004. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3005. }
  3006. return results;
  3007. };
  3008. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3009. var results = [];
  3010. for (var index = 0; index < attributesNames.length; index++) {
  3011. try {
  3012. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3013. } catch (e) {
  3014. results.push(-1);
  3015. }
  3016. }
  3017. return results;
  3018. };
  3019. Engine.prototype.enableEffect = function (effect) {
  3020. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3021. return;
  3022. }
  3023. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3024. this._gl.useProgram(effect.getProgram());
  3025. for (var i in this._vertexAttribArrays) {
  3026. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3027. continue;
  3028. }
  3029. this._vertexAttribArrays[i] = false;
  3030. this._gl.disableVertexAttribArray(i);
  3031. }
  3032. var attributesCount = effect.getAttributesCount();
  3033. for (var index = 0; index < attributesCount; index++) {
  3034. var order = effect.getAttributeLocation(index);
  3035. if (order >= 0) {
  3036. this._vertexAttribArrays[order] = true;
  3037. this._gl.enableVertexAttribArray(order);
  3038. }
  3039. }
  3040. this._currentEffect = effect;
  3041. };
  3042. Engine.prototype.setArray = function (uniform, array) {
  3043. if (!uniform)
  3044. return;
  3045. this._gl.uniform1fv(uniform, array);
  3046. };
  3047. Engine.prototype.setMatrices = function (uniform, matrices) {
  3048. if (!uniform)
  3049. return;
  3050. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3051. };
  3052. Engine.prototype.setMatrix = function (uniform, matrix) {
  3053. if (!uniform)
  3054. return;
  3055. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3056. };
  3057. Engine.prototype.setFloat = function (uniform, value) {
  3058. if (!uniform)
  3059. return;
  3060. this._gl.uniform1f(uniform, value);
  3061. };
  3062. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3063. if (!uniform)
  3064. return;
  3065. this._gl.uniform2f(uniform, x, y);
  3066. };
  3067. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3068. if (!uniform)
  3069. return;
  3070. this._gl.uniform3f(uniform, x, y, z);
  3071. };
  3072. Engine.prototype.setBool = function (uniform, bool) {
  3073. if (!uniform)
  3074. return;
  3075. this._gl.uniform1i(uniform, bool);
  3076. };
  3077. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3078. if (!uniform)
  3079. return;
  3080. this._gl.uniform4f(uniform, x, y, z, w);
  3081. };
  3082. Engine.prototype.setColor3 = function (uniform, color3) {
  3083. if (!uniform)
  3084. return;
  3085. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3086. };
  3087. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3088. if (!uniform)
  3089. return;
  3090. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3091. };
  3092. Engine.prototype.setState = function (culling, force) {
  3093. if (this._depthCullingState.cull !== culling || force) {
  3094. if (culling) {
  3095. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3096. this._depthCullingState.cull = true;
  3097. } else {
  3098. this._depthCullingState.cull = false;
  3099. }
  3100. }
  3101. };
  3102. Engine.prototype.setDepthBuffer = function (enable) {
  3103. this._depthCullingState.depthTest = enable;
  3104. };
  3105. Engine.prototype.getDepthWrite = function () {
  3106. return this._depthCullingState.depthMask;
  3107. };
  3108. Engine.prototype.setDepthWrite = function (enable) {
  3109. this._depthCullingState.depthMask = enable;
  3110. };
  3111. Engine.prototype.setColorWrite = function (enable) {
  3112. this._gl.colorMask(enable, enable, enable, enable);
  3113. };
  3114. Engine.prototype.setAlphaMode = function (mode) {
  3115. switch (mode) {
  3116. case BABYLON.Engine.ALPHA_DISABLE:
  3117. this.setDepthWrite(true);
  3118. this._alphaState.alphaBlend = false;
  3119. break;
  3120. case BABYLON.Engine.ALPHA_COMBINE:
  3121. this.setDepthWrite(false);
  3122. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3123. this._alphaState.alphaBlend = true;
  3124. break;
  3125. case BABYLON.Engine.ALPHA_ADD:
  3126. this.setDepthWrite(false);
  3127. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3128. this._alphaState.alphaBlend = true;
  3129. break;
  3130. }
  3131. };
  3132. Engine.prototype.setAlphaTesting = function (enable) {
  3133. this._alphaTest = enable;
  3134. };
  3135. Engine.prototype.getAlphaTesting = function () {
  3136. return this._alphaTest;
  3137. };
  3138. Engine.prototype.wipeCaches = function () {
  3139. this._activeTexturesCache = [];
  3140. this._currentEffect = null;
  3141. this._depthCullingState.reset();
  3142. this._alphaState.reset();
  3143. this._cachedVertexBuffers = null;
  3144. this._cachedIndexBuffer = null;
  3145. this._cachedEffectForVertexBuffers = null;
  3146. };
  3147. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3148. var gl = this._gl;
  3149. gl.bindTexture(gl.TEXTURE_2D, texture);
  3150. var magFilter = gl.NEAREST;
  3151. var minFilter = gl.NEAREST;
  3152. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3153. magFilter = gl.LINEAR;
  3154. minFilter = gl.LINEAR;
  3155. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3156. magFilter = gl.LINEAR;
  3157. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3158. }
  3159. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3160. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3161. gl.bindTexture(gl.TEXTURE_2D, null);
  3162. };
  3163. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  3164. var _this = this;
  3165. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3166. if (typeof onLoad === "undefined") { onLoad = null; }
  3167. if (typeof onError === "undefined") { onError = null; }
  3168. if (typeof buffer === "undefined") { buffer = null; }
  3169. var texture = this._gl.createTexture();
  3170. var extension;
  3171. var fromData = false;
  3172. if (url.substr(0, 5) === "data:") {
  3173. fromData = true;
  3174. }
  3175. if (!fromData)
  3176. extension = url.substr(url.length - 4, 4).toLowerCase();
  3177. else {
  3178. var oldUrl = url;
  3179. fromData = oldUrl.split(':');
  3180. url = oldUrl;
  3181. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  3182. }
  3183. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3184. var isTGA = (extension === ".tga");
  3185. scene._addPendingData(texture);
  3186. texture.url = url;
  3187. texture.noMipmap = noMipmap;
  3188. texture.references = 1;
  3189. this._loadedTexturesCache.push(texture);
  3190. var onerror = function () {
  3191. scene._removePendingData(texture);
  3192. if (onError) {
  3193. onError();
  3194. }
  3195. };
  3196. if (isTGA) {
  3197. var callback = function (arrayBuffer) {
  3198. var data = new Uint8Array(arrayBuffer);
  3199. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  3200. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  3201. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  3202. if (onLoad) {
  3203. onLoad();
  3204. }
  3205. }, samplingMode);
  3206. };
  3207. if (!(fromData instanceof Array))
  3208. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  3209. callback(arrayBuffer);
  3210. }, onerror, scene.database, true);
  3211. else
  3212. callback(buffer);
  3213. } else if (isDDS) {
  3214. var callback = function (data) {
  3215. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3216. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  3217. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  3218. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  3219. if (onLoad) {
  3220. onLoad();
  3221. }
  3222. }, samplingMode);
  3223. };
  3224. if (!(fromData instanceof Array))
  3225. BABYLON.Tools.LoadFile(url, function (data) {
  3226. callback(data);
  3227. }, onerror, scene.database, true);
  3228. else
  3229. callback(buffer);
  3230. } else {
  3231. var onload = function (img) {
  3232. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  3233. var isPot = (img.width == potWidth && img.height == potHeight);
  3234. if (!isPot) {
  3235. _this._workingCanvas.width = potWidth;
  3236. _this._workingCanvas.height = potHeight;
  3237. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3238. }
  3239. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  3240. if (onLoad) {
  3241. onLoad();
  3242. }
  3243. }, samplingMode);
  3244. };
  3245. if (!(fromData instanceof Array))
  3246. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3247. else
  3248. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  3249. }
  3250. return texture;
  3251. };
  3252. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  3253. var texture = this._gl.createTexture();
  3254. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  3255. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  3256. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3257. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3258. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3259. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3260. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3261. this._activeTexturesCache = [];
  3262. texture._baseWidth = width;
  3263. texture._baseHeight = height;
  3264. texture._width = width;
  3265. texture._height = height;
  3266. texture.isReady = false;
  3267. texture.generateMipMaps = generateMipMaps;
  3268. texture.references = 1;
  3269. this._loadedTexturesCache.push(texture);
  3270. return texture;
  3271. };
  3272. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  3273. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3274. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  3275. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  3276. if (texture.generateMipMaps) {
  3277. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3278. }
  3279. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3280. this._activeTexturesCache = [];
  3281. texture.isReady = true;
  3282. };
  3283. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  3284. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3285. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1);
  3286. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  3287. if (!texture._workingCanvas) {
  3288. texture._workingCanvas = document.createElement("canvas");
  3289. texture._workingContext = texture._workingCanvas.getContext("2d");
  3290. texture._workingCanvas.width = texture._width;
  3291. texture._workingCanvas.height = texture._height;
  3292. }
  3293. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  3294. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3295. } else {
  3296. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3297. }
  3298. if (texture.generateMipMaps) {
  3299. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3300. }
  3301. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3302. this._activeTexturesCache = [];
  3303. texture.isReady = true;
  3304. };
  3305. Engine.prototype.createRenderTargetTexture = function (size, options) {
  3306. var generateMipMaps = false;
  3307. var generateDepthBuffer = true;
  3308. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3309. if (options !== undefined) {
  3310. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  3311. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3312. if (options.samplingMode !== undefined) {
  3313. samplingMode = options.samplingMode;
  3314. }
  3315. }
  3316. var gl = this._gl;
  3317. var texture = gl.createTexture();
  3318. gl.bindTexture(gl.TEXTURE_2D, texture);
  3319. var width = size.width || size;
  3320. var height = size.height || size;
  3321. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3322. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3323. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3324. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3325. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3326. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  3327. var depthBuffer;
  3328. if (generateDepthBuffer) {
  3329. depthBuffer = gl.createRenderbuffer();
  3330. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  3331. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3332. }
  3333. var framebuffer = gl.createFramebuffer();
  3334. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  3335. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3336. if (generateDepthBuffer) {
  3337. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  3338. }
  3339. gl.bindTexture(gl.TEXTURE_2D, null);
  3340. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3341. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3342. texture._framebuffer = framebuffer;
  3343. if (generateDepthBuffer) {
  3344. texture._depthBuffer = depthBuffer;
  3345. }
  3346. texture._width = width;
  3347. texture._height = height;
  3348. texture.isReady = true;
  3349. texture.generateMipMaps = generateMipMaps;
  3350. texture.references = 1;
  3351. this._activeTexturesCache = [];
  3352. this._loadedTexturesCache.push(texture);
  3353. return texture;
  3354. };
  3355. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  3356. var _this = this;
  3357. var gl = this._gl;
  3358. var texture = gl.createTexture();
  3359. texture.isCube = true;
  3360. texture.url = rootUrl;
  3361. texture.references = 1;
  3362. this._loadedTexturesCache.push(texture);
  3363. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  3364. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3365. if (isDDS) {
  3366. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  3367. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3368. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3369. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3370. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3371. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  3372. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  3373. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3374. }
  3375. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3376. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3377. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3378. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3379. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3380. _this._activeTexturesCache = [];
  3381. texture._width = info.width;
  3382. texture._height = info.height;
  3383. texture.isReady = true;
  3384. }, null, null, true);
  3385. } else {
  3386. cascadeLoad(rootUrl, 0, [], scene, function (imgs) {
  3387. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  3388. var height = width;
  3389. _this._workingCanvas.width = width;
  3390. _this._workingCanvas.height = height;
  3391. var faces = [
  3392. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3393. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3394. ];
  3395. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3396. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3397. for (var index = 0; index < faces.length; index++) {
  3398. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3399. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  3400. }
  3401. if (!noMipmap) {
  3402. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3403. }
  3404. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3405. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  3406. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3407. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3408. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3409. _this._activeTexturesCache = [];
  3410. texture._width = width;
  3411. texture._height = height;
  3412. texture.isReady = true;
  3413. }, extensions);
  3414. }
  3415. return texture;
  3416. };
  3417. Engine.prototype._releaseTexture = function (texture) {
  3418. var gl = this._gl;
  3419. if (texture._framebuffer) {
  3420. gl.deleteFramebuffer(texture._framebuffer);
  3421. }
  3422. if (texture._depthBuffer) {
  3423. gl.deleteRenderbuffer(texture._depthBuffer);
  3424. }
  3425. gl.deleteTexture(texture);
  3426. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3427. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3428. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3429. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3430. this._activeTexturesCache[channel] = null;
  3431. }
  3432. var index = this._loadedTexturesCache.indexOf(texture);
  3433. if (index !== -1) {
  3434. this._loadedTexturesCache.splice(index, 1);
  3435. }
  3436. };
  3437. Engine.prototype.bindSamplers = function (effect) {
  3438. this._gl.useProgram(effect.getProgram());
  3439. var samplers = effect.getSamplers();
  3440. for (var index = 0; index < samplers.length; index++) {
  3441. var uniform = effect.getUniform(samplers[index]);
  3442. this._gl.uniform1i(uniform, index);
  3443. }
  3444. this._currentEffect = null;
  3445. };
  3446. Engine.prototype._bindTexture = function (channel, texture) {
  3447. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3448. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3449. this._activeTexturesCache[channel] = null;
  3450. };
  3451. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  3452. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3453. };
  3454. Engine.prototype.setTexture = function (channel, texture) {
  3455. if (channel < 0) {
  3456. return;
  3457. }
  3458. if (!texture || !texture.isReady()) {
  3459. if (this._activeTexturesCache[channel] != null) {
  3460. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3461. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3462. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3463. this._activeTexturesCache[channel] = null;
  3464. }
  3465. return;
  3466. }
  3467. if (texture instanceof BABYLON.VideoTexture) {
  3468. if (texture.update()) {
  3469. this._activeTexturesCache[channel] = null;
  3470. }
  3471. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  3472. texture.delayLoad();
  3473. return;
  3474. }
  3475. if (this._activeTexturesCache[channel] == texture) {
  3476. return;
  3477. }
  3478. this._activeTexturesCache[channel] = texture;
  3479. var internalTexture = texture.getInternalTexture();
  3480. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3481. if (internalTexture.isCube) {
  3482. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3483. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3484. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3485. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3486. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3487. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3488. }
  3489. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3490. } else {
  3491. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  3492. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3493. internalTexture._cachedWrapU = texture.wrapU;
  3494. switch (texture.wrapU) {
  3495. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3496. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3497. break;
  3498. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3499. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3500. break;
  3501. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3502. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  3503. break;
  3504. }
  3505. }
  3506. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3507. internalTexture._cachedWrapV = texture.wrapV;
  3508. switch (texture.wrapV) {
  3509. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3510. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  3511. break;
  3512. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3513. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  3514. break;
  3515. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3516. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  3517. break;
  3518. }
  3519. }
  3520. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3521. }
  3522. };
  3523. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  3524. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3525. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  3526. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  3527. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  3528. }
  3529. };
  3530. Engine.prototype.readPixels = function (x, y, width, height) {
  3531. var data = new Uint8Array(height * width * 4);
  3532. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  3533. return data;
  3534. };
  3535. Engine.prototype.dispose = function () {
  3536. this.hideLoadingUI();
  3537. this.stopRenderLoop();
  3538. while (this.scenes.length) {
  3539. this.scenes[0].dispose();
  3540. }
  3541. for (var name in this._compiledEffects) {
  3542. this._gl.deleteProgram(this._compiledEffects[name]._program);
  3543. }
  3544. for (var i in this._vertexAttribArrays) {
  3545. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3546. continue;
  3547. }
  3548. this._gl.disableVertexAttribArray(i);
  3549. }
  3550. window.removeEventListener("blur", this._onBlur);
  3551. window.removeEventListener("focus", this._onFocus);
  3552. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  3553. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  3554. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  3555. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  3556. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  3557. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  3558. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  3559. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  3560. };
  3561. Engine.prototype.displayLoadingUI = function () {
  3562. var _this = this;
  3563. this._loadingDiv = document.createElement("div");
  3564. this._loadingDiv.style.opacity = "0";
  3565. this._loadingDiv.style.transition = "opacity 1.5s ease";
  3566. this._loadingTextDiv = document.createElement("div");
  3567. this._loadingTextDiv.style.position = "absolute";
  3568. this._loadingTextDiv.style.left = "0";
  3569. this._loadingTextDiv.style.top = "50%";
  3570. this._loadingTextDiv.style.marginTop = "80px";
  3571. this._loadingTextDiv.style.width = "100%";
  3572. this._loadingTextDiv.style.height = "20px";
  3573. this._loadingTextDiv.style.fontFamily = "Arial";
  3574. this._loadingTextDiv.style.fontSize = "14px";
  3575. this._loadingTextDiv.style.color = "white";
  3576. this._loadingTextDiv.style.textAlign = "center";
  3577. this._loadingTextDiv.innerHTML = "Loading";
  3578. this._loadingDiv.appendChild(this._loadingTextDiv);
  3579. var imgBack = new Image();
  3580. 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==";
  3581. imgBack.style.position = "absolute";
  3582. imgBack.style.left = "50%";
  3583. imgBack.style.top = "50%";
  3584. imgBack.style.marginLeft = "-50px";
  3585. imgBack.style.marginTop = "-50px";
  3586. imgBack.style.transition = "transform 1.0s ease";
  3587. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  3588. var deg = 360;
  3589. var onTransitionEnd = function () {
  3590. deg += 360;
  3591. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  3592. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  3593. };
  3594. imgBack.addEventListener("transitionend", onTransitionEnd);
  3595. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  3596. this._loadingDiv.appendChild(imgBack);
  3597. var imgFront = new Image();
  3598. 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=";
  3599. imgFront.style.position = "absolute";
  3600. imgFront.style.left = "50%";
  3601. imgFront.style.top = "50%";
  3602. imgFront.style.marginLeft = "-50px";
  3603. imgFront.style.marginTop = "-50px";
  3604. this._loadingDiv.appendChild(imgFront);
  3605. this._resizeLoadingUI = function () {
  3606. var canvasRect = _this.getRenderingCanvasClientRect();
  3607. _this._loadingDiv.style.position = "absolute";
  3608. _this._loadingDiv.style.left = canvasRect.left + "px";
  3609. _this._loadingDiv.style.top = canvasRect.top + "px";
  3610. _this._loadingDiv.style.width = canvasRect.width + "px";
  3611. _this._loadingDiv.style.height = canvasRect.height + "px";
  3612. };
  3613. this._resizeLoadingUI();
  3614. window.addEventListener("resize", this._resizeLoadingUI);
  3615. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3616. document.body.appendChild(this._loadingDiv);
  3617. setTimeout(function () {
  3618. _this._loadingDiv.style.opacity = "1";
  3619. imgBack.style.transform = "rotateZ(360deg)";
  3620. imgBack.style.webkitTransform = "rotateZ(360deg)";
  3621. }, 0);
  3622. };
  3623. Object.defineProperty(Engine.prototype, "loadingUIText", {
  3624. set: function (text) {
  3625. if (!this._loadingDiv) {
  3626. return;
  3627. }
  3628. this._loadingTextDiv.innerHTML = text;
  3629. },
  3630. enumerable: true,
  3631. configurable: true
  3632. });
  3633. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  3634. get: function () {
  3635. return this._loadingDivBackgroundColor;
  3636. },
  3637. set: function (color) {
  3638. this._loadingDivBackgroundColor = color;
  3639. if (!this._loadingDiv) {
  3640. return;
  3641. }
  3642. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3643. },
  3644. enumerable: true,
  3645. configurable: true
  3646. });
  3647. Engine.prototype.hideLoadingUI = function () {
  3648. var _this = this;
  3649. if (!this._loadingDiv) {
  3650. return;
  3651. }
  3652. var onTransitionEnd = function () {
  3653. if (!_this._loadingDiv) {
  3654. return;
  3655. }
  3656. document.body.removeChild(_this._loadingDiv);
  3657. window.removeEventListener("resize", _this._resizeLoadingUI);
  3658. _this._loadingDiv = null;
  3659. };
  3660. this._loadingDiv.style.opacity = "0";
  3661. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  3662. };
  3663. Engine.isSupported = function () {
  3664. try {
  3665. var tempcanvas = document.createElement("canvas");
  3666. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  3667. return gl != null && !!window.WebGLRenderingContext;
  3668. } catch (e) {
  3669. return false;
  3670. }
  3671. };
  3672. Engine._ALPHA_DISABLE = 0;
  3673. Engine._ALPHA_ADD = 1;
  3674. Engine._ALPHA_COMBINE = 2;
  3675. Engine._DELAYLOADSTATE_NONE = 0;
  3676. Engine._DELAYLOADSTATE_LOADED = 1;
  3677. Engine._DELAYLOADSTATE_LOADING = 2;
  3678. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  3679. Engine.Epsilon = 0.001;
  3680. Engine.CollisionsEpsilon = 0.001;
  3681. Engine.ShadersRepository = "Babylon/Shaders/";
  3682. return Engine;
  3683. })();
  3684. BABYLON.Engine = Engine;
  3685. })(BABYLON || (BABYLON = {}));
  3686. var BABYLON;
  3687. (function (BABYLON) {
  3688. var Node = (function () {
  3689. function Node(name, scene) {
  3690. this.state = "";
  3691. this.animations = new Array();
  3692. this._childrenFlag = -1;
  3693. this._isEnabled = true;
  3694. this._isReady = true;
  3695. this._currentRenderId = -1;
  3696. this.name = name;
  3697. this.id = name;
  3698. this._scene = scene;
  3699. this._initCache();
  3700. }
  3701. Node.prototype.getScene = function () {
  3702. return this._scene;
  3703. };
  3704. Node.prototype.getEngine = function () {
  3705. return this._scene.getEngine();
  3706. };
  3707. Node.prototype.getWorldMatrix = function () {
  3708. return BABYLON.Matrix.Identity();
  3709. };
  3710. Node.prototype._initCache = function () {
  3711. this._cache = {};
  3712. this._cache.parent = undefined;
  3713. };
  3714. Node.prototype.updateCache = function (force) {
  3715. if (!force && this.isSynchronized())
  3716. return;
  3717. this._cache.parent = this.parent;
  3718. this._updateCache();
  3719. };
  3720. Node.prototype._updateCache = function (ignoreParentClass) {
  3721. };
  3722. Node.prototype._isSynchronized = function () {
  3723. return true;
  3724. };
  3725. Node.prototype.isSynchronizedWithParent = function () {
  3726. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  3727. };
  3728. Node.prototype.isSynchronized = function (updateCache) {
  3729. var check = this.hasNewParent();
  3730. check = check || !this.isSynchronizedWithParent();
  3731. check = check || !this._isSynchronized();
  3732. if (updateCache)
  3733. this.updateCache(true);
  3734. return !check;
  3735. };
  3736. Node.prototype.hasNewParent = function (update) {
  3737. if (this._cache.parent === this.parent)
  3738. return false;
  3739. if (update)
  3740. this._cache.parent = this.parent;
  3741. return true;
  3742. };
  3743. Node.prototype.isReady = function () {
  3744. return this._isReady;
  3745. };
  3746. Node.prototype.isEnabled = function () {
  3747. if (!this._isEnabled) {
  3748. return false;
  3749. }
  3750. if (this.parent) {
  3751. return this.parent.isEnabled();
  3752. }
  3753. return true;
  3754. };
  3755. Node.prototype.setEnabled = function (value) {
  3756. this._isEnabled = value;
  3757. };
  3758. Node.prototype.isDescendantOf = function (ancestor) {
  3759. if (this.parent) {
  3760. if (this.parent === ancestor) {
  3761. return true;
  3762. }
  3763. return this.parent.isDescendantOf(ancestor);
  3764. }
  3765. return false;
  3766. };
  3767. Node.prototype._getDescendants = function (list, results) {
  3768. for (var index = 0; index < list.length; index++) {
  3769. var item = list[index];
  3770. if (item.isDescendantOf(this)) {
  3771. results.push(item);
  3772. }
  3773. }
  3774. };
  3775. Node.prototype.getDescendants = function () {
  3776. var results = [];
  3777. this._getDescendants(this._scene.meshes, results);
  3778. this._getDescendants(this._scene.lights, results);
  3779. this._getDescendants(this._scene.cameras, results);
  3780. return results;
  3781. };
  3782. Node.prototype._setReady = function (state) {
  3783. if (state == this._isReady) {
  3784. return;
  3785. }
  3786. if (!state) {
  3787. this._isReady = false;
  3788. return;
  3789. }
  3790. this._isReady = true;
  3791. if (this.onReady) {
  3792. this.onReady(this);
  3793. }
  3794. };
  3795. return Node;
  3796. })();
  3797. BABYLON.Node = Node;
  3798. })(BABYLON || (BABYLON = {}));
  3799. var BABYLON;
  3800. (function (BABYLON) {
  3801. var BoundingSphere = (function () {
  3802. function BoundingSphere(minimum, maximum) {
  3803. this.minimum = minimum;
  3804. this.maximum = maximum;
  3805. this._tempRadiusVector = BABYLON.Vector3.Zero();
  3806. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  3807. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  3808. this.radius = distance * 0.5;
  3809. this.centerWorld = BABYLON.Vector3.Zero();
  3810. this._update(BABYLON.Matrix.Identity());
  3811. }
  3812. BoundingSphere.prototype._update = function (world) {
  3813. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  3814. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  3815. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  3816. };
  3817. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  3818. for (var i = 0; i < 6; i++) {
  3819. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  3820. return false;
  3821. }
  3822. return true;
  3823. };
  3824. BoundingSphere.prototype.intersectsPoint = function (point) {
  3825. var x = this.centerWorld.x - point.x;
  3826. var y = this.centerWorld.y - point.y;
  3827. var z = this.centerWorld.z - point.z;
  3828. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3829. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  3830. return false;
  3831. return true;
  3832. };
  3833. BoundingSphere.Intersects = function (sphere0, sphere1) {
  3834. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  3835. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  3836. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  3837. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3838. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  3839. return false;
  3840. return true;
  3841. };
  3842. return BoundingSphere;
  3843. })();
  3844. BABYLON.BoundingSphere = BoundingSphere;
  3845. })(BABYLON || (BABYLON = {}));
  3846. var BABYLON;
  3847. (function (BABYLON) {
  3848. var BoundingBox = (function () {
  3849. function BoundingBox(minimum, maximum) {
  3850. this.minimum = minimum;
  3851. this.maximum = maximum;
  3852. this.vectors = new Array();
  3853. this.vectorsWorld = new Array();
  3854. this.vectors.push(this.minimum.clone());
  3855. this.vectors.push(this.maximum.clone());
  3856. this.vectors.push(this.minimum.clone());
  3857. this.vectors[2].x = this.maximum.x;
  3858. this.vectors.push(this.minimum.clone());
  3859. this.vectors[3].y = this.maximum.y;
  3860. this.vectors.push(this.minimum.clone());
  3861. this.vectors[4].z = this.maximum.z;
  3862. this.vectors.push(this.maximum.clone());
  3863. this.vectors[5].z = this.minimum.z;
  3864. this.vectors.push(this.maximum.clone());
  3865. this.vectors[6].x = this.minimum.x;
  3866. this.vectors.push(this.maximum.clone());
  3867. this.vectors[7].y = this.minimum.y;
  3868. this.center = this.maximum.add(this.minimum).scale(0.5);
  3869. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  3870. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  3871. for (var index = 0; index < this.vectors.length; index++) {
  3872. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  3873. }
  3874. this.minimumWorld = BABYLON.Vector3.Zero();
  3875. this.maximumWorld = BABYLON.Vector3.Zero();
  3876. this._update(BABYLON.Matrix.Identity());
  3877. }
  3878. BoundingBox.prototype.getWorldMatrix = function () {
  3879. return this._worldMatrix;
  3880. };
  3881. BoundingBox.prototype._update = function (world) {
  3882. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  3883. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  3884. for (var index = 0; index < this.vectors.length; index++) {
  3885. var v = this.vectorsWorld[index];
  3886. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  3887. if (v.x < this.minimumWorld.x)
  3888. this.minimumWorld.x = v.x;
  3889. if (v.y < this.minimumWorld.y)
  3890. this.minimumWorld.y = v.y;
  3891. if (v.z < this.minimumWorld.z)
  3892. this.minimumWorld.z = v.z;
  3893. if (v.x > this.maximumWorld.x)
  3894. this.maximumWorld.x = v.x;
  3895. if (v.y > this.maximumWorld.y)
  3896. this.maximumWorld.y = v.y;
  3897. if (v.z > this.maximumWorld.z)
  3898. this.maximumWorld.z = v.z;
  3899. }
  3900. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  3901. this.center.scaleInPlace(0.5);
  3902. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  3903. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  3904. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  3905. this._worldMatrix = world;
  3906. };
  3907. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  3908. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  3909. };
  3910. BoundingBox.prototype.intersectsPoint = function (point) {
  3911. var delta = BABYLON.Engine.Epsilon;
  3912. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  3913. return false;
  3914. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  3915. return false;
  3916. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  3917. return false;
  3918. return true;
  3919. };
  3920. BoundingBox.prototype.intersectsSphere = function (sphere) {
  3921. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  3922. };
  3923. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  3924. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  3925. return false;
  3926. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  3927. return false;
  3928. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  3929. return false;
  3930. return true;
  3931. };
  3932. BoundingBox.Intersects = function (box0, box1) {
  3933. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  3934. return false;
  3935. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  3936. return false;
  3937. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  3938. return false;
  3939. return true;
  3940. };
  3941. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  3942. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  3943. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  3944. return (num <= (sphereRadius * sphereRadius));
  3945. };
  3946. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  3947. for (var p = 0; p < 6; p++) {
  3948. var inCount = 8;
  3949. for (var i = 0; i < 8; i++) {
  3950. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  3951. --inCount;
  3952. } else {
  3953. break;
  3954. }
  3955. }
  3956. if (inCount == 0)
  3957. return false;
  3958. }
  3959. return true;
  3960. };
  3961. return BoundingBox;
  3962. })();
  3963. BABYLON.BoundingBox = BoundingBox;
  3964. })(BABYLON || (BABYLON = {}));
  3965. var BABYLON;
  3966. (function (BABYLON) {
  3967. var computeBoxExtents = function (axis, box) {
  3968. var p = BABYLON.Vector3.Dot(box.center, axis);
  3969. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  3970. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  3971. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  3972. var r = r0 + r1 + r2;
  3973. return {
  3974. min: p - r,
  3975. max: p + r
  3976. };
  3977. };
  3978. var extentsOverlap = function (min0, max0, min1, max1) {
  3979. return !(min0 > max1 || min1 > max0);
  3980. };
  3981. var axisOverlap = function (axis, box0, box1) {
  3982. var result0 = computeBoxExtents(axis, box0);
  3983. var result1 = computeBoxExtents(axis, box1);
  3984. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  3985. };
  3986. var BoundingInfo = (function () {
  3987. function BoundingInfo(minimum, maximum) {
  3988. this.minimum = minimum;
  3989. this.maximum = maximum;
  3990. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  3991. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  3992. }
  3993. BoundingInfo.prototype._update = function (world) {
  3994. this.boundingBox._update(world);
  3995. this.boundingSphere._update(world);
  3996. };
  3997. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  3998. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  3999. return false;
  4000. return this.boundingBox.isInFrustum(frustumPlanes);
  4001. };
  4002. BoundingInfo.prototype._checkCollision = function (collider) {
  4003. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  4004. };
  4005. BoundingInfo.prototype.intersectsPoint = function (point) {
  4006. if (!this.boundingSphere.centerWorld) {
  4007. return false;
  4008. }
  4009. if (!this.boundingSphere.intersectsPoint(point)) {
  4010. return false;
  4011. }
  4012. if (!this.boundingBox.intersectsPoint(point)) {
  4013. return false;
  4014. }
  4015. return true;
  4016. };
  4017. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  4018. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  4019. return false;
  4020. }
  4021. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  4022. return false;
  4023. }
  4024. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  4025. return false;
  4026. }
  4027. if (!precise) {
  4028. return true;
  4029. }
  4030. var box0 = this.boundingBox;
  4031. var box1 = boundingInfo.boundingBox;
  4032. if (!axisOverlap(box0.directions[0], box0, box1))
  4033. return false;
  4034. if (!axisOverlap(box0.directions[1], box0, box1))
  4035. return false;
  4036. if (!axisOverlap(box0.directions[2], box0, box1))
  4037. return false;
  4038. if (!axisOverlap(box1.directions[0], box0, box1))
  4039. return false;
  4040. if (!axisOverlap(box1.directions[1], box0, box1))
  4041. return false;
  4042. if (!axisOverlap(box1.directions[2], box0, box1))
  4043. return false;
  4044. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  4045. return false;
  4046. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  4047. return false;
  4048. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  4049. return false;
  4050. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  4051. return false;
  4052. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  4053. return false;
  4054. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  4055. return false;
  4056. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  4057. return false;
  4058. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  4059. return false;
  4060. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  4061. return false;
  4062. return true;
  4063. };
  4064. return BoundingInfo;
  4065. })();
  4066. BABYLON.BoundingInfo = BoundingInfo;
  4067. })(BABYLON || (BABYLON = {}));
  4068. var __extends = this.__extends || function (d, b) {
  4069. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4070. function __() { this.constructor = d; }
  4071. __.prototype = b.prototype;
  4072. d.prototype = new __();
  4073. };
  4074. var BABYLON;
  4075. (function (BABYLON) {
  4076. var Light = (function (_super) {
  4077. __extends(Light, _super);
  4078. function Light(name, scene) {
  4079. _super.call(this, name, scene);
  4080. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  4081. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  4082. this.intensity = 1.0;
  4083. this.range = Number.MAX_VALUE;
  4084. this.includedOnlyMeshes = new Array();
  4085. this.excludedMeshes = new Array();
  4086. this._excludedMeshesIds = new Array();
  4087. this._includedOnlyMeshesIds = new Array();
  4088. scene.lights.push(this);
  4089. }
  4090. Light.prototype.getShadowGenerator = function () {
  4091. return this._shadowGenerator;
  4092. };
  4093. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  4094. };
  4095. Light.prototype._getWorldMatrix = function () {
  4096. return BABYLON.Matrix.Identity();
  4097. };
  4098. Light.prototype.canAffectMesh = function (mesh) {
  4099. if (!mesh) {
  4100. return true;
  4101. }
  4102. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  4103. return false;
  4104. }
  4105. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  4106. return false;
  4107. }
  4108. return true;
  4109. };
  4110. Light.prototype.getWorldMatrix = function () {
  4111. this._currentRenderId = this.getScene().getRenderId();
  4112. var worldMatrix = this._getWorldMatrix();
  4113. if (this.parent && this.parent.getWorldMatrix) {
  4114. if (!this._parentedWorldMatrix) {
  4115. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4116. }
  4117. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4118. return this._parentedWorldMatrix;
  4119. }
  4120. return worldMatrix;
  4121. };
  4122. Light.prototype.dispose = function () {
  4123. if (this._shadowGenerator) {
  4124. this._shadowGenerator.dispose();
  4125. this._shadowGenerator = null;
  4126. }
  4127. var index = this.getScene().lights.indexOf(this);
  4128. this.getScene().lights.splice(index, 1);
  4129. };
  4130. return Light;
  4131. })(BABYLON.Node);
  4132. BABYLON.Light = Light;
  4133. })(BABYLON || (BABYLON = {}));
  4134. var __extends = this.__extends || function (d, b) {
  4135. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4136. function __() { this.constructor = d; }
  4137. __.prototype = b.prototype;
  4138. d.prototype = new __();
  4139. };
  4140. var BABYLON;
  4141. (function (BABYLON) {
  4142. var PointLight = (function (_super) {
  4143. __extends(PointLight, _super);
  4144. function PointLight(name, position, scene) {
  4145. _super.call(this, name, scene);
  4146. this.position = position;
  4147. }
  4148. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  4149. if (this.parent && this.parent.getWorldMatrix) {
  4150. if (!this._transformedPosition) {
  4151. this._transformedPosition = BABYLON.Vector3.Zero();
  4152. }
  4153. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4154. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  4155. return;
  4156. }
  4157. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  4158. };
  4159. PointLight.prototype.getShadowGenerator = function () {
  4160. return null;
  4161. };
  4162. PointLight.prototype._getWorldMatrix = function () {
  4163. if (!this._worldMatrix) {
  4164. this._worldMatrix = BABYLON.Matrix.Identity();
  4165. }
  4166. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4167. return this._worldMatrix;
  4168. };
  4169. return PointLight;
  4170. })(BABYLON.Light);
  4171. BABYLON.PointLight = PointLight;
  4172. })(BABYLON || (BABYLON = {}));
  4173. var __extends = this.__extends || function (d, b) {
  4174. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4175. function __() { this.constructor = d; }
  4176. __.prototype = b.prototype;
  4177. d.prototype = new __();
  4178. };
  4179. var BABYLON;
  4180. (function (BABYLON) {
  4181. var SpotLight = (function (_super) {
  4182. __extends(SpotLight, _super);
  4183. function SpotLight(name, position, direction, angle, exponent, scene) {
  4184. _super.call(this, name, scene);
  4185. this.position = position;
  4186. this.direction = direction;
  4187. this.angle = angle;
  4188. this.exponent = exponent;
  4189. }
  4190. SpotLight.prototype.setDirectionToTarget = function (target) {
  4191. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4192. return this.direction;
  4193. };
  4194. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  4195. var normalizeDirection;
  4196. if (this.parent && this.parent.getWorldMatrix) {
  4197. if (!this._transformedDirection) {
  4198. this._transformedDirection = BABYLON.Vector3.Zero();
  4199. }
  4200. if (!this._transformedPosition) {
  4201. this._transformedPosition = BABYLON.Vector3.Zero();
  4202. }
  4203. var parentWorldMatrix = this.parent.getWorldMatrix();
  4204. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  4205. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  4206. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  4207. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  4208. } else {
  4209. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  4210. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4211. }
  4212. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  4213. };
  4214. SpotLight.prototype._getWorldMatrix = function () {
  4215. if (!this._worldMatrix) {
  4216. this._worldMatrix = BABYLON.Matrix.Identity();
  4217. }
  4218. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4219. return this._worldMatrix;
  4220. };
  4221. return SpotLight;
  4222. })(BABYLON.Light);
  4223. BABYLON.SpotLight = SpotLight;
  4224. })(BABYLON || (BABYLON = {}));
  4225. var __extends = this.__extends || function (d, b) {
  4226. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4227. function __() { this.constructor = d; }
  4228. __.prototype = b.prototype;
  4229. d.prototype = new __();
  4230. };
  4231. var BABYLON;
  4232. (function (BABYLON) {
  4233. var DirectionalLight = (function (_super) {
  4234. __extends(DirectionalLight, _super);
  4235. function DirectionalLight(name, direction, scene) {
  4236. _super.call(this, name, scene);
  4237. this.direction = direction;
  4238. this.position = direction.scale(-1);
  4239. }
  4240. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  4241. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4242. return this.direction;
  4243. };
  4244. DirectionalLight.prototype._computeTransformedPosition = function () {
  4245. if (this.parent && this.parent.getWorldMatrix) {
  4246. if (!this._transformedPosition) {
  4247. this._transformedPosition = BABYLON.Vector3.Zero();
  4248. }
  4249. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4250. return true;
  4251. }
  4252. return false;
  4253. };
  4254. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  4255. if (this.parent && this.parent.getWorldMatrix) {
  4256. if (!this._transformedDirection) {
  4257. this._transformedDirection = BABYLON.Vector3.Zero();
  4258. }
  4259. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  4260. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  4261. return;
  4262. }
  4263. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  4264. };
  4265. DirectionalLight.prototype._getWorldMatrix = function () {
  4266. if (!this._worldMatrix) {
  4267. this._worldMatrix = BABYLON.Matrix.Identity();
  4268. }
  4269. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4270. return this._worldMatrix;
  4271. };
  4272. return DirectionalLight;
  4273. })(BABYLON.Light);
  4274. BABYLON.DirectionalLight = DirectionalLight;
  4275. })(BABYLON || (BABYLON = {}));
  4276. var BABYLON;
  4277. (function (BABYLON) {
  4278. var ShadowGenerator = (function () {
  4279. function ShadowGenerator(mapSize, light) {
  4280. var _this = this;
  4281. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4282. this._darkness = 0;
  4283. this._transparencyShadow = false;
  4284. this._viewMatrix = BABYLON.Matrix.Zero();
  4285. this._projectionMatrix = BABYLON.Matrix.Zero();
  4286. this._transformMatrix = BABYLON.Matrix.Zero();
  4287. this._worldViewProjection = BABYLON.Matrix.Zero();
  4288. this._light = light;
  4289. this._scene = light.getScene();
  4290. light._shadowGenerator = this;
  4291. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  4292. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4293. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4294. this._shadowMap.renderParticles = false;
  4295. var renderSubMesh = function (subMesh) {
  4296. var mesh = subMesh.getRenderingMesh();
  4297. var scene = _this._scene;
  4298. var engine = scene.getEngine();
  4299. engine.setState(subMesh.getMaterial().backFaceCulling);
  4300. var batch = mesh._getInstancesRenderList(subMesh._id);
  4301. if (batch.mustReturn) {
  4302. return;
  4303. }
  4304. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  4305. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  4306. engine.enableEffect(_this._effect);
  4307. mesh._bind(subMesh, _this._effect, false);
  4308. var material = subMesh.getMaterial();
  4309. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  4310. if (material && material.needAlphaTesting()) {
  4311. var alphaTexture = material.getAlphaTestTexture();
  4312. _this._effect.setTexture("diffuseSampler", alphaTexture);
  4313. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  4314. }
  4315. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  4316. if (useBones) {
  4317. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  4318. }
  4319. if (hardwareInstancedRendering) {
  4320. mesh._renderWithInstances(subMesh, false, batch, _this._effect, engine);
  4321. } else {
  4322. if (batch.renderSelf[subMesh._id]) {
  4323. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  4324. mesh._draw(subMesh, true);
  4325. }
  4326. if (batch.visibleInstances[subMesh._id]) {
  4327. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  4328. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  4329. _this._effect.setMatrix("world", instance.getWorldMatrix());
  4330. mesh._draw(subMesh, true);
  4331. }
  4332. }
  4333. }
  4334. } else {
  4335. _this._shadowMap.resetRefreshCounter();
  4336. }
  4337. };
  4338. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  4339. var index;
  4340. for (index = 0; index < opaqueSubMeshes.length; index++) {
  4341. renderSubMesh(opaqueSubMeshes.data[index]);
  4342. }
  4343. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  4344. renderSubMesh(alphaTestSubMeshes.data[index]);
  4345. }
  4346. if (_this._transparencyShadow) {
  4347. for (index = 0; index < transparentSubMeshes.length; index++) {
  4348. renderSubMesh(transparentSubMeshes.data[index]);
  4349. }
  4350. }
  4351. };
  4352. }
  4353. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  4354. get: function () {
  4355. return ShadowGenerator._FILTER_NONE;
  4356. },
  4357. enumerable: true,
  4358. configurable: true
  4359. });
  4360. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  4361. get: function () {
  4362. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  4363. },
  4364. enumerable: true,
  4365. configurable: true
  4366. });
  4367. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  4368. get: function () {
  4369. return ShadowGenerator._FILTER_POISSONSAMPLING;
  4370. },
  4371. enumerable: true,
  4372. configurable: true
  4373. });
  4374. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  4375. get: function () {
  4376. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4377. },
  4378. set: function (value) {
  4379. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  4380. },
  4381. enumerable: true,
  4382. configurable: true
  4383. });
  4384. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  4385. get: function () {
  4386. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  4387. },
  4388. set: function (value) {
  4389. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  4390. },
  4391. enumerable: true,
  4392. configurable: true
  4393. });
  4394. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  4395. var defines = [];
  4396. if (this.useVarianceShadowMap) {
  4397. defines.push("#define VSM");
  4398. }
  4399. var attribs = [BABYLON.VertexBuffer.PositionKind];
  4400. var mesh = subMesh.getMesh();
  4401. var material = subMesh.getMaterial();
  4402. if (material && material.needAlphaTesting()) {
  4403. defines.push("#define ALPHATEST");
  4404. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  4405. attribs.push(BABYLON.VertexBuffer.UVKind);
  4406. defines.push("#define UV1");
  4407. }
  4408. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  4409. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  4410. defines.push("#define UV2");
  4411. }
  4412. }
  4413. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  4414. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  4415. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  4416. defines.push("#define BONES");
  4417. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  4418. }
  4419. if (useInstances) {
  4420. defines.push("#define INSTANCES");
  4421. attribs.push("world0");
  4422. attribs.push("world1");
  4423. attribs.push("world2");
  4424. attribs.push("world3");
  4425. }
  4426. var join = defines.join("\n");
  4427. if (this._cachedDefines != join) {
  4428. this._cachedDefines = join;
  4429. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  4430. }
  4431. return this._effect.isReady();
  4432. };
  4433. ShadowGenerator.prototype.getShadowMap = function () {
  4434. return this._shadowMap;
  4435. };
  4436. ShadowGenerator.prototype.getLight = function () {
  4437. return this._light;
  4438. };
  4439. ShadowGenerator.prototype.getTransformMatrix = function () {
  4440. var lightPosition = this._light.position;
  4441. var lightDirection = this._light.direction;
  4442. if (this._light._computeTransformedPosition()) {
  4443. lightPosition = this._light._transformedPosition;
  4444. }
  4445. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  4446. this._cachedPosition = lightPosition.clone();
  4447. this._cachedDirection = lightDirection.clone();
  4448. var activeCamera = this._scene.activeCamera;
  4449. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  4450. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  4451. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  4452. }
  4453. return this._transformMatrix;
  4454. };
  4455. ShadowGenerator.prototype.getDarkness = function () {
  4456. return this._darkness;
  4457. };
  4458. ShadowGenerator.prototype.setDarkness = function (darkness) {
  4459. if (darkness >= 1.0)
  4460. this._darkness = 1.0;
  4461. else if (darkness <= 0.0)
  4462. this._darkness = 0.0;
  4463. else
  4464. this._darkness = darkness;
  4465. };
  4466. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  4467. this._transparencyShadow = hasShadow;
  4468. };
  4469. ShadowGenerator.prototype.dispose = function () {
  4470. this._shadowMap.dispose();
  4471. };
  4472. ShadowGenerator._FILTER_NONE = 0;
  4473. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  4474. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  4475. return ShadowGenerator;
  4476. })();
  4477. BABYLON.ShadowGenerator = ShadowGenerator;
  4478. })(BABYLON || (BABYLON = {}));
  4479. var __extends = this.__extends || function (d, b) {
  4480. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4481. function __() { this.constructor = d; }
  4482. __.prototype = b.prototype;
  4483. d.prototype = new __();
  4484. };
  4485. var BABYLON;
  4486. (function (BABYLON) {
  4487. var HemisphericLight = (function (_super) {
  4488. __extends(HemisphericLight, _super);
  4489. function HemisphericLight(name, direction, scene) {
  4490. _super.call(this, name, scene);
  4491. this.direction = direction;
  4492. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  4493. }
  4494. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  4495. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  4496. return this.direction;
  4497. };
  4498. HemisphericLight.prototype.getShadowGenerator = function () {
  4499. return null;
  4500. };
  4501. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  4502. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4503. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  4504. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  4505. };
  4506. HemisphericLight.prototype._getWorldMatrix = function () {
  4507. if (!this._worldMatrix) {
  4508. this._worldMatrix = BABYLON.Matrix.Identity();
  4509. }
  4510. return this._worldMatrix;
  4511. };
  4512. return HemisphericLight;
  4513. })(BABYLON.Light);
  4514. BABYLON.HemisphericLight = HemisphericLight;
  4515. })(BABYLON || (BABYLON = {}));
  4516. var BABYLON;
  4517. (function (BABYLON) {
  4518. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  4519. if (boxMin.x > sphereCenter.x + sphereRadius)
  4520. return false;
  4521. if (sphereCenter.x - sphereRadius > boxMax.x)
  4522. return false;
  4523. if (boxMin.y > sphereCenter.y + sphereRadius)
  4524. return false;
  4525. if (sphereCenter.y - sphereRadius > boxMax.y)
  4526. return false;
  4527. if (boxMin.z > sphereCenter.z + sphereRadius)
  4528. return false;
  4529. if (sphereCenter.z - sphereRadius > boxMax.z)
  4530. return false;
  4531. return true;
  4532. };
  4533. var getLowestRoot = function (a, b, c, maxR) {
  4534. var determinant = b * b - 4.0 * a * c;
  4535. var result = { root: 0, found: false };
  4536. if (determinant < 0)
  4537. return result;
  4538. var sqrtD = Math.sqrt(determinant);
  4539. var r1 = (-b - sqrtD) / (2.0 * a);
  4540. var r2 = (-b + sqrtD) / (2.0 * a);
  4541. if (r1 > r2) {
  4542. var temp = r2;
  4543. r2 = r1;
  4544. r1 = temp;
  4545. }
  4546. if (r1 > 0 && r1 < maxR) {
  4547. result.root = r1;
  4548. result.found = true;
  4549. return result;
  4550. }
  4551. if (r2 > 0 && r2 < maxR) {
  4552. result.root = r2;
  4553. result.found = true;
  4554. return result;
  4555. }
  4556. return result;
  4557. };
  4558. var Collider = (function () {
  4559. function Collider() {
  4560. this.radius = new BABYLON.Vector3(1, 1, 1);
  4561. this.retry = 0;
  4562. this.basePointWorld = BABYLON.Vector3.Zero();
  4563. this.velocityWorld = BABYLON.Vector3.Zero();
  4564. this.normalizedVelocity = BABYLON.Vector3.Zero();
  4565. this._collisionPoint = BABYLON.Vector3.Zero();
  4566. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  4567. this._tempVector = BABYLON.Vector3.Zero();
  4568. this._tempVector2 = BABYLON.Vector3.Zero();
  4569. this._tempVector3 = BABYLON.Vector3.Zero();
  4570. this._tempVector4 = BABYLON.Vector3.Zero();
  4571. this._edge = BABYLON.Vector3.Zero();
  4572. this._baseToVertex = BABYLON.Vector3.Zero();
  4573. this._destinationPoint = BABYLON.Vector3.Zero();
  4574. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  4575. this._displacementVector = BABYLON.Vector3.Zero();
  4576. }
  4577. Collider.prototype._initialize = function (source, dir, e) {
  4578. this.velocity = dir;
  4579. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  4580. this.basePoint = source;
  4581. source.multiplyToRef(this.radius, this.basePointWorld);
  4582. dir.multiplyToRef(this.radius, this.velocityWorld);
  4583. this.velocityWorldLength = this.velocityWorld.length();
  4584. this.epsilon = e;
  4585. this.collisionFound = false;
  4586. };
  4587. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  4588. pa.subtractToRef(point, this._tempVector);
  4589. pb.subtractToRef(point, this._tempVector2);
  4590. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  4591. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4592. if (d < 0)
  4593. return false;
  4594. pc.subtractToRef(point, this._tempVector3);
  4595. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  4596. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4597. if (d < 0)
  4598. return false;
  4599. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  4600. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4601. return d >= 0;
  4602. };
  4603. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  4604. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  4605. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  4606. if (distance > this.velocityWorldLength + max + sphereRadius) {
  4607. return false;
  4608. }
  4609. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  4610. return false;
  4611. return true;
  4612. };
  4613. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  4614. var t0;
  4615. var embeddedInPlane = false;
  4616. if (!subMesh._trianglePlanes) {
  4617. subMesh._trianglePlanes = [];
  4618. }
  4619. if (!subMesh._trianglePlanes[faceIndex]) {
  4620. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  4621. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  4622. }
  4623. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  4624. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  4625. return;
  4626. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  4627. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  4628. if (normalDotVelocity == 0) {
  4629. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  4630. return;
  4631. embeddedInPlane = true;
  4632. t0 = 0;
  4633. } else {
  4634. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4635. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4636. if (t0 > t1) {
  4637. var temp = t1;
  4638. t1 = t0;
  4639. t0 = temp;
  4640. }
  4641. if (t0 > 1.0 || t1 < 0.0)
  4642. return;
  4643. if (t0 < 0)
  4644. t0 = 0;
  4645. if (t0 > 1.0)
  4646. t0 = 1.0;
  4647. }
  4648. this._collisionPoint.copyFromFloats(0, 0, 0);
  4649. var found = false;
  4650. var t = 1.0;
  4651. if (!embeddedInPlane) {
  4652. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  4653. this.velocity.scaleToRef(t0, this._tempVector);
  4654. this._planeIntersectionPoint.addInPlace(this._tempVector);
  4655. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  4656. found = true;
  4657. t = t0;
  4658. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  4659. }
  4660. }
  4661. if (!found) {
  4662. var velocitySquaredLength = this.velocity.lengthSquared();
  4663. var a = velocitySquaredLength;
  4664. this.basePoint.subtractToRef(p1, this._tempVector);
  4665. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4666. var c = this._tempVector.lengthSquared() - 1.0;
  4667. var lowestRoot = getLowestRoot(a, b, c, t);
  4668. if (lowestRoot.found) {
  4669. t = lowestRoot.root;
  4670. found = true;
  4671. this._collisionPoint.copyFrom(p1);
  4672. }
  4673. this.basePoint.subtractToRef(p2, this._tempVector);
  4674. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4675. c = this._tempVector.lengthSquared() - 1.0;
  4676. lowestRoot = getLowestRoot(a, b, c, t);
  4677. if (lowestRoot.found) {
  4678. t = lowestRoot.root;
  4679. found = true;
  4680. this._collisionPoint.copyFrom(p2);
  4681. }
  4682. this.basePoint.subtractToRef(p3, this._tempVector);
  4683. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4684. c = this._tempVector.lengthSquared() - 1.0;
  4685. lowestRoot = getLowestRoot(a, b, c, t);
  4686. if (lowestRoot.found) {
  4687. t = lowestRoot.root;
  4688. found = true;
  4689. this._collisionPoint.copyFrom(p3);
  4690. }
  4691. p2.subtractToRef(p1, this._edge);
  4692. p1.subtractToRef(this.basePoint, this._baseToVertex);
  4693. var edgeSquaredLength = this._edge.lengthSquared();
  4694. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4695. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4696. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4697. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4698. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4699. lowestRoot = getLowestRoot(a, b, c, t);
  4700. if (lowestRoot.found) {
  4701. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4702. if (f >= 0.0 && f <= 1.0) {
  4703. t = lowestRoot.root;
  4704. found = true;
  4705. this._edge.scaleInPlace(f);
  4706. p1.addToRef(this._edge, this._collisionPoint);
  4707. }
  4708. }
  4709. p3.subtractToRef(p2, this._edge);
  4710. p2.subtractToRef(this.basePoint, this._baseToVertex);
  4711. edgeSquaredLength = this._edge.lengthSquared();
  4712. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4713. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4714. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4715. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4716. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4717. lowestRoot = getLowestRoot(a, b, c, t);
  4718. if (lowestRoot.found) {
  4719. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4720. if (f >= 0.0 && f <= 1.0) {
  4721. t = lowestRoot.root;
  4722. found = true;
  4723. this._edge.scaleInPlace(f);
  4724. p2.addToRef(this._edge, this._collisionPoint);
  4725. }
  4726. }
  4727. p1.subtractToRef(p3, this._edge);
  4728. p3.subtractToRef(this.basePoint, this._baseToVertex);
  4729. edgeSquaredLength = this._edge.lengthSquared();
  4730. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4731. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4732. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4733. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4734. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4735. lowestRoot = getLowestRoot(a, b, c, t);
  4736. if (lowestRoot.found) {
  4737. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4738. if (f >= 0.0 && f <= 1.0) {
  4739. t = lowestRoot.root;
  4740. found = true;
  4741. this._edge.scaleInPlace(f);
  4742. p3.addToRef(this._edge, this._collisionPoint);
  4743. }
  4744. }
  4745. }
  4746. if (found) {
  4747. var distToCollision = t * this.velocity.length();
  4748. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  4749. if (!this.intersectionPoint) {
  4750. this.intersectionPoint = this._collisionPoint.clone();
  4751. } else {
  4752. this.intersectionPoint.copyFrom(this._collisionPoint);
  4753. }
  4754. this.nearestDistance = distToCollision;
  4755. this.collisionFound = true;
  4756. this.collidedMesh = subMesh.getMesh();
  4757. }
  4758. }
  4759. };
  4760. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  4761. for (var i = indexStart; i < indexEnd; i += 3) {
  4762. var p1 = pts[indices[i] - decal];
  4763. var p2 = pts[indices[i + 1] - decal];
  4764. var p3 = pts[indices[i + 2] - decal];
  4765. this._testTriangle(i, subMesh, p3, p2, p1);
  4766. }
  4767. };
  4768. Collider.prototype._getResponse = function (pos, vel) {
  4769. pos.addToRef(vel, this._destinationPoint);
  4770. vel.scaleInPlace((this.nearestDistance / vel.length()));
  4771. this.basePoint.addToRef(vel, pos);
  4772. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  4773. this._slidePlaneNormal.normalize();
  4774. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  4775. pos.addInPlace(this._displacementVector);
  4776. this.intersectionPoint.addInPlace(this._displacementVector);
  4777. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  4778. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  4779. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  4780. };
  4781. return Collider;
  4782. })();
  4783. BABYLON.Collider = Collider;
  4784. })(BABYLON || (BABYLON = {}));
  4785. var __extends = this.__extends || function (d, b) {
  4786. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4787. function __() { this.constructor = d; }
  4788. __.prototype = b.prototype;
  4789. d.prototype = new __();
  4790. };
  4791. var BABYLON;
  4792. (function (BABYLON) {
  4793. var Camera = (function (_super) {
  4794. __extends(Camera, _super);
  4795. function Camera(name, position, scene) {
  4796. _super.call(this, name, scene);
  4797. this.position = position;
  4798. this.upVector = BABYLON.Vector3.Up();
  4799. this.orthoLeft = null;
  4800. this.orthoRight = null;
  4801. this.orthoBottom = null;
  4802. this.orthoTop = null;
  4803. this.fov = 0.8;
  4804. this.minZ = 1.0;
  4805. this.maxZ = 10000.0;
  4806. this.inertia = 0.9;
  4807. this.mode = Camera.PERSPECTIVE_CAMERA;
  4808. this.isIntermediate = false;
  4809. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  4810. this.subCameras = [];
  4811. this.layerMask = 0xFFFFFFFF;
  4812. this._computedViewMatrix = BABYLON.Matrix.Identity();
  4813. this._projectionMatrix = new BABYLON.Matrix();
  4814. this._postProcesses = new Array();
  4815. this._postProcessesTakenIndices = [];
  4816. scene.cameras.push(this);
  4817. if (!scene.activeCamera) {
  4818. scene.activeCamera = this;
  4819. }
  4820. }
  4821. Camera.prototype._initCache = function () {
  4822. _super.prototype._initCache.call(this);
  4823. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4824. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4825. this._cache.mode = undefined;
  4826. this._cache.minZ = undefined;
  4827. this._cache.maxZ = undefined;
  4828. this._cache.fov = undefined;
  4829. this._cache.aspectRatio = undefined;
  4830. this._cache.orthoLeft = undefined;
  4831. this._cache.orthoRight = undefined;
  4832. this._cache.orthoBottom = undefined;
  4833. this._cache.orthoTop = undefined;
  4834. this._cache.renderWidth = undefined;
  4835. this._cache.renderHeight = undefined;
  4836. };
  4837. Camera.prototype._updateCache = function (ignoreParentClass) {
  4838. if (!ignoreParentClass) {
  4839. _super.prototype._updateCache.call(this);
  4840. }
  4841. var engine = this.getEngine();
  4842. this._cache.position.copyFrom(this.position);
  4843. this._cache.upVector.copyFrom(this.upVector);
  4844. this._cache.mode = this.mode;
  4845. this._cache.minZ = this.minZ;
  4846. this._cache.maxZ = this.maxZ;
  4847. this._cache.fov = this.fov;
  4848. this._cache.aspectRatio = engine.getAspectRatio(this);
  4849. this._cache.orthoLeft = this.orthoLeft;
  4850. this._cache.orthoRight = this.orthoRight;
  4851. this._cache.orthoBottom = this.orthoBottom;
  4852. this._cache.orthoTop = this.orthoTop;
  4853. this._cache.renderWidth = engine.getRenderWidth();
  4854. this._cache.renderHeight = engine.getRenderHeight();
  4855. };
  4856. Camera.prototype._updateFromScene = function () {
  4857. this.updateCache();
  4858. this._update();
  4859. };
  4860. Camera.prototype._isSynchronized = function () {
  4861. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  4862. };
  4863. Camera.prototype._isSynchronizedViewMatrix = function () {
  4864. if (!_super.prototype._isSynchronized.call(this))
  4865. return false;
  4866. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  4867. };
  4868. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  4869. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  4870. if (!check) {
  4871. return false;
  4872. }
  4873. var engine = this.getEngine();
  4874. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4875. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  4876. } else {
  4877. 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();
  4878. }
  4879. return check;
  4880. };
  4881. Camera.prototype.attachControl = function (element) {
  4882. };
  4883. Camera.prototype.detachControl = function (element) {
  4884. };
  4885. Camera.prototype._update = function () {
  4886. };
  4887. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  4888. if (typeof insertAt === "undefined") { insertAt = null; }
  4889. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  4890. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  4891. return 0;
  4892. }
  4893. if (insertAt == null || insertAt < 0) {
  4894. this._postProcesses.push(postProcess);
  4895. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  4896. return this._postProcesses.length - 1;
  4897. }
  4898. var add = 0;
  4899. if (this._postProcesses[insertAt]) {
  4900. var start = this._postProcesses.length - 1;
  4901. for (var i = start; i >= insertAt + 1; --i) {
  4902. this._postProcesses[i + 1] = this._postProcesses[i];
  4903. }
  4904. add = 1;
  4905. }
  4906. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  4907. if (this._postProcessesTakenIndices[i] < insertAt) {
  4908. continue;
  4909. }
  4910. start = this._postProcessesTakenIndices.length - 1;
  4911. for (var j = start; j >= i; --j) {
  4912. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  4913. }
  4914. this._postProcessesTakenIndices[i] = insertAt;
  4915. break;
  4916. }
  4917. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  4918. this._postProcessesTakenIndices.push(insertAt);
  4919. }
  4920. var result = insertAt + add;
  4921. this._postProcesses[result] = postProcess;
  4922. return result;
  4923. };
  4924. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  4925. if (typeof atIndices === "undefined") { atIndices = null; }
  4926. var result = [];
  4927. if (!atIndices) {
  4928. var length = this._postProcesses.length;
  4929. for (var i = 0; i < length; i++) {
  4930. if (this._postProcesses[i] !== postProcess) {
  4931. continue;
  4932. }
  4933. delete this._postProcesses[i];
  4934. var index = this._postProcessesTakenIndices.indexOf(i);
  4935. this._postProcessesTakenIndices.splice(index, 1);
  4936. }
  4937. } else {
  4938. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  4939. for (i = 0; i < atIndices.length; i++) {
  4940. var foundPostProcess = this._postProcesses[atIndices[i]];
  4941. if (foundPostProcess !== postProcess) {
  4942. result.push(i);
  4943. continue;
  4944. }
  4945. delete this._postProcesses[atIndices[i]];
  4946. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  4947. this._postProcessesTakenIndices.splice(index, 1);
  4948. }
  4949. }
  4950. return result;
  4951. };
  4952. Camera.prototype.getWorldMatrix = function () {
  4953. if (!this._worldMatrix) {
  4954. this._worldMatrix = BABYLON.Matrix.Identity();
  4955. }
  4956. var viewMatrix = this.getViewMatrix();
  4957. viewMatrix.invertToRef(this._worldMatrix);
  4958. return this._worldMatrix;
  4959. };
  4960. Camera.prototype._getViewMatrix = function () {
  4961. return BABYLON.Matrix.Identity();
  4962. };
  4963. Camera.prototype.getViewMatrix = function () {
  4964. this._computedViewMatrix = this._computeViewMatrix();
  4965. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  4966. return this._computedViewMatrix;
  4967. }
  4968. if (!this._worldMatrix) {
  4969. this._worldMatrix = BABYLON.Matrix.Identity();
  4970. }
  4971. this._computedViewMatrix.invertToRef(this._worldMatrix);
  4972. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  4973. this._computedViewMatrix.invert();
  4974. this._currentRenderId = this.getScene().getRenderId();
  4975. return this._computedViewMatrix;
  4976. };
  4977. Camera.prototype._computeViewMatrix = function (force) {
  4978. if (!force && this._isSynchronizedViewMatrix()) {
  4979. return this._computedViewMatrix;
  4980. }
  4981. this._computedViewMatrix = this._getViewMatrix();
  4982. if (!this.parent || !this.parent.getWorldMatrix) {
  4983. this._currentRenderId = this.getScene().getRenderId();
  4984. }
  4985. return this._computedViewMatrix;
  4986. };
  4987. Camera.prototype.getProjectionMatrix = function (force) {
  4988. if (!force && this._isSynchronizedProjectionMatrix()) {
  4989. return this._projectionMatrix;
  4990. }
  4991. var engine = this.getEngine();
  4992. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4993. if (this.minZ <= 0) {
  4994. this.minZ = 0.1;
  4995. }
  4996. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  4997. return this._projectionMatrix;
  4998. }
  4999. var halfWidth = engine.getRenderWidth() / 2.0;
  5000. var halfHeight = engine.getRenderHeight() / 2.0;
  5001. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  5002. return this._projectionMatrix;
  5003. };
  5004. Camera.prototype.dispose = function () {
  5005. var index = this.getScene().cameras.indexOf(this);
  5006. this.getScene().cameras.splice(index, 1);
  5007. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5008. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  5009. }
  5010. };
  5011. Camera.PERSPECTIVE_CAMERA = 0;
  5012. Camera.ORTHOGRAPHIC_CAMERA = 1;
  5013. return Camera;
  5014. })(BABYLON.Node);
  5015. BABYLON.Camera = Camera;
  5016. })(BABYLON || (BABYLON = {}));
  5017. var __extends = this.__extends || function (d, b) {
  5018. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5019. function __() { this.constructor = d; }
  5020. __.prototype = b.prototype;
  5021. d.prototype = new __();
  5022. };
  5023. var BABYLON;
  5024. (function (BABYLON) {
  5025. var TargetCamera = (function (_super) {
  5026. __extends(TargetCamera, _super);
  5027. function TargetCamera(name, position, scene) {
  5028. _super.call(this, name, position, scene);
  5029. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5030. this.cameraRotation = new BABYLON.Vector2(0, 0);
  5031. this.rotation = new BABYLON.Vector3(0, 0, 0);
  5032. this.speed = 2.0;
  5033. this.noRotationConstraint = false;
  5034. this.lockedTarget = null;
  5035. this._currentTarget = BABYLON.Vector3.Zero();
  5036. this._viewMatrix = BABYLON.Matrix.Zero();
  5037. this._camMatrix = BABYLON.Matrix.Zero();
  5038. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  5039. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  5040. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  5041. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  5042. this._lookAtTemp = BABYLON.Matrix.Zero();
  5043. this._tempMatrix = BABYLON.Matrix.Zero();
  5044. }
  5045. TargetCamera.prototype._getLockedTargetPosition = function () {
  5046. if (!this.lockedTarget) {
  5047. return null;
  5048. }
  5049. return this.lockedTarget.position || this.lockedTarget;
  5050. };
  5051. TargetCamera.prototype._initCache = function () {
  5052. _super.prototype._initCache.call(this);
  5053. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5054. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5055. };
  5056. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  5057. if (!ignoreParentClass) {
  5058. _super.prototype._updateCache.call(this);
  5059. }
  5060. var lockedTargetPosition = this._getLockedTargetPosition();
  5061. if (!lockedTargetPosition) {
  5062. this._cache.lockedTarget = null;
  5063. } else {
  5064. if (!this._cache.lockedTarget) {
  5065. this._cache.lockedTarget = lockedTargetPosition.clone();
  5066. } else {
  5067. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  5068. }
  5069. }
  5070. this._cache.rotation.copyFrom(this.rotation);
  5071. };
  5072. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  5073. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  5074. return false;
  5075. }
  5076. var lockedTargetPosition = this._getLockedTargetPosition();
  5077. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  5078. };
  5079. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  5080. return this.speed * ((BABYLON.Tools.GetDeltaTime() / (BABYLON.Tools.GetFps() * 10.0)));
  5081. };
  5082. TargetCamera.prototype.setTarget = function (target) {
  5083. this.upVector.normalize();
  5084. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  5085. this._camMatrix.invert();
  5086. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  5087. var vDir = target.subtract(this.position);
  5088. if (vDir.x >= 0.0) {
  5089. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  5090. } else {
  5091. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  5092. }
  5093. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  5094. if (isNaN(this.rotation.x)) {
  5095. this.rotation.x = 0;
  5096. }
  5097. if (isNaN(this.rotation.y)) {
  5098. this.rotation.y = 0;
  5099. }
  5100. if (isNaN(this.rotation.z)) {
  5101. this.rotation.z = 0;
  5102. }
  5103. };
  5104. TargetCamera.prototype.getTarget = function () {
  5105. return this._currentTarget;
  5106. };
  5107. TargetCamera.prototype._decideIfNeedsToMove = function () {
  5108. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5109. };
  5110. TargetCamera.prototype._updatePosition = function () {
  5111. this.position.addInPlace(this.cameraDirection);
  5112. };
  5113. TargetCamera.prototype._update = function () {
  5114. var needToMove = this._decideIfNeedsToMove();
  5115. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5116. if (needToMove) {
  5117. this._updatePosition();
  5118. }
  5119. if (needToRotate) {
  5120. this.rotation.x += this.cameraRotation.x;
  5121. this.rotation.y += this.cameraRotation.y;
  5122. if (!this.noRotationConstraint) {
  5123. var limit = (Math.PI / 2) * 0.95;
  5124. if (this.rotation.x > limit)
  5125. this.rotation.x = limit;
  5126. if (this.rotation.x < -limit)
  5127. this.rotation.x = -limit;
  5128. }
  5129. }
  5130. if (needToMove) {
  5131. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  5132. this.cameraDirection.x = 0;
  5133. }
  5134. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  5135. this.cameraDirection.y = 0;
  5136. }
  5137. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  5138. this.cameraDirection.z = 0;
  5139. }
  5140. this.cameraDirection.scaleInPlace(this.inertia);
  5141. }
  5142. if (needToRotate) {
  5143. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  5144. this.cameraRotation.x = 0;
  5145. }
  5146. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  5147. this.cameraRotation.y = 0;
  5148. }
  5149. this.cameraRotation.scaleInPlace(this.inertia);
  5150. }
  5151. };
  5152. TargetCamera.prototype._getViewMatrix = function () {
  5153. if (!this.lockedTarget) {
  5154. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  5155. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  5156. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5157. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  5158. this._lookAtTemp.invert();
  5159. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  5160. } else {
  5161. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5162. }
  5163. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  5164. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  5165. } else {
  5166. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  5167. }
  5168. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  5169. return this._viewMatrix;
  5170. };
  5171. return TargetCamera;
  5172. })(BABYLON.Camera);
  5173. BABYLON.TargetCamera = TargetCamera;
  5174. })(BABYLON || (BABYLON = {}));
  5175. var __extends = this.__extends || function (d, b) {
  5176. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5177. function __() { this.constructor = d; }
  5178. __.prototype = b.prototype;
  5179. d.prototype = new __();
  5180. };
  5181. var BABYLON;
  5182. (function (BABYLON) {
  5183. var FollowCamera = (function (_super) {
  5184. __extends(FollowCamera, _super);
  5185. function FollowCamera(name, position, scene) {
  5186. _super.call(this, name, position, scene);
  5187. this.radius = 12;
  5188. this.rotationOffset = 0;
  5189. this.heightOffset = 4;
  5190. this.cameraAcceleration = 0.05;
  5191. this.maxCameraSpeed = 20;
  5192. }
  5193. FollowCamera.prototype.getRadians = function (degrees) {
  5194. return degrees * Math.PI / 180;
  5195. };
  5196. FollowCamera.prototype.follow = function (cameraTarget) {
  5197. if (!cameraTarget)
  5198. return;
  5199. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  5200. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  5201. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  5202. var dx = targetX - this.position.x;
  5203. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  5204. var dz = (targetZ) - this.position.z;
  5205. var vx = dx * this.cameraAcceleration * 2;
  5206. var vy = dy * this.cameraAcceleration;
  5207. var vz = dz * this.cameraAcceleration * 2;
  5208. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  5209. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5210. }
  5211. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  5212. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5213. }
  5214. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  5215. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5216. }
  5217. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  5218. this.setTarget(cameraTarget.position);
  5219. };
  5220. FollowCamera.prototype._update = function () {
  5221. _super.prototype._update.call(this);
  5222. this.follow(this.target);
  5223. };
  5224. return FollowCamera;
  5225. })(BABYLON.TargetCamera);
  5226. BABYLON.FollowCamera = FollowCamera;
  5227. })(BABYLON || (BABYLON = {}));
  5228. var __extends = this.__extends || function (d, b) {
  5229. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5230. function __() { this.constructor = d; }
  5231. __.prototype = b.prototype;
  5232. d.prototype = new __();
  5233. };
  5234. var BABYLON;
  5235. (function (BABYLON) {
  5236. var FreeCamera = (function (_super) {
  5237. __extends(FreeCamera, _super);
  5238. function FreeCamera(name, position, scene) {
  5239. _super.call(this, name, position, scene);
  5240. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  5241. this.keysUp = [38];
  5242. this.keysDown = [40];
  5243. this.keysLeft = [37];
  5244. this.keysRight = [39];
  5245. this.checkCollisions = false;
  5246. this.applyGravity = false;
  5247. this.angularSensibility = 2000.0;
  5248. this._keys = [];
  5249. this._collider = new BABYLON.Collider();
  5250. this._needMoveForGravity = true;
  5251. this._oldPosition = BABYLON.Vector3.Zero();
  5252. this._diffPosition = BABYLON.Vector3.Zero();
  5253. this._newPosition = BABYLON.Vector3.Zero();
  5254. }
  5255. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  5256. var _this = this;
  5257. var previousPosition;
  5258. var engine = this.getEngine();
  5259. if (this._attachedElement) {
  5260. return;
  5261. }
  5262. this._attachedElement = element;
  5263. if (this._onMouseDown === undefined) {
  5264. this._onMouseDown = function (evt) {
  5265. previousPosition = {
  5266. x: evt.clientX,
  5267. y: evt.clientY
  5268. };
  5269. if (!noPreventDefault) {
  5270. evt.preventDefault();
  5271. }
  5272. };
  5273. this._onMouseUp = function (evt) {
  5274. previousPosition = null;
  5275. if (!noPreventDefault) {
  5276. evt.preventDefault();
  5277. }
  5278. };
  5279. this._onMouseOut = function (evt) {
  5280. previousPosition = null;
  5281. _this._keys = [];
  5282. if (!noPreventDefault) {
  5283. evt.preventDefault();
  5284. }
  5285. };
  5286. this._onMouseMove = function (evt) {
  5287. if (!previousPosition && !engine.isPointerLock) {
  5288. return;
  5289. }
  5290. var offsetX;
  5291. var offsetY;
  5292. if (!engine.isPointerLock) {
  5293. offsetX = evt.clientX - previousPosition.x;
  5294. offsetY = evt.clientY - previousPosition.y;
  5295. } else {
  5296. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5297. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5298. }
  5299. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  5300. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  5301. previousPosition = {
  5302. x: evt.clientX,
  5303. y: evt.clientY
  5304. };
  5305. if (!noPreventDefault) {
  5306. evt.preventDefault();
  5307. }
  5308. };
  5309. this._onKeyDown = function (evt) {
  5310. 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) {
  5311. var index = _this._keys.indexOf(evt.keyCode);
  5312. if (index === -1) {
  5313. _this._keys.push(evt.keyCode);
  5314. }
  5315. if (!noPreventDefault) {
  5316. evt.preventDefault();
  5317. }
  5318. }
  5319. };
  5320. this._onKeyUp = function (evt) {
  5321. 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) {
  5322. var index = _this._keys.indexOf(evt.keyCode);
  5323. if (index >= 0) {
  5324. _this._keys.splice(index, 1);
  5325. }
  5326. if (!noPreventDefault) {
  5327. evt.preventDefault();
  5328. }
  5329. }
  5330. };
  5331. this._onLostFocus = function () {
  5332. _this._keys = [];
  5333. };
  5334. this._reset = function () {
  5335. _this._keys = [];
  5336. previousPosition = null;
  5337. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5338. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  5339. };
  5340. }
  5341. element.addEventListener("mousedown", this._onMouseDown, false);
  5342. element.addEventListener("mouseup", this._onMouseUp, false);
  5343. element.addEventListener("mouseout", this._onMouseOut, false);
  5344. element.addEventListener("mousemove", this._onMouseMove, false);
  5345. BABYLON.Tools.RegisterTopRootEvents([
  5346. { name: "keydown", handler: this._onKeyDown },
  5347. { name: "keyup", handler: this._onKeyUp },
  5348. { name: "blur", handler: this._onLostFocus }
  5349. ]);
  5350. };
  5351. FreeCamera.prototype.detachControl = function (element) {
  5352. if (this._attachedElement != element) {
  5353. return;
  5354. }
  5355. element.removeEventListener("mousedown", this._onMouseDown);
  5356. element.removeEventListener("mouseup", this._onMouseUp);
  5357. element.removeEventListener("mouseout", this._onMouseOut);
  5358. element.removeEventListener("mousemove", this._onMouseMove);
  5359. BABYLON.Tools.UnregisterTopRootEvents([
  5360. { name: "keydown", handler: this._onKeyDown },
  5361. { name: "keyup", handler: this._onKeyUp },
  5362. { name: "blur", handler: this._onLostFocus }
  5363. ]);
  5364. this._attachedElement = null;
  5365. if (this._reset) {
  5366. this._reset();
  5367. }
  5368. };
  5369. FreeCamera.prototype._collideWithWorld = function (velocity) {
  5370. var globalPosition;
  5371. if (this.parent) {
  5372. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  5373. } else {
  5374. globalPosition = this.position;
  5375. }
  5376. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  5377. this._collider.radius = this.ellipsoid;
  5378. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  5379. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  5380. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  5381. this.position.addInPlace(this._diffPosition);
  5382. if (this.onCollide) {
  5383. this.onCollide(this._collider.collidedMesh);
  5384. }
  5385. }
  5386. };
  5387. FreeCamera.prototype._checkInputs = function () {
  5388. if (!this._localDirection) {
  5389. this._localDirection = BABYLON.Vector3.Zero();
  5390. this._transformedDirection = BABYLON.Vector3.Zero();
  5391. }
  5392. for (var index = 0; index < this._keys.length; index++) {
  5393. var keyCode = this._keys[index];
  5394. var speed = this._computeLocalCameraSpeed();
  5395. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5396. this._localDirection.copyFromFloats(-speed, 0, 0);
  5397. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5398. this._localDirection.copyFromFloats(0, 0, speed);
  5399. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5400. this._localDirection.copyFromFloats(speed, 0, 0);
  5401. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5402. this._localDirection.copyFromFloats(0, 0, -speed);
  5403. }
  5404. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  5405. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  5406. this.cameraDirection.addInPlace(this._transformedDirection);
  5407. }
  5408. };
  5409. FreeCamera.prototype._decideIfNeedsToMove = function () {
  5410. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5411. };
  5412. FreeCamera.prototype._updatePosition = function () {
  5413. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  5414. this._collideWithWorld(this.cameraDirection);
  5415. if (this.applyGravity) {
  5416. var oldPosition = this.position;
  5417. this._collideWithWorld(this.getScene().gravity);
  5418. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  5419. }
  5420. } else {
  5421. this.position.addInPlace(this.cameraDirection);
  5422. }
  5423. };
  5424. FreeCamera.prototype._update = function () {
  5425. this._checkInputs();
  5426. _super.prototype._update.call(this);
  5427. };
  5428. return FreeCamera;
  5429. })(BABYLON.TargetCamera);
  5430. BABYLON.FreeCamera = FreeCamera;
  5431. })(BABYLON || (BABYLON = {}));
  5432. var __extends = this.__extends || function (d, b) {
  5433. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5434. function __() { this.constructor = d; }
  5435. __.prototype = b.prototype;
  5436. d.prototype = new __();
  5437. };
  5438. var BABYLON;
  5439. (function (BABYLON) {
  5440. var TouchCamera = (function (_super) {
  5441. __extends(TouchCamera, _super);
  5442. function TouchCamera(name, position, scene) {
  5443. _super.call(this, name, position, scene);
  5444. this._offsetX = null;
  5445. this._offsetY = null;
  5446. this._pointerCount = 0;
  5447. this._pointerPressed = [];
  5448. this.angularSensibility = 200000.0;
  5449. this.moveSensibility = 500.0;
  5450. }
  5451. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5452. var _this = this;
  5453. var previousPosition;
  5454. if (this._attachedCanvas) {
  5455. return;
  5456. }
  5457. this._attachedCanvas = canvas;
  5458. if (this._onPointerDown === undefined) {
  5459. this._onPointerDown = function (evt) {
  5460. if (!noPreventDefault) {
  5461. evt.preventDefault();
  5462. }
  5463. _this._pointerPressed.push(evt.pointerId);
  5464. if (_this._pointerPressed.length !== 1) {
  5465. return;
  5466. }
  5467. previousPosition = {
  5468. x: evt.clientX,
  5469. y: evt.clientY
  5470. };
  5471. };
  5472. this._onPointerUp = function (evt) {
  5473. if (!noPreventDefault) {
  5474. evt.preventDefault();
  5475. }
  5476. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5477. if (index === -1) {
  5478. return;
  5479. }
  5480. _this._pointerPressed.splice(index, 1);
  5481. if (index != 0) {
  5482. return;
  5483. }
  5484. previousPosition = null;
  5485. _this._offsetX = null;
  5486. _this._offsetY = null;
  5487. };
  5488. this._onPointerMove = function (evt) {
  5489. if (!noPreventDefault) {
  5490. evt.preventDefault();
  5491. }
  5492. if (!previousPosition) {
  5493. return;
  5494. }
  5495. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5496. if (index != 0) {
  5497. return;
  5498. }
  5499. _this._offsetX = evt.clientX - previousPosition.x;
  5500. _this._offsetY = -(evt.clientY - previousPosition.y);
  5501. };
  5502. this._onLostFocus = function () {
  5503. _this._offsetX = null;
  5504. _this._offsetY = null;
  5505. };
  5506. }
  5507. canvas.addEventListener("pointerdown", this._onPointerDown);
  5508. canvas.addEventListener("pointerup", this._onPointerUp);
  5509. canvas.addEventListener("pointerout", this._onPointerUp);
  5510. canvas.addEventListener("pointermove", this._onPointerMove);
  5511. BABYLON.Tools.RegisterTopRootEvents([
  5512. { name: "blur", handler: this._onLostFocus }
  5513. ]);
  5514. };
  5515. TouchCamera.prototype.detachControl = function (canvas) {
  5516. if (this._attachedCanvas != canvas) {
  5517. return;
  5518. }
  5519. canvas.removeEventListener("pointerdown", this._onPointerDown);
  5520. canvas.removeEventListener("pointerup", this._onPointerUp);
  5521. canvas.removeEventListener("pointerout", this._onPointerUp);
  5522. canvas.removeEventListener("pointermove", this._onPointerMove);
  5523. BABYLON.Tools.UnregisterTopRootEvents([
  5524. { name: "blur", handler: this._onLostFocus }
  5525. ]);
  5526. this._attachedCanvas = null;
  5527. };
  5528. TouchCamera.prototype._checkInputs = function () {
  5529. if (!this._offsetX) {
  5530. return;
  5531. }
  5532. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  5533. if (this._pointerPressed.length > 1) {
  5534. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  5535. } else {
  5536. var speed = this._computeLocalCameraSpeed();
  5537. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5538. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5539. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5540. }
  5541. };
  5542. return TouchCamera;
  5543. })(BABYLON.FreeCamera);
  5544. BABYLON.TouchCamera = TouchCamera;
  5545. })(BABYLON || (BABYLON = {}));
  5546. var __extends = this.__extends || function (d, b) {
  5547. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5548. function __() { this.constructor = d; }
  5549. __.prototype = b.prototype;
  5550. d.prototype = new __();
  5551. };
  5552. var BABYLON;
  5553. (function (BABYLON) {
  5554. var DeviceOrientationCamera = (function (_super) {
  5555. __extends(DeviceOrientationCamera, _super);
  5556. function DeviceOrientationCamera(name, position, scene) {
  5557. var _this = this;
  5558. _super.call(this, name, position, scene);
  5559. this._offsetX = null;
  5560. this._offsetY = null;
  5561. this._orientationGamma = 0;
  5562. this._orientationBeta = 0;
  5563. this._initialOrientationGamma = 0;
  5564. this._initialOrientationBeta = 0;
  5565. this.angularSensibility = 10000.0;
  5566. this.moveSensibility = 50.0;
  5567. window.addEventListener("resize", function () {
  5568. _this._initialOrientationGamma = null;
  5569. }, false);
  5570. }
  5571. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5572. var _this = this;
  5573. if (this._attachedCanvas) {
  5574. return;
  5575. }
  5576. this._attachedCanvas = canvas;
  5577. if (!this._orientationChanged) {
  5578. this._orientationChanged = function (evt) {
  5579. if (!_this._initialOrientationGamma) {
  5580. _this._initialOrientationGamma = evt.gamma;
  5581. _this._initialOrientationBeta = evt.beta;
  5582. }
  5583. _this._orientationGamma = evt.gamma;
  5584. _this._orientationBeta = evt.beta;
  5585. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  5586. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  5587. };
  5588. }
  5589. window.addEventListener("deviceorientation", this._orientationChanged);
  5590. };
  5591. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  5592. if (this._attachedCanvas != canvas) {
  5593. return;
  5594. }
  5595. window.removeEventListener("deviceorientation", this._orientationChanged);
  5596. this._attachedCanvas = null;
  5597. this._orientationGamma = 0;
  5598. this._orientationBeta = 0;
  5599. this._initialOrientationGamma = 0;
  5600. this._initialOrientationBeta = 0;
  5601. };
  5602. DeviceOrientationCamera.prototype._checkInputs = function () {
  5603. if (!this._offsetX) {
  5604. return;
  5605. }
  5606. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  5607. var speed = this._computeLocalCameraSpeed();
  5608. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5609. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5610. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5611. };
  5612. return DeviceOrientationCamera;
  5613. })(BABYLON.FreeCamera);
  5614. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  5615. })(BABYLON || (BABYLON = {}));
  5616. var __extends = this.__extends || function (d, b) {
  5617. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5618. function __() { this.constructor = d; }
  5619. __.prototype = b.prototype;
  5620. d.prototype = new __();
  5621. };
  5622. var BABYLON;
  5623. (function (BABYLON) {
  5624. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  5625. var ArcRotateCamera = (function (_super) {
  5626. __extends(ArcRotateCamera, _super);
  5627. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  5628. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  5629. this.alpha = alpha;
  5630. this.beta = beta;
  5631. this.radius = radius;
  5632. this.target = target;
  5633. this.inertialAlphaOffset = 0;
  5634. this.inertialBetaOffset = 0;
  5635. this.inertialRadiusOffset = 0;
  5636. this.lowerAlphaLimit = null;
  5637. this.upperAlphaLimit = null;
  5638. this.lowerBetaLimit = 0.01;
  5639. this.upperBetaLimit = Math.PI;
  5640. this.lowerRadiusLimit = null;
  5641. this.upperRadiusLimit = null;
  5642. this.angularSensibility = 1000.0;
  5643. this.wheelPrecision = 3.0;
  5644. this.keysUp = [38];
  5645. this.keysDown = [40];
  5646. this.keysLeft = [37];
  5647. this.keysRight = [39];
  5648. this.zoomOnFactor = 1;
  5649. this._keys = [];
  5650. this._viewMatrix = new BABYLON.Matrix();
  5651. this.checkCollisions = false;
  5652. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  5653. this._collider = new BABYLON.Collider();
  5654. this._previousPosition = BABYLON.Vector3.Zero();
  5655. this._collisionVelocity = BABYLON.Vector3.Zero();
  5656. this._newPosition = BABYLON.Vector3.Zero();
  5657. this.pinchPrecision = 20;
  5658. this.getViewMatrix();
  5659. }
  5660. ArcRotateCamera.prototype._getTargetPosition = function () {
  5661. return this.target.position || this.target;
  5662. };
  5663. ArcRotateCamera.prototype._initCache = function () {
  5664. _super.prototype._initCache.call(this);
  5665. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5666. this._cache.alpha = undefined;
  5667. this._cache.beta = undefined;
  5668. this._cache.radius = undefined;
  5669. };
  5670. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  5671. if (!ignoreParentClass) {
  5672. _super.prototype._updateCache.call(this);
  5673. }
  5674. this._cache.target.copyFrom(this._getTargetPosition());
  5675. this._cache.alpha = this.alpha;
  5676. this._cache.beta = this.beta;
  5677. this._cache.radius = this.radius;
  5678. };
  5679. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  5680. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  5681. return false;
  5682. return this._cache.target.equals(this._getTargetPosition()) && this._cache.alpha === this.alpha && this._cache.beta === this.beta && this._cache.radius === this.radius;
  5683. };
  5684. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  5685. var _this = this;
  5686. var previousPosition;
  5687. var pointerId;
  5688. var pinchStarted = false;
  5689. var pinchPointX1, pinchPointX2;
  5690. if (this._attachedElement) {
  5691. return;
  5692. }
  5693. this._attachedElement = element;
  5694. var engine = this.getEngine();
  5695. if (this._onPointerDown === undefined) {
  5696. this._onPointerDown = function (evt) {
  5697. if (pointerId) {
  5698. return;
  5699. }
  5700. pointerId = evt.pointerId;
  5701. previousPosition = {
  5702. x: evt.clientX,
  5703. y: evt.clientY
  5704. };
  5705. if (!noPreventDefault) {
  5706. evt.preventDefault();
  5707. }
  5708. };
  5709. this._onPointerUp = function (evt) {
  5710. previousPosition = null;
  5711. pointerId = null;
  5712. if (!noPreventDefault) {
  5713. evt.preventDefault();
  5714. }
  5715. };
  5716. this._onPointerMove = function (evt) {
  5717. if (!previousPosition) {
  5718. return;
  5719. }
  5720. if (pointerId !== evt.pointerId) {
  5721. return;
  5722. }
  5723. if (pinchStarted) {
  5724. return;
  5725. }
  5726. var offsetX = evt.clientX - previousPosition.x;
  5727. var offsetY = evt.clientY - previousPosition.y;
  5728. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5729. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5730. previousPosition = {
  5731. x: evt.clientX,
  5732. y: evt.clientY
  5733. };
  5734. if (!noPreventDefault) {
  5735. evt.preventDefault();
  5736. }
  5737. };
  5738. this._onMouseMove = function (evt) {
  5739. if (!engine.isPointerLock) {
  5740. return;
  5741. }
  5742. if (pinchStarted) {
  5743. return;
  5744. }
  5745. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5746. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5747. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5748. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5749. if (!noPreventDefault) {
  5750. evt.preventDefault();
  5751. }
  5752. };
  5753. this._wheel = function (event) {
  5754. var delta = 0;
  5755. if (event.wheelDelta) {
  5756. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  5757. } else if (event.detail) {
  5758. delta = -event.detail / _this.wheelPrecision;
  5759. }
  5760. if (delta)
  5761. _this.inertialRadiusOffset += delta;
  5762. if (event.preventDefault) {
  5763. if (!noPreventDefault) {
  5764. event.preventDefault();
  5765. }
  5766. }
  5767. };
  5768. this._onKeyDown = function (evt) {
  5769. 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) {
  5770. var index = _this._keys.indexOf(evt.keyCode);
  5771. if (index === -1) {
  5772. _this._keys.push(evt.keyCode);
  5773. }
  5774. if (evt.preventDefault) {
  5775. if (!noPreventDefault) {
  5776. evt.preventDefault();
  5777. }
  5778. }
  5779. }
  5780. };
  5781. this._onKeyUp = function (evt) {
  5782. 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) {
  5783. var index = _this._keys.indexOf(evt.keyCode);
  5784. if (index >= 0) {
  5785. _this._keys.splice(index, 1);
  5786. }
  5787. if (evt.preventDefault) {
  5788. if (!noPreventDefault) {
  5789. evt.preventDefault();
  5790. }
  5791. }
  5792. }
  5793. };
  5794. this._onLostFocus = function () {
  5795. _this._keys = [];
  5796. pointerId = null;
  5797. };
  5798. this._onGestureStart = function (e) {
  5799. if (window.MSGesture === undefined) {
  5800. return;
  5801. }
  5802. if (!_this._MSGestureHandler) {
  5803. _this._MSGestureHandler = new MSGesture();
  5804. _this._MSGestureHandler.target = element;
  5805. }
  5806. _this._MSGestureHandler.addPointer(e.pointerId);
  5807. };
  5808. this._onGesture = function (e) {
  5809. _this.radius *= e.scale;
  5810. if (e.preventDefault) {
  5811. if (!noPreventDefault) {
  5812. e.stopPropagation();
  5813. e.preventDefault();
  5814. }
  5815. }
  5816. };
  5817. this._reset = function () {
  5818. _this._keys = [];
  5819. _this.inertialAlphaOffset = 0;
  5820. _this.inertialBetaOffset = 0;
  5821. _this.inertialRadiusOffset = 0;
  5822. previousPosition = null;
  5823. pointerId = null;
  5824. };
  5825. this._touchStart = function (event) {
  5826. if (event.touches.length == 2) {
  5827. pinchStarted = true;
  5828. _this._pinchStart(event);
  5829. }
  5830. };
  5831. this._touchMove = function (event) {
  5832. if (pinchStarted) {
  5833. _this._pinchMove(event);
  5834. }
  5835. };
  5836. this._touchEnd = function (event) {
  5837. if (pinchStarted) {
  5838. _this._pinchEnd(event);
  5839. }
  5840. };
  5841. this._pinchStart = function (event) {
  5842. pinchPointX1 = event.touches[0].clientX;
  5843. pinchPointX2 = event.touches[1].clientX;
  5844. pinchStarted = true;
  5845. };
  5846. this._pinchMove = function (event) {
  5847. var delta = 0;
  5848. var direction = 1;
  5849. var distanceXOrigine, distanceXNow;
  5850. if (event.touches.length != 2)
  5851. return;
  5852. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  5853. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  5854. if (distanceXNow < distanceXOrigine) {
  5855. direction = -1;
  5856. }
  5857. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  5858. _this.inertialRadiusOffset += delta;
  5859. pinchPointX1 = event.touches[0].clientX;
  5860. pinchPointX2 = event.touches[1].clientX;
  5861. };
  5862. this._pinchEnd = function (event) {
  5863. pinchStarted = false;
  5864. };
  5865. }
  5866. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  5867. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  5868. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  5869. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  5870. element.addEventListener("mousemove", this._onMouseMove, false);
  5871. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  5872. element.addEventListener("MSGestureChange", this._onGesture, false);
  5873. element.addEventListener('mousewheel', this._wheel, false);
  5874. element.addEventListener('DOMMouseScroll', this._wheel, false);
  5875. element.addEventListener('touchstart', this._touchStart, false);
  5876. element.addEventListener('touchmove', this._touchMove, false);
  5877. element.addEventListener('touchend', this._touchEnd, false);
  5878. BABYLON.Tools.RegisterTopRootEvents([
  5879. { name: "keydown", handler: this._onKeyDown },
  5880. { name: "keyup", handler: this._onKeyUp },
  5881. { name: "blur", handler: this._onLostFocus }
  5882. ]);
  5883. };
  5884. ArcRotateCamera.prototype.detachControl = function (element) {
  5885. if (this._attachedElement != element) {
  5886. return;
  5887. }
  5888. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  5889. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  5890. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  5891. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  5892. element.removeEventListener("mousemove", this._onMouseMove);
  5893. element.removeEventListener("MSPointerDown", this._onGestureStart);
  5894. element.removeEventListener("MSGestureChange", this._onGesture);
  5895. element.removeEventListener('mousewheel', this._wheel);
  5896. element.removeEventListener('DOMMouseScroll', this._wheel);
  5897. element.removeEventListener('touchstart', this._touchStart);
  5898. element.removeEventListener('touchmove', this._touchMove);
  5899. element.removeEventListener('touchend', this._touchEnd);
  5900. BABYLON.Tools.UnregisterTopRootEvents([
  5901. { name: "keydown", handler: this._onKeyDown },
  5902. { name: "keyup", handler: this._onKeyUp },
  5903. { name: "blur", handler: this._onLostFocus }
  5904. ]);
  5905. this._MSGestureHandler = null;
  5906. this._attachedElement = null;
  5907. if (this._reset) {
  5908. this._reset();
  5909. }
  5910. };
  5911. ArcRotateCamera.prototype._update = function () {
  5912. for (var index = 0; index < this._keys.length; index++) {
  5913. var keyCode = this._keys[index];
  5914. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5915. this.inertialAlphaOffset -= 0.01;
  5916. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5917. this.inertialBetaOffset -= 0.01;
  5918. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5919. this.inertialAlphaOffset += 0.01;
  5920. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5921. this.inertialBetaOffset += 0.01;
  5922. }
  5923. }
  5924. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  5925. this.alpha += this.inertialAlphaOffset;
  5926. this.beta += this.inertialBetaOffset;
  5927. this.radius -= this.inertialRadiusOffset;
  5928. this.inertialAlphaOffset *= this.inertia;
  5929. this.inertialBetaOffset *= this.inertia;
  5930. this.inertialRadiusOffset *= this.inertia;
  5931. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  5932. this.inertialAlphaOffset = 0;
  5933. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  5934. this.inertialBetaOffset = 0;
  5935. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  5936. this.inertialRadiusOffset = 0;
  5937. }
  5938. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  5939. this.alpha = this.lowerAlphaLimit;
  5940. }
  5941. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  5942. this.alpha = this.upperAlphaLimit;
  5943. }
  5944. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  5945. this.beta = this.lowerBetaLimit;
  5946. }
  5947. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  5948. this.beta = this.upperBetaLimit;
  5949. }
  5950. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  5951. this.radius = this.lowerRadiusLimit;
  5952. }
  5953. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  5954. this.radius = this.upperRadiusLimit;
  5955. }
  5956. };
  5957. ArcRotateCamera.prototype.setPosition = function (position) {
  5958. var radiusv3 = position.subtract(this._getTargetPosition());
  5959. this.radius = radiusv3.length();
  5960. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  5961. if (radiusv3.z < 0) {
  5962. this.alpha = 2 * Math.PI - this.alpha;
  5963. }
  5964. this.beta = Math.acos(radiusv3.y / this.radius);
  5965. };
  5966. ArcRotateCamera.prototype._getViewMatrix = function () {
  5967. var cosa = Math.cos(this.alpha);
  5968. var sina = Math.sin(this.alpha);
  5969. var cosb = Math.cos(this.beta);
  5970. var sinb = Math.sin(this.beta);
  5971. var target = this._getTargetPosition();
  5972. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  5973. if (this.checkCollisions) {
  5974. this._collider.radius = this.collisionRadius;
  5975. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  5976. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  5977. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  5978. this.position.copyFrom(this._previousPosition);
  5979. this.alpha = this._previousAlpha;
  5980. this.beta = this._previousBeta;
  5981. this.radius = this._previousRadius;
  5982. if (this.onCollide) {
  5983. this.onCollide(this._collider.collidedMesh);
  5984. }
  5985. }
  5986. }
  5987. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  5988. this._previousAlpha = this.alpha;
  5989. this._previousBeta = this.beta;
  5990. this._previousRadius = this.radius;
  5991. this._previousPosition.copyFrom(this.position);
  5992. return this._viewMatrix;
  5993. };
  5994. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  5995. meshes = meshes || this.getScene().meshes;
  5996. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  5997. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  5998. this.radius = distance * this.zoomOnFactor;
  5999. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  6000. };
  6001. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  6002. var meshesOrMinMaxVector;
  6003. var distance;
  6004. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  6005. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  6006. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  6007. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  6008. } else {
  6009. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  6010. distance = meshesOrMinMaxVectorAndDistance.distance;
  6011. }
  6012. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  6013. this.maxZ = distance * 2;
  6014. };
  6015. return ArcRotateCamera;
  6016. })(BABYLON.Camera);
  6017. BABYLON.ArcRotateCamera = ArcRotateCamera;
  6018. })(BABYLON || (BABYLON = {}));
  6019. var BABYLON;
  6020. (function (BABYLON) {
  6021. var Scene = (function () {
  6022. function Scene(engine) {
  6023. this.autoClear = true;
  6024. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6025. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  6026. this.forceWireframe = false;
  6027. this.cameraToUseForPointers = null;
  6028. this.fogMode = BABYLON.Scene.FOGMODE_NONE;
  6029. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6030. this.fogDensity = 0.1;
  6031. this.fogStart = 0;
  6032. this.fogEnd = 1000.0;
  6033. this.lightsEnabled = true;
  6034. this.lights = new Array();
  6035. this.cameras = new Array();
  6036. this.activeCameras = new Array();
  6037. this.meshes = new Array();
  6038. this._geometries = new Array();
  6039. this.materials = new Array();
  6040. this.multiMaterials = new Array();
  6041. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  6042. this.texturesEnabled = true;
  6043. this.textures = new Array();
  6044. this.particlesEnabled = true;
  6045. this.particleSystems = new Array();
  6046. this.spriteManagers = new Array();
  6047. this.layers = new Array();
  6048. this.skeletons = new Array();
  6049. this.lensFlareSystems = new Array();
  6050. this.collisionsEnabled = true;
  6051. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  6052. this.postProcessesEnabled = true;
  6053. this.renderTargetsEnabled = true;
  6054. this.customRenderTargets = new Array();
  6055. this.importedMeshesFiles = new Array();
  6056. this._actionManagers = new Array();
  6057. this._meshesForIntersections = new BABYLON.SmartArray(256);
  6058. this._totalVertices = 0;
  6059. this._activeVertices = 0;
  6060. this._activeParticles = 0;
  6061. this._lastFrameDuration = 0;
  6062. this._evaluateActiveMeshesDuration = 0;
  6063. this._renderTargetsDuration = 0;
  6064. this._particlesDuration = 0;
  6065. this._renderDuration = 0;
  6066. this._spritesDuration = 0;
  6067. this._animationRatio = 0;
  6068. this._renderId = 0;
  6069. this._executeWhenReadyTimeoutId = -1;
  6070. this._toBeDisposed = new BABYLON.SmartArray(256);
  6071. this._onReadyCallbacks = new Array();
  6072. this._pendingData = [];
  6073. this._onBeforeRenderCallbacks = new Array();
  6074. this._activeMeshes = new BABYLON.SmartArray(256);
  6075. this._processedMaterials = new BABYLON.SmartArray(256);
  6076. this._renderTargets = new BABYLON.SmartArray(256);
  6077. this._activeParticleSystems = new BABYLON.SmartArray(256);
  6078. this._activeSkeletons = new BABYLON.SmartArray(32);
  6079. this._activeAnimatables = new Array();
  6080. this._transformMatrix = BABYLON.Matrix.Zero();
  6081. this._scaledPosition = BABYLON.Vector3.Zero();
  6082. this._scaledVelocity = BABYLON.Vector3.Zero();
  6083. this._engine = engine;
  6084. engine.scenes.push(this);
  6085. this._renderingManager = new BABYLON.RenderingManager(this);
  6086. this.postProcessManager = new BABYLON.PostProcessManager(this);
  6087. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  6088. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  6089. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  6090. this.attachControl();
  6091. }
  6092. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  6093. get: function () {
  6094. return this._meshUnderPointer;
  6095. },
  6096. enumerable: true,
  6097. configurable: true
  6098. });
  6099. Object.defineProperty(Scene.prototype, "pointerX", {
  6100. get: function () {
  6101. return this._pointerX;
  6102. },
  6103. enumerable: true,
  6104. configurable: true
  6105. });
  6106. Object.defineProperty(Scene.prototype, "pointerY", {
  6107. get: function () {
  6108. return this._pointerY;
  6109. },
  6110. enumerable: true,
  6111. configurable: true
  6112. });
  6113. Scene.prototype.getBoundingBoxRenderer = function () {
  6114. return this._boundingBoxRenderer;
  6115. };
  6116. Scene.prototype.getOutlineRenderer = function () {
  6117. return this._outlineRenderer;
  6118. };
  6119. Scene.prototype.getEngine = function () {
  6120. return this._engine;
  6121. };
  6122. Scene.prototype.getTotalVertices = function () {
  6123. return this._totalVertices;
  6124. };
  6125. Scene.prototype.getActiveVertices = function () {
  6126. return this._activeVertices;
  6127. };
  6128. Scene.prototype.getActiveParticles = function () {
  6129. return this._activeParticles;
  6130. };
  6131. Scene.prototype.getLastFrameDuration = function () {
  6132. return this._lastFrameDuration;
  6133. };
  6134. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  6135. return this._evaluateActiveMeshesDuration;
  6136. };
  6137. Scene.prototype.getActiveMeshes = function () {
  6138. return this._activeMeshes;
  6139. };
  6140. Scene.prototype.getRenderTargetsDuration = function () {
  6141. return this._renderTargetsDuration;
  6142. };
  6143. Scene.prototype.getRenderDuration = function () {
  6144. return this._renderDuration;
  6145. };
  6146. Scene.prototype.getParticlesDuration = function () {
  6147. return this._particlesDuration;
  6148. };
  6149. Scene.prototype.getSpritesDuration = function () {
  6150. return this._spritesDuration;
  6151. };
  6152. Scene.prototype.getAnimationRatio = function () {
  6153. return this._animationRatio;
  6154. };
  6155. Scene.prototype.getRenderId = function () {
  6156. return this._renderId;
  6157. };
  6158. Scene.prototype._updatePointerPosition = function (evt) {
  6159. var canvasRect = this._engine.getRenderingCanvasClientRect();
  6160. this._pointerX = evt.clientX - canvasRect.left;
  6161. this._pointerY = evt.clientY - canvasRect.top;
  6162. if (this.cameraToUseForPointers) {
  6163. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  6164. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  6165. }
  6166. };
  6167. Scene.prototype.attachControl = function () {
  6168. var _this = this;
  6169. this._onPointerMove = function (evt) {
  6170. var canvas = _this._engine.getRenderingCanvas();
  6171. _this._updatePointerPosition(evt);
  6172. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  6173. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  6174. }, false, _this.cameraToUseForPointers);
  6175. if (pickResult.hit) {
  6176. _this._meshUnderPointer = pickResult.pickedMesh;
  6177. _this.setPointerOverMesh(pickResult.pickedMesh);
  6178. canvas.style.cursor = "pointer";
  6179. } else {
  6180. _this.setPointerOverMesh(null);
  6181. canvas.style.cursor = "";
  6182. _this._meshUnderPointer = null;
  6183. }
  6184. };
  6185. this._onPointerDown = function (evt) {
  6186. var predicate = null;
  6187. if (!_this.onPointerDown) {
  6188. predicate = function (mesh) {
  6189. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  6190. };
  6191. }
  6192. _this._updatePointerPosition(evt);
  6193. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  6194. if (pickResult.hit) {
  6195. if (pickResult.pickedMesh.actionManager) {
  6196. switch (evt.button) {
  6197. case 0:
  6198. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6199. break;
  6200. case 1:
  6201. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6202. break;
  6203. case 2:
  6204. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6205. break;
  6206. }
  6207. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6208. }
  6209. }
  6210. if (_this.onPointerDown) {
  6211. _this.onPointerDown(evt, pickResult);
  6212. }
  6213. };
  6214. this._onKeyDown = function (evt) {
  6215. if (_this.actionManager) {
  6216. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6217. }
  6218. };
  6219. this._onKeyUp = function (evt) {
  6220. if (_this.actionManager) {
  6221. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6222. }
  6223. };
  6224. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6225. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6226. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6227. window.addEventListener("keydown", this._onKeyDown, false);
  6228. window.addEventListener("keyup", this._onKeyUp, false);
  6229. };
  6230. Scene.prototype.detachControl = function () {
  6231. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6232. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  6233. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  6234. window.removeEventListener("keydown", this._onKeyDown);
  6235. window.removeEventListener("keyup", this._onKeyUp);
  6236. };
  6237. Scene.prototype.isReady = function () {
  6238. if (this._pendingData.length > 0) {
  6239. return false;
  6240. }
  6241. for (var index = 0; index < this._geometries.length; index++) {
  6242. var geometry = this._geometries[index];
  6243. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  6244. return false;
  6245. }
  6246. }
  6247. for (index = 0; index < this.meshes.length; index++) {
  6248. var mesh = this.meshes[index];
  6249. if (!mesh.isReady()) {
  6250. return false;
  6251. }
  6252. var mat = mesh.material;
  6253. if (mat) {
  6254. if (!mat.isReady(mesh)) {
  6255. return false;
  6256. }
  6257. }
  6258. }
  6259. return true;
  6260. };
  6261. Scene.prototype.registerBeforeRender = function (func) {
  6262. this._onBeforeRenderCallbacks.push(func);
  6263. };
  6264. Scene.prototype.unregisterBeforeRender = function (func) {
  6265. var index = this._onBeforeRenderCallbacks.indexOf(func);
  6266. if (index > -1) {
  6267. this._onBeforeRenderCallbacks.splice(index, 1);
  6268. }
  6269. };
  6270. Scene.prototype._addPendingData = function (data) {
  6271. this._pendingData.push(data);
  6272. };
  6273. Scene.prototype._removePendingData = function (data) {
  6274. var index = this._pendingData.indexOf(data);
  6275. if (index !== -1) {
  6276. this._pendingData.splice(index, 1);
  6277. }
  6278. };
  6279. Scene.prototype.getWaitingItemsCount = function () {
  6280. return this._pendingData.length;
  6281. };
  6282. Scene.prototype.executeWhenReady = function (func) {
  6283. var _this = this;
  6284. this._onReadyCallbacks.push(func);
  6285. if (this._executeWhenReadyTimeoutId !== -1) {
  6286. return;
  6287. }
  6288. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6289. _this._checkIsReady();
  6290. }, 150);
  6291. };
  6292. Scene.prototype._checkIsReady = function () {
  6293. var _this = this;
  6294. if (this.isReady()) {
  6295. this._onReadyCallbacks.forEach(function (func) {
  6296. func();
  6297. });
  6298. this._onReadyCallbacks = [];
  6299. this._executeWhenReadyTimeoutId = -1;
  6300. return;
  6301. }
  6302. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6303. _this._checkIsReady();
  6304. }, 150);
  6305. };
  6306. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  6307. if (speedRatio === undefined) {
  6308. speedRatio = 1.0;
  6309. }
  6310. this.stopAnimation(target);
  6311. if (!animatable) {
  6312. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  6313. }
  6314. if (target.animations) {
  6315. animatable.appendAnimations(target, target.animations);
  6316. }
  6317. if (target.getAnimatables) {
  6318. var animatables = target.getAnimatables();
  6319. for (var index = 0; index < animatables.length; index++) {
  6320. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  6321. }
  6322. }
  6323. return animatable;
  6324. };
  6325. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  6326. if (speedRatio === undefined) {
  6327. speedRatio = 1.0;
  6328. }
  6329. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  6330. return animatable;
  6331. };
  6332. Scene.prototype.getAnimatableByTarget = function (target) {
  6333. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6334. if (this._activeAnimatables[index].target === target) {
  6335. return this._activeAnimatables[index];
  6336. }
  6337. }
  6338. return null;
  6339. };
  6340. Scene.prototype.stopAnimation = function (target) {
  6341. var animatable = this.getAnimatableByTarget(target);
  6342. if (animatable) {
  6343. animatable.stop();
  6344. }
  6345. };
  6346. Scene.prototype._animate = function () {
  6347. if (!this._animationStartDate) {
  6348. this._animationStartDate = new Date().getTime();
  6349. }
  6350. var now = new Date().getTime();
  6351. var delay = now - this._animationStartDate;
  6352. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6353. if (!this._activeAnimatables[index]._animate(delay)) {
  6354. this._activeAnimatables.splice(index, 1);
  6355. index--;
  6356. }
  6357. }
  6358. };
  6359. Scene.prototype.getViewMatrix = function () {
  6360. return this._viewMatrix;
  6361. };
  6362. Scene.prototype.getProjectionMatrix = function () {
  6363. return this._projectionMatrix;
  6364. };
  6365. Scene.prototype.getTransformMatrix = function () {
  6366. return this._transformMatrix;
  6367. };
  6368. Scene.prototype.setTransformMatrix = function (view, projection) {
  6369. this._viewMatrix = view;
  6370. this._projectionMatrix = projection;
  6371. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6372. };
  6373. Scene.prototype.setActiveCameraByID = function (id) {
  6374. var camera = this.getCameraByID(id);
  6375. if (camera) {
  6376. this.activeCamera = camera;
  6377. return camera;
  6378. }
  6379. return null;
  6380. };
  6381. Scene.prototype.setActiveCameraByName = function (name) {
  6382. var camera = this.getCameraByName(name);
  6383. if (camera) {
  6384. this.activeCamera = camera;
  6385. return camera;
  6386. }
  6387. return null;
  6388. };
  6389. Scene.prototype.getMaterialByID = function (id) {
  6390. for (var index = 0; index < this.materials.length; index++) {
  6391. if (this.materials[index].id === id) {
  6392. return this.materials[index];
  6393. }
  6394. }
  6395. return null;
  6396. };
  6397. Scene.prototype.getMaterialByName = function (name) {
  6398. for (var index = 0; index < this.materials.length; index++) {
  6399. if (this.materials[index].name === name) {
  6400. return this.materials[index];
  6401. }
  6402. }
  6403. return null;
  6404. };
  6405. Scene.prototype.getCameraByID = function (id) {
  6406. for (var index = 0; index < this.cameras.length; index++) {
  6407. if (this.cameras[index].id === id) {
  6408. return this.cameras[index];
  6409. }
  6410. }
  6411. return null;
  6412. };
  6413. Scene.prototype.getCameraByName = function (name) {
  6414. for (var index = 0; index < this.cameras.length; index++) {
  6415. if (this.cameras[index].name === name) {
  6416. return this.cameras[index];
  6417. }
  6418. }
  6419. return null;
  6420. };
  6421. Scene.prototype.getLightByName = function (name) {
  6422. for (var index = 0; index < this.lights.length; index++) {
  6423. if (this.lights[index].name === name) {
  6424. return this.lights[index];
  6425. }
  6426. }
  6427. return null;
  6428. };
  6429. Scene.prototype.getLightByID = function (id) {
  6430. for (var index = 0; index < this.lights.length; index++) {
  6431. if (this.lights[index].id === id) {
  6432. return this.lights[index];
  6433. }
  6434. }
  6435. return null;
  6436. };
  6437. Scene.prototype.getGeometryByID = function (id) {
  6438. for (var index = 0; index < this._geometries.length; index++) {
  6439. if (this._geometries[index].id === id) {
  6440. return this._geometries[index];
  6441. }
  6442. }
  6443. return null;
  6444. };
  6445. Scene.prototype.pushGeometry = function (geometry, force) {
  6446. if (!force && this.getGeometryByID(geometry.id)) {
  6447. return false;
  6448. }
  6449. this._geometries.push(geometry);
  6450. return true;
  6451. };
  6452. Scene.prototype.getGeometries = function () {
  6453. return this._geometries;
  6454. };
  6455. Scene.prototype.getMeshByID = function (id) {
  6456. for (var index = 0; index < this.meshes.length; index++) {
  6457. if (this.meshes[index].id === id) {
  6458. return this.meshes[index];
  6459. }
  6460. }
  6461. return null;
  6462. };
  6463. Scene.prototype.getLastMeshByID = function (id) {
  6464. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6465. if (this.meshes[index].id === id) {
  6466. return this.meshes[index];
  6467. }
  6468. }
  6469. return null;
  6470. };
  6471. Scene.prototype.getLastEntryByID = function (id) {
  6472. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6473. if (this.meshes[index].id === id) {
  6474. return this.meshes[index];
  6475. }
  6476. }
  6477. for (index = this.cameras.length - 1; index >= 0; index--) {
  6478. if (this.cameras[index].id === id) {
  6479. return this.cameras[index];
  6480. }
  6481. }
  6482. for (index = this.lights.length - 1; index >= 0; index--) {
  6483. if (this.lights[index].id === id) {
  6484. return this.lights[index];
  6485. }
  6486. }
  6487. return null;
  6488. };
  6489. Scene.prototype.getMeshByName = function (name) {
  6490. for (var index = 0; index < this.meshes.length; index++) {
  6491. if (this.meshes[index].name === name) {
  6492. return this.meshes[index];
  6493. }
  6494. }
  6495. return null;
  6496. };
  6497. Scene.prototype.getLastSkeletonByID = function (id) {
  6498. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  6499. if (this.skeletons[index].id === id) {
  6500. return this.skeletons[index];
  6501. }
  6502. }
  6503. return null;
  6504. };
  6505. Scene.prototype.getSkeletonById = function (id) {
  6506. for (var index = 0; index < this.skeletons.length; index++) {
  6507. if (this.skeletons[index].id === id) {
  6508. return this.skeletons[index];
  6509. }
  6510. }
  6511. return null;
  6512. };
  6513. Scene.prototype.getSkeletonByName = function (name) {
  6514. for (var index = 0; index < this.skeletons.length; index++) {
  6515. if (this.skeletons[index].name === name) {
  6516. return this.skeletons[index];
  6517. }
  6518. }
  6519. return null;
  6520. };
  6521. Scene.prototype.isActiveMesh = function (mesh) {
  6522. return (this._activeMeshes.indexOf(mesh) !== -1);
  6523. };
  6524. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  6525. if (mesh.subMeshes.length == 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  6526. var material = subMesh.getMaterial();
  6527. if (mesh.showSubMeshesBoundingBox) {
  6528. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  6529. }
  6530. if (material) {
  6531. if (material.getRenderTargetTextures) {
  6532. if (this._processedMaterials.indexOf(material) === -1) {
  6533. this._processedMaterials.push(material);
  6534. this._renderTargets.concat(material.getRenderTargetTextures());
  6535. }
  6536. }
  6537. this._activeVertices += subMesh.verticesCount;
  6538. this._renderingManager.dispatch(subMesh);
  6539. }
  6540. }
  6541. };
  6542. Scene.prototype._evaluateActiveMeshes = function () {
  6543. this._activeMeshes.reset();
  6544. this._renderingManager.reset();
  6545. this._processedMaterials.reset();
  6546. this._activeParticleSystems.reset();
  6547. this._activeSkeletons.reset();
  6548. this._boundingBoxRenderer.reset();
  6549. if (!this._frustumPlanes) {
  6550. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  6551. } else {
  6552. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  6553. }
  6554. var meshes;
  6555. var len;
  6556. if (this._selectionOctree) {
  6557. var selection = this._selectionOctree.select(this._frustumPlanes);
  6558. meshes = selection.data;
  6559. len = selection.length;
  6560. } else {
  6561. len = this.meshes.length;
  6562. meshes = this.meshes;
  6563. }
  6564. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  6565. var mesh = meshes[meshIndex];
  6566. this._totalVertices += mesh.getTotalVertices();
  6567. if (!mesh.isReady()) {
  6568. continue;
  6569. }
  6570. mesh.computeWorldMatrix();
  6571. mesh._preActivate();
  6572. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  6573. this._meshesForIntersections.pushNoDuplicate(mesh);
  6574. }
  6575. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) != 0) && mesh.isInFrustum(this._frustumPlanes)) {
  6576. this._activeMeshes.push(mesh);
  6577. mesh._activate(this._renderId);
  6578. this._activeMesh(mesh);
  6579. }
  6580. }
  6581. var beforeParticlesDate = new Date().getTime();
  6582. if (this.particlesEnabled) {
  6583. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  6584. var particleSystem = this.particleSystems[particleIndex];
  6585. if (!particleSystem.isStarted()) {
  6586. continue;
  6587. }
  6588. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  6589. this._activeParticleSystems.push(particleSystem);
  6590. particleSystem.animate();
  6591. }
  6592. }
  6593. }
  6594. this._particlesDuration += new Date().getTime() - beforeParticlesDate;
  6595. };
  6596. Scene.prototype._activeMesh = function (mesh) {
  6597. if (mesh.skeleton) {
  6598. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  6599. }
  6600. if (mesh.showBoundingBox) {
  6601. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  6602. }
  6603. if (mesh.subMeshes) {
  6604. var len;
  6605. var subMeshes;
  6606. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  6607. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  6608. len = intersections.length;
  6609. subMeshes = intersections.data;
  6610. } else {
  6611. subMeshes = mesh.subMeshes;
  6612. len = subMeshes.length;
  6613. }
  6614. for (var subIndex = 0; subIndex < len; subIndex++) {
  6615. var subMesh = subMeshes[subIndex];
  6616. this._evaluateSubMesh(subMesh, mesh);
  6617. }
  6618. }
  6619. };
  6620. Scene.prototype.updateTransformMatrix = function (force) {
  6621. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  6622. };
  6623. Scene.prototype._renderForCamera = function (camera) {
  6624. var engine = this._engine;
  6625. this.activeCamera = camera;
  6626. if (!this.activeCamera)
  6627. throw new Error("Active camera not set");
  6628. engine.setViewport(this.activeCamera.viewport);
  6629. this._renderId++;
  6630. this.updateTransformMatrix();
  6631. if (this.beforeCameraRender) {
  6632. this.beforeCameraRender(this.activeCamera);
  6633. }
  6634. var beforeEvaluateActiveMeshesDate = new Date().getTime();
  6635. this._evaluateActiveMeshes();
  6636. this._evaluateActiveMeshesDuration += new Date().getTime() - beforeEvaluateActiveMeshesDate;
  6637. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  6638. var skeleton = this._activeSkeletons.data[skeletonIndex];
  6639. skeleton.prepare();
  6640. }
  6641. var beforeRenderTargetDate = new Date().getTime();
  6642. if (this.renderTargetsEnabled) {
  6643. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  6644. var renderTarget = this._renderTargets.data[renderIndex];
  6645. if (renderTarget._shouldRender()) {
  6646. this._renderId++;
  6647. renderTarget.render();
  6648. }
  6649. }
  6650. this._renderId++;
  6651. }
  6652. if (this._renderTargets.length > 0) {
  6653. engine.restoreDefaultFramebuffer();
  6654. }
  6655. this._renderTargetsDuration += new Date().getTime() - beforeRenderTargetDate;
  6656. this.postProcessManager._prepareFrame();
  6657. var beforeRenderDate = new Date().getTime();
  6658. if (this.layers.length) {
  6659. engine.setDepthBuffer(false);
  6660. var layerIndex;
  6661. var layer;
  6662. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6663. layer = this.layers[layerIndex];
  6664. if (layer.isBackground) {
  6665. layer.render();
  6666. }
  6667. }
  6668. engine.setDepthBuffer(true);
  6669. }
  6670. this._renderingManager.render(null, null, true, true);
  6671. this._boundingBoxRenderer.render();
  6672. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  6673. this.lensFlareSystems[lensFlareSystemIndex].render();
  6674. }
  6675. if (this.layers.length) {
  6676. engine.setDepthBuffer(false);
  6677. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6678. layer = this.layers[layerIndex];
  6679. if (!layer.isBackground) {
  6680. layer.render();
  6681. }
  6682. }
  6683. engine.setDepthBuffer(true);
  6684. }
  6685. this._renderDuration += new Date().getTime() - beforeRenderDate;
  6686. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  6687. this.activeCamera._updateFromScene();
  6688. this._renderTargets.reset();
  6689. if (this.afterCameraRender) {
  6690. this.afterCameraRender(this.activeCamera);
  6691. }
  6692. };
  6693. Scene.prototype._processSubCameras = function (camera) {
  6694. if (camera.subCameras.length == 0) {
  6695. this._renderForCamera(camera);
  6696. return;
  6697. }
  6698. for (var index = 0; index < camera.subCameras.length; index++) {
  6699. this._renderForCamera(camera.subCameras[index]);
  6700. }
  6701. this.activeCamera = camera;
  6702. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  6703. this.activeCamera._updateFromScene();
  6704. };
  6705. Scene.prototype._checkIntersections = function () {
  6706. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  6707. var sourceMesh = this._meshesForIntersections.data[index];
  6708. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  6709. var action = sourceMesh.actionManager.actions[actionIndex];
  6710. if (action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6711. var otherMesh = action.getTriggerParameter();
  6712. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  6713. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6714. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  6715. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6716. sourceMesh._intersectionsInProgress.push(otherMesh);
  6717. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6718. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6719. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6720. if (indexOfOther > -1) {
  6721. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  6722. }
  6723. }
  6724. }
  6725. }
  6726. }
  6727. };
  6728. Scene.prototype.render = function () {
  6729. var startDate = new Date().getTime();
  6730. this._particlesDuration = 0;
  6731. this._spritesDuration = 0;
  6732. this._activeParticles = 0;
  6733. this._renderDuration = 0;
  6734. this._evaluateActiveMeshesDuration = 0;
  6735. this._totalVertices = 0;
  6736. this._activeVertices = 0;
  6737. this._meshesForIntersections.reset();
  6738. if (this.actionManager) {
  6739. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  6740. }
  6741. if (this.beforeRender) {
  6742. this.beforeRender();
  6743. }
  6744. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  6745. this._onBeforeRenderCallbacks[callbackIndex]();
  6746. }
  6747. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(BABYLON.Tools.GetDeltaTime(), Scene.MaxDeltaTime));
  6748. this._animationRatio = deltaTime * (60.0 / 1000.0);
  6749. this._animate();
  6750. if (this._physicsEngine) {
  6751. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  6752. }
  6753. var beforeRenderTargetDate = new Date().getTime();
  6754. var engine = this.getEngine();
  6755. if (this.renderTargetsEnabled) {
  6756. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  6757. var renderTarget = this.customRenderTargets[customIndex];
  6758. if (renderTarget._shouldRender()) {
  6759. this._renderId++;
  6760. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  6761. if (!this.activeCamera)
  6762. throw new Error("Active camera not set");
  6763. engine.setViewport(this.activeCamera.viewport);
  6764. this.updateTransformMatrix();
  6765. renderTarget.render();
  6766. }
  6767. }
  6768. this._renderId++;
  6769. }
  6770. if (this.customRenderTargets.length > 0) {
  6771. engine.restoreDefaultFramebuffer();
  6772. }
  6773. this._renderTargetsDuration += new Date().getTime() - beforeRenderTargetDate;
  6774. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe, true);
  6775. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  6776. var light = this.lights[lightIndex];
  6777. var shadowGenerator = light.getShadowGenerator();
  6778. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  6779. this._renderTargets.push(shadowGenerator.getShadowMap());
  6780. }
  6781. }
  6782. this.postProcessRenderPipelineManager.update();
  6783. if (this.activeCameras.length > 0) {
  6784. var currentRenderId = this._renderId;
  6785. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  6786. this._renderId = currentRenderId;
  6787. this._processSubCameras(this.activeCameras[cameraIndex]);
  6788. }
  6789. } else {
  6790. if (!this.activeCamera) {
  6791. throw new Error("No camera defined");
  6792. }
  6793. this._processSubCameras(this.activeCamera);
  6794. }
  6795. this._checkIntersections();
  6796. if (this.afterRender) {
  6797. this.afterRender();
  6798. }
  6799. for (var index = 0; index < this._toBeDisposed.length; index++) {
  6800. this._toBeDisposed.data[index].dispose();
  6801. this._toBeDisposed[index] = null;
  6802. }
  6803. this._toBeDisposed.reset();
  6804. this._lastFrameDuration = new Date().getTime() - startDate;
  6805. };
  6806. Scene.prototype.dispose = function () {
  6807. this.beforeRender = null;
  6808. this.afterRender = null;
  6809. this.skeletons = [];
  6810. this._boundingBoxRenderer.dispose();
  6811. if (this.onDispose) {
  6812. this.onDispose();
  6813. }
  6814. this.detachControl();
  6815. var canvas = this._engine.getRenderingCanvas();
  6816. var index;
  6817. for (index = 0; index < this.cameras.length; index++) {
  6818. this.cameras[index].detachControl(canvas);
  6819. }
  6820. while (this.lights.length) {
  6821. this.lights[0].dispose();
  6822. }
  6823. while (this.meshes.length) {
  6824. this.meshes[0].dispose(true);
  6825. }
  6826. while (this.cameras.length) {
  6827. this.cameras[0].dispose();
  6828. }
  6829. while (this.materials.length) {
  6830. this.materials[0].dispose();
  6831. }
  6832. while (this.particleSystems.length) {
  6833. this.particleSystems[0].dispose();
  6834. }
  6835. while (this.spriteManagers.length) {
  6836. this.spriteManagers[0].dispose();
  6837. }
  6838. while (this.layers.length) {
  6839. this.layers[0].dispose();
  6840. }
  6841. while (this.textures.length) {
  6842. this.textures[0].dispose();
  6843. }
  6844. this.postProcessManager.dispose();
  6845. if (this._physicsEngine) {
  6846. this.disablePhysicsEngine();
  6847. }
  6848. index = this._engine.scenes.indexOf(this);
  6849. if (index > -1) {
  6850. this._engine.scenes.splice(index, 1);
  6851. }
  6852. this._engine.wipeCaches();
  6853. };
  6854. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6855. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6856. position.divideToRef(collider.radius, this._scaledPosition);
  6857. velocity.divideToRef(collider.radius, this._scaledVelocity);
  6858. collider.retry = 0;
  6859. collider.initialVelocity = this._scaledVelocity;
  6860. collider.initialPosition = this._scaledPosition;
  6861. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  6862. finalPosition.multiplyInPlace(collider.radius);
  6863. };
  6864. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6865. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6866. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  6867. if (collider.retry >= maximumRetry) {
  6868. finalPosition.copyFrom(position);
  6869. return;
  6870. }
  6871. collider._initialize(position, velocity, closeDistance);
  6872. for (var index = 0; index < this.meshes.length; index++) {
  6873. var mesh = this.meshes[index];
  6874. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  6875. mesh._checkCollision(collider);
  6876. }
  6877. }
  6878. if (!collider.collisionFound) {
  6879. position.addToRef(velocity, finalPosition);
  6880. return;
  6881. }
  6882. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  6883. collider._getResponse(position, velocity);
  6884. }
  6885. if (velocity.length() <= closeDistance) {
  6886. finalPosition.copyFrom(position);
  6887. return;
  6888. }
  6889. collider.retry++;
  6890. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  6891. };
  6892. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  6893. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  6894. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  6895. if (!this._selectionOctree) {
  6896. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  6897. }
  6898. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6899. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6900. for (var index = 0; index < this.meshes.length; index++) {
  6901. var mesh = this.meshes[index];
  6902. mesh.computeWorldMatrix(true);
  6903. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  6904. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  6905. BABYLON.Tools.CheckExtends(minBox, min, max);
  6906. BABYLON.Tools.CheckExtends(maxBox, min, max);
  6907. }
  6908. this._selectionOctree.update(min, max, this.meshes);
  6909. return this._selectionOctree;
  6910. };
  6911. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  6912. var engine = this._engine;
  6913. if (!camera) {
  6914. if (!this.activeCamera)
  6915. throw new Error("Active camera not set");
  6916. camera = this.activeCamera;
  6917. }
  6918. var cameraViewport = camera.viewport;
  6919. var viewport = cameraViewport.toGlobal(engine);
  6920. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  6921. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  6922. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  6923. };
  6924. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  6925. var pickingInfo = null;
  6926. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  6927. var mesh = this.meshes[meshIndex];
  6928. if (predicate) {
  6929. if (!predicate(mesh)) {
  6930. continue;
  6931. }
  6932. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  6933. continue;
  6934. }
  6935. var world = mesh.getWorldMatrix();
  6936. var ray = rayFunction(world);
  6937. var result = mesh.intersects(ray, fastCheck);
  6938. if (!result || !result.hit)
  6939. continue;
  6940. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  6941. continue;
  6942. pickingInfo = result;
  6943. if (fastCheck) {
  6944. break;
  6945. }
  6946. }
  6947. return pickingInfo || new BABYLON.PickingInfo();
  6948. };
  6949. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  6950. var _this = this;
  6951. return this._internalPick(function (world) {
  6952. return _this.createPickingRay(x, y, world, camera);
  6953. }, predicate, fastCheck);
  6954. };
  6955. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  6956. var _this = this;
  6957. return this._internalPick(function (world) {
  6958. if (!_this._pickWithRayInverseMatrix) {
  6959. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  6960. }
  6961. world.invertToRef(_this._pickWithRayInverseMatrix);
  6962. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  6963. }, predicate, fastCheck);
  6964. };
  6965. Scene.prototype.setPointerOverMesh = function (mesh) {
  6966. if (this._pointerOverMesh === mesh) {
  6967. return;
  6968. }
  6969. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6970. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6971. }
  6972. this._pointerOverMesh = mesh;
  6973. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6974. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6975. }
  6976. };
  6977. Scene.prototype.getPointerOverMesh = function () {
  6978. return this._pointerOverMesh;
  6979. };
  6980. Scene.prototype.getPhysicsEngine = function () {
  6981. return this._physicsEngine;
  6982. };
  6983. Scene.prototype.enablePhysics = function (gravity, plugin) {
  6984. if (this._physicsEngine) {
  6985. return true;
  6986. }
  6987. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  6988. if (!this._physicsEngine.isSupported()) {
  6989. this._physicsEngine = null;
  6990. return false;
  6991. }
  6992. this._physicsEngine._initialize(gravity);
  6993. return true;
  6994. };
  6995. Scene.prototype.disablePhysicsEngine = function () {
  6996. if (!this._physicsEngine) {
  6997. return;
  6998. }
  6999. this._physicsEngine.dispose();
  7000. this._physicsEngine = undefined;
  7001. };
  7002. Scene.prototype.isPhysicsEnabled = function () {
  7003. return this._physicsEngine !== undefined;
  7004. };
  7005. Scene.prototype.setGravity = function (gravity) {
  7006. if (!this._physicsEngine) {
  7007. return;
  7008. }
  7009. this._physicsEngine._setGravity(gravity);
  7010. };
  7011. Scene.prototype.createCompoundImpostor = function (parts, options) {
  7012. if (parts.parts) {
  7013. options = parts;
  7014. parts = parts.parts;
  7015. }
  7016. if (!this._physicsEngine) {
  7017. return null;
  7018. }
  7019. for (var index = 0; index < parts.length; index++) {
  7020. var mesh = parts[index].mesh;
  7021. mesh._physicImpostor = parts[index].impostor;
  7022. mesh._physicsMass = options.mass / parts.length;
  7023. mesh._physicsFriction = options.friction;
  7024. mesh._physicRestitution = options.restitution;
  7025. }
  7026. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  7027. };
  7028. Scene.prototype.deleteCompoundImpostor = function (compound) {
  7029. for (var index = 0; index < compound.parts.length; index++) {
  7030. var mesh = compound.parts[index].mesh;
  7031. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7032. this._physicsEngine._unregisterMesh(mesh);
  7033. }
  7034. };
  7035. Scene.prototype._getByTags = function (list, tagsQuery) {
  7036. if (tagsQuery === undefined) {
  7037. return list;
  7038. }
  7039. var listByTags = [];
  7040. for (var i in list) {
  7041. var item = list[i];
  7042. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  7043. listByTags.push(item);
  7044. }
  7045. }
  7046. return listByTags;
  7047. };
  7048. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  7049. return this._getByTags(this.meshes, tagsQuery);
  7050. };
  7051. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  7052. return this._getByTags(this.cameras, tagsQuery);
  7053. };
  7054. Scene.prototype.getLightsByTags = function (tagsQuery) {
  7055. return this._getByTags(this.lights, tagsQuery);
  7056. };
  7057. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  7058. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  7059. };
  7060. Scene.FOGMODE_NONE = 0;
  7061. Scene.FOGMODE_EXP = 1;
  7062. Scene.FOGMODE_EXP2 = 2;
  7063. Scene.FOGMODE_LINEAR = 3;
  7064. Scene.MinDeltaTime = 1.0;
  7065. Scene.MaxDeltaTime = 1000.0;
  7066. return Scene;
  7067. })();
  7068. BABYLON.Scene = Scene;
  7069. })(BABYLON || (BABYLON = {}));
  7070. var BABYLON;
  7071. (function (BABYLON) {
  7072. var VertexBuffer = (function () {
  7073. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation) {
  7074. if (engine instanceof BABYLON.Mesh) {
  7075. this._engine = engine.getScene().getEngine();
  7076. } else {
  7077. this._engine = engine;
  7078. }
  7079. this._updatable = updatable;
  7080. this._data = data;
  7081. if (!postponeInternalCreation) {
  7082. this.create();
  7083. }
  7084. this._kind = kind;
  7085. switch (kind) {
  7086. case VertexBuffer.PositionKind:
  7087. this._strideSize = 3;
  7088. break;
  7089. case VertexBuffer.NormalKind:
  7090. this._strideSize = 3;
  7091. break;
  7092. case VertexBuffer.UVKind:
  7093. this._strideSize = 2;
  7094. break;
  7095. case VertexBuffer.UV2Kind:
  7096. this._strideSize = 2;
  7097. break;
  7098. case VertexBuffer.ColorKind:
  7099. this._strideSize = 3;
  7100. break;
  7101. case VertexBuffer.MatricesIndicesKind:
  7102. this._strideSize = 4;
  7103. break;
  7104. case VertexBuffer.MatricesWeightsKind:
  7105. this._strideSize = 4;
  7106. break;
  7107. }
  7108. }
  7109. VertexBuffer.prototype.isUpdatable = function () {
  7110. return this._updatable;
  7111. };
  7112. VertexBuffer.prototype.getData = function () {
  7113. return this._data;
  7114. };
  7115. VertexBuffer.prototype.getBuffer = function () {
  7116. return this._buffer;
  7117. };
  7118. VertexBuffer.prototype.getStrideSize = function () {
  7119. return this._strideSize;
  7120. };
  7121. VertexBuffer.prototype.create = function (data) {
  7122. if (!data && this._buffer) {
  7123. return;
  7124. }
  7125. data = data || this._data;
  7126. if (!this._buffer) {
  7127. if (this._updatable) {
  7128. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  7129. } else {
  7130. this._buffer = this._engine.createVertexBuffer(data);
  7131. }
  7132. }
  7133. if (this._updatable) {
  7134. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7135. this._data = data;
  7136. }
  7137. };
  7138. VertexBuffer.prototype.update = function (data) {
  7139. this.create(data);
  7140. };
  7141. VertexBuffer.prototype.updateDirectly = function (data) {
  7142. if (!this._buffer) {
  7143. return;
  7144. }
  7145. if (this._updatable) {
  7146. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7147. this._data = null;
  7148. }
  7149. };
  7150. VertexBuffer.prototype.dispose = function () {
  7151. if (!this._buffer) {
  7152. return;
  7153. }
  7154. if (this._engine._releaseBuffer(this._buffer)) {
  7155. this._buffer = null;
  7156. }
  7157. };
  7158. Object.defineProperty(VertexBuffer, "PositionKind", {
  7159. get: function () {
  7160. return VertexBuffer._PositionKind;
  7161. },
  7162. enumerable: true,
  7163. configurable: true
  7164. });
  7165. Object.defineProperty(VertexBuffer, "NormalKind", {
  7166. get: function () {
  7167. return VertexBuffer._NormalKind;
  7168. },
  7169. enumerable: true,
  7170. configurable: true
  7171. });
  7172. Object.defineProperty(VertexBuffer, "UVKind", {
  7173. get: function () {
  7174. return VertexBuffer._UVKind;
  7175. },
  7176. enumerable: true,
  7177. configurable: true
  7178. });
  7179. Object.defineProperty(VertexBuffer, "UV2Kind", {
  7180. get: function () {
  7181. return VertexBuffer._UV2Kind;
  7182. },
  7183. enumerable: true,
  7184. configurable: true
  7185. });
  7186. Object.defineProperty(VertexBuffer, "ColorKind", {
  7187. get: function () {
  7188. return VertexBuffer._ColorKind;
  7189. },
  7190. enumerable: true,
  7191. configurable: true
  7192. });
  7193. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  7194. get: function () {
  7195. return VertexBuffer._MatricesIndicesKind;
  7196. },
  7197. enumerable: true,
  7198. configurable: true
  7199. });
  7200. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  7201. get: function () {
  7202. return VertexBuffer._MatricesWeightsKind;
  7203. },
  7204. enumerable: true,
  7205. configurable: true
  7206. });
  7207. VertexBuffer._PositionKind = "position";
  7208. VertexBuffer._NormalKind = "normal";
  7209. VertexBuffer._UVKind = "uv";
  7210. VertexBuffer._UV2Kind = "uv2";
  7211. VertexBuffer._ColorKind = "color";
  7212. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  7213. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  7214. return VertexBuffer;
  7215. })();
  7216. BABYLON.VertexBuffer = VertexBuffer;
  7217. })(BABYLON || (BABYLON = {}));
  7218. var __extends = this.__extends || function (d, b) {
  7219. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7220. function __() { this.constructor = d; }
  7221. __.prototype = b.prototype;
  7222. d.prototype = new __();
  7223. };
  7224. var BABYLON;
  7225. (function (BABYLON) {
  7226. var AbstractMesh = (function (_super) {
  7227. __extends(AbstractMesh, _super);
  7228. function AbstractMesh(name, scene) {
  7229. _super.call(this, name, scene);
  7230. this.position = new BABYLON.Vector3(0, 0, 0);
  7231. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7232. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7233. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  7234. this.visibility = 1.0;
  7235. this.infiniteDistance = false;
  7236. this.isVisible = true;
  7237. this.isPickable = true;
  7238. this.showBoundingBox = false;
  7239. this.showSubMeshesBoundingBox = false;
  7240. this.onDispose = null;
  7241. this.checkCollisions = false;
  7242. this.isBlocker = false;
  7243. this.renderingGroupId = 0;
  7244. this.receiveShadows = false;
  7245. this.renderOutline = false;
  7246. this.outlineColor = BABYLON.Color3.Red();
  7247. this.outlineWidth = 0.02;
  7248. this.useOctreeForRenderingSelection = true;
  7249. this.useOctreeForPicking = true;
  7250. this.useOctreeForCollisions = true;
  7251. this.layerMask = 0xFFFFFFFF;
  7252. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7253. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7254. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7255. this._collider = new BABYLON.Collider();
  7256. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7257. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7258. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7259. this._localScaling = BABYLON.Matrix.Zero();
  7260. this._localRotation = BABYLON.Matrix.Zero();
  7261. this._localTranslation = BABYLON.Matrix.Zero();
  7262. this._localBillboard = BABYLON.Matrix.Zero();
  7263. this._localPivotScaling = BABYLON.Matrix.Zero();
  7264. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7265. this._localWorld = BABYLON.Matrix.Zero();
  7266. this._worldMatrix = BABYLON.Matrix.Zero();
  7267. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7268. this._absolutePosition = BABYLON.Vector3.Zero();
  7269. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7270. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7271. this._isDirty = false;
  7272. this._pivotMatrix = BABYLON.Matrix.Identity();
  7273. this._isDisposed = false;
  7274. this._renderId = 0;
  7275. this._intersectionsInProgress = new Array();
  7276. scene.meshes.push(this);
  7277. }
  7278. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7279. get: function () {
  7280. return AbstractMesh._BILLBOARDMODE_NONE;
  7281. },
  7282. enumerable: true,
  7283. configurable: true
  7284. });
  7285. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7286. get: function () {
  7287. return AbstractMesh._BILLBOARDMODE_X;
  7288. },
  7289. enumerable: true,
  7290. configurable: true
  7291. });
  7292. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7293. get: function () {
  7294. return AbstractMesh._BILLBOARDMODE_Y;
  7295. },
  7296. enumerable: true,
  7297. configurable: true
  7298. });
  7299. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7300. get: function () {
  7301. return AbstractMesh._BILLBOARDMODE_Z;
  7302. },
  7303. enumerable: true,
  7304. configurable: true
  7305. });
  7306. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7307. get: function () {
  7308. return AbstractMesh._BILLBOARDMODE_ALL;
  7309. },
  7310. enumerable: true,
  7311. configurable: true
  7312. });
  7313. AbstractMesh.prototype.getTotalVertices = function () {
  7314. return 0;
  7315. };
  7316. AbstractMesh.prototype.getIndices = function () {
  7317. return null;
  7318. };
  7319. AbstractMesh.prototype.getVerticesData = function (kind) {
  7320. return null;
  7321. };
  7322. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7323. return false;
  7324. };
  7325. AbstractMesh.prototype.getBoundingInfo = function () {
  7326. if (!this._boundingInfo) {
  7327. this._updateBoundingInfo();
  7328. }
  7329. return this._boundingInfo;
  7330. };
  7331. AbstractMesh.prototype._preActivate = function () {
  7332. };
  7333. AbstractMesh.prototype._activate = function (renderId) {
  7334. this._renderId = renderId;
  7335. };
  7336. AbstractMesh.prototype.getWorldMatrix = function () {
  7337. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7338. this.computeWorldMatrix();
  7339. }
  7340. return this._worldMatrix;
  7341. };
  7342. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7343. get: function () {
  7344. return this._worldMatrix;
  7345. },
  7346. enumerable: true,
  7347. configurable: true
  7348. });
  7349. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7350. get: function () {
  7351. return this._absolutePosition;
  7352. },
  7353. enumerable: true,
  7354. configurable: true
  7355. });
  7356. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7357. if (!this.rotationQuaternion) {
  7358. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7359. this.rotation = BABYLON.Vector3.Zero();
  7360. }
  7361. if (!space || space == 0 /* LOCAL */) {
  7362. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7363. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7364. } else {
  7365. if (this.parent) {
  7366. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7367. invertParentWorldMatrix.invert();
  7368. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7369. }
  7370. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7371. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7372. }
  7373. };
  7374. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7375. var displacementVector = axis.scale(distance);
  7376. if (!space || space == 0 /* LOCAL */) {
  7377. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7378. this.setPositionWithLocalVector(tempV3);
  7379. } else {
  7380. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7381. }
  7382. };
  7383. AbstractMesh.prototype.getAbsolutePosition = function () {
  7384. this.computeWorldMatrix();
  7385. return this._absolutePosition;
  7386. };
  7387. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7388. if (!absolutePosition) {
  7389. return;
  7390. }
  7391. var absolutePositionX;
  7392. var absolutePositionY;
  7393. var absolutePositionZ;
  7394. if (absolutePosition.x === undefined) {
  7395. if (arguments.length < 3) {
  7396. return;
  7397. }
  7398. absolutePositionX = arguments[0];
  7399. absolutePositionY = arguments[1];
  7400. absolutePositionZ = arguments[2];
  7401. } else {
  7402. absolutePositionX = absolutePosition.x;
  7403. absolutePositionY = absolutePosition.y;
  7404. absolutePositionZ = absolutePosition.z;
  7405. }
  7406. if (this.parent) {
  7407. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7408. invertParentWorldMatrix.invert();
  7409. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7410. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7411. } else {
  7412. this.position.x = absolutePositionX;
  7413. this.position.y = absolutePositionY;
  7414. this.position.z = absolutePositionZ;
  7415. }
  7416. };
  7417. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7418. this._pivotMatrix = matrix;
  7419. this._cache.pivotMatrixUpdated = true;
  7420. };
  7421. AbstractMesh.prototype.getPivotMatrix = function () {
  7422. return this._pivotMatrix;
  7423. };
  7424. AbstractMesh.prototype._isSynchronized = function () {
  7425. if (this._isDirty) {
  7426. return false;
  7427. }
  7428. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7429. return false;
  7430. if (this._cache.pivotMatrixUpdated) {
  7431. return false;
  7432. }
  7433. if (this.infiniteDistance) {
  7434. return false;
  7435. }
  7436. if (!this._cache.position.equals(this.position))
  7437. return false;
  7438. if (this.rotationQuaternion) {
  7439. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7440. return false;
  7441. } else {
  7442. if (!this._cache.rotation.equals(this.rotation))
  7443. return false;
  7444. }
  7445. if (!this._cache.scaling.equals(this.scaling))
  7446. return false;
  7447. return true;
  7448. };
  7449. AbstractMesh.prototype._initCache = function () {
  7450. _super.prototype._initCache.call(this);
  7451. this._cache.localMatrixUpdated = false;
  7452. this._cache.position = BABYLON.Vector3.Zero();
  7453. this._cache.scaling = BABYLON.Vector3.Zero();
  7454. this._cache.rotation = BABYLON.Vector3.Zero();
  7455. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7456. };
  7457. AbstractMesh.prototype.markAsDirty = function (property) {
  7458. if (property === "rotation") {
  7459. this.rotationQuaternion = null;
  7460. }
  7461. this._currentRenderId = Number.MAX_VALUE;
  7462. this._isDirty = true;
  7463. };
  7464. AbstractMesh.prototype._updateBoundingInfo = function () {
  7465. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7466. this._boundingInfo._update(this.worldMatrixFromCache);
  7467. if (!this.subMeshes) {
  7468. return;
  7469. }
  7470. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7471. var subMesh = this.subMeshes[subIndex];
  7472. subMesh.updateBoundingInfo(this.worldMatrixFromCache);
  7473. }
  7474. };
  7475. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7476. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  7477. return this._worldMatrix;
  7478. }
  7479. this._cache.position.copyFrom(this.position);
  7480. this._cache.scaling.copyFrom(this.scaling);
  7481. this._cache.pivotMatrixUpdated = false;
  7482. this._currentRenderId = this.getScene().getRenderId();
  7483. this._isDirty = false;
  7484. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7485. if (this.rotationQuaternion) {
  7486. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7487. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7488. } else {
  7489. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7490. this._cache.rotation.copyFrom(this.rotation);
  7491. }
  7492. if (this.infiniteDistance && !this.parent) {
  7493. var camera = this.getScene().activeCamera;
  7494. var cameraWorldMatrix = camera.getWorldMatrix();
  7495. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7496. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7497. } else {
  7498. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7499. }
  7500. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7501. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7502. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7503. var localPosition = this.position.clone();
  7504. var zero = this.getScene().activeCamera.position.clone();
  7505. if (this.parent && this.parent.position) {
  7506. localPosition.addInPlace(this.parent.position);
  7507. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7508. }
  7509. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  7510. zero = this.getScene().activeCamera.position;
  7511. } else {
  7512. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  7513. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7514. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  7515. zero.y = localPosition.y + 0.001;
  7516. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  7517. zero.z = localPosition.z + 0.001;
  7518. }
  7519. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7520. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7521. this._localBillboard.invert();
  7522. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7523. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7524. }
  7525. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7526. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  7527. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7528. } else {
  7529. this._worldMatrix.copyFrom(this._localWorld);
  7530. }
  7531. this._updateBoundingInfo();
  7532. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7533. return this._worldMatrix;
  7534. };
  7535. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7536. this.computeWorldMatrix();
  7537. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7538. };
  7539. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7540. this.computeWorldMatrix();
  7541. var invLocalWorldMatrix = this._localWorld.clone();
  7542. invLocalWorldMatrix.invert();
  7543. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7544. };
  7545. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7546. this.computeWorldMatrix();
  7547. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7548. };
  7549. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7550. yawCor = yawCor || 0;
  7551. pitchCor = pitchCor || 0;
  7552. rollCor = rollCor || 0;
  7553. var dv = targetPoint.subtract(this.position);
  7554. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7555. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7556. var pitch = Math.atan2(dv.y, len);
  7557. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7558. };
  7559. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7560. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  7561. return false;
  7562. }
  7563. return true;
  7564. };
  7565. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7566. if (!this._boundingInfo || !mesh._boundingInfo) {
  7567. return false;
  7568. }
  7569. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  7570. };
  7571. AbstractMesh.prototype.intersectsPoint = function (point) {
  7572. if (!this._boundingInfo) {
  7573. return false;
  7574. }
  7575. return this._boundingInfo.intersectsPoint(point);
  7576. };
  7577. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  7578. var physicsEngine = this.getScene().getPhysicsEngine();
  7579. if (!physicsEngine) {
  7580. return;
  7581. }
  7582. if (impostor.impostor) {
  7583. options = impostor;
  7584. impostor = impostor.impostor;
  7585. }
  7586. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  7587. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  7588. physicsEngine._unregisterMesh(this);
  7589. return;
  7590. }
  7591. options.mass = options.mass || 0;
  7592. options.friction = options.friction || 0.2;
  7593. options.restitution = options.restitution || 0.2;
  7594. this._physicImpostor = impostor;
  7595. this._physicsMass = options.mass;
  7596. this._physicsFriction = options.friction;
  7597. this._physicRestitution = options.restitution;
  7598. physicsEngine._registerMesh(this, impostor, options);
  7599. };
  7600. AbstractMesh.prototype.getPhysicsImpostor = function () {
  7601. if (!this._physicImpostor) {
  7602. return BABYLON.PhysicsEngine.NoImpostor;
  7603. }
  7604. return this._physicImpostor;
  7605. };
  7606. AbstractMesh.prototype.getPhysicsMass = function () {
  7607. if (!this._physicsMass) {
  7608. return 0;
  7609. }
  7610. return this._physicsMass;
  7611. };
  7612. AbstractMesh.prototype.getPhysicsFriction = function () {
  7613. if (!this._physicsFriction) {
  7614. return 0;
  7615. }
  7616. return this._physicsFriction;
  7617. };
  7618. AbstractMesh.prototype.getPhysicsRestitution = function () {
  7619. if (!this._physicRestitution) {
  7620. return 0;
  7621. }
  7622. return this._physicRestitution;
  7623. };
  7624. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  7625. if (!this._physicImpostor) {
  7626. return;
  7627. }
  7628. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  7629. };
  7630. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  7631. if (!this._physicImpostor) {
  7632. return;
  7633. }
  7634. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  7635. };
  7636. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  7637. if (!this._physicImpostor) {
  7638. return;
  7639. }
  7640. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  7641. };
  7642. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  7643. var globalPosition = this.getAbsolutePosition();
  7644. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  7645. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  7646. this._collider.radius = this.ellipsoid;
  7647. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  7648. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  7649. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7650. this.position.addInPlace(this._diffPositionForCollisions);
  7651. }
  7652. };
  7653. /**
  7654. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  7655. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  7656. */
  7657. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  7658. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7659. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7660. if (!this._submeshesOctree) {
  7661. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  7662. }
  7663. this.computeWorldMatrix(true);
  7664. var bbox = this.getBoundingInfo().boundingBox;
  7665. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  7666. return this._submeshesOctree;
  7667. };
  7668. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  7669. this._generatePointsArray();
  7670. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  7671. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  7672. subMesh._lastColliderWorldVertices = [];
  7673. subMesh._trianglePlanes = [];
  7674. var start = subMesh.verticesStart;
  7675. var end = (subMesh.verticesStart + subMesh.verticesCount);
  7676. for (var i = start; i < end; i++) {
  7677. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  7678. }
  7679. }
  7680. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  7681. };
  7682. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  7683. var subMeshes;
  7684. var len;
  7685. if (this._submeshesOctree && this.useOctreeForCollisions) {
  7686. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  7687. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  7688. len = intersections.length;
  7689. subMeshes = intersections.data;
  7690. } else {
  7691. subMeshes = this.subMeshes;
  7692. len = subMeshes.length;
  7693. }
  7694. for (var index = 0; index < len; index++) {
  7695. var subMesh = subMeshes[index];
  7696. if (len > 1 && !subMesh._checkCollision(collider))
  7697. continue;
  7698. this._collideForSubMesh(subMesh, transformMatrix, collider);
  7699. }
  7700. };
  7701. AbstractMesh.prototype._checkCollision = function (collider) {
  7702. if (!this._boundingInfo._checkCollision(collider))
  7703. return;
  7704. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  7705. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  7706. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  7707. };
  7708. AbstractMesh.prototype._generatePointsArray = function () {
  7709. return false;
  7710. };
  7711. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  7712. var pickingInfo = new BABYLON.PickingInfo();
  7713. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  7714. return pickingInfo;
  7715. }
  7716. if (!this._generatePointsArray()) {
  7717. return pickingInfo;
  7718. }
  7719. var intersectInfo = null;
  7720. var subMeshes;
  7721. var len;
  7722. if (this._submeshesOctree && this.useOctreeForPicking) {
  7723. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  7724. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  7725. len = intersections.length;
  7726. subMeshes = intersections.data;
  7727. } else {
  7728. subMeshes = this.subMeshes;
  7729. len = subMeshes.length;
  7730. }
  7731. for (var index = 0; index < len; index++) {
  7732. var subMesh = subMeshes[index];
  7733. if (len > 1 && !subMesh.canIntersects(ray))
  7734. continue;
  7735. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  7736. if (currentIntersectInfo) {
  7737. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  7738. intersectInfo = currentIntersectInfo;
  7739. if (fastCheck) {
  7740. break;
  7741. }
  7742. }
  7743. }
  7744. }
  7745. if (intersectInfo) {
  7746. var world = this.getWorldMatrix();
  7747. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  7748. var direction = ray.direction.clone();
  7749. direction.normalize();
  7750. direction = direction.scale(intersectInfo.distance);
  7751. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  7752. var pickedPoint = worldOrigin.add(worldDirection);
  7753. pickingInfo.hit = true;
  7754. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  7755. pickingInfo.pickedPoint = pickedPoint;
  7756. pickingInfo.pickedMesh = this;
  7757. pickingInfo.bu = intersectInfo.bu;
  7758. pickingInfo.bv = intersectInfo.bv;
  7759. pickingInfo.faceId = intersectInfo.faceId;
  7760. return pickingInfo;
  7761. }
  7762. return pickingInfo;
  7763. };
  7764. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  7765. return null;
  7766. };
  7767. AbstractMesh.prototype.releaseSubMeshes = function () {
  7768. if (this.subMeshes) {
  7769. while (this.subMeshes.length) {
  7770. this.subMeshes[0].dispose();
  7771. }
  7772. } else {
  7773. this.subMeshes = new Array();
  7774. }
  7775. };
  7776. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  7777. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  7778. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  7779. }
  7780. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  7781. var other = this._intersectionsInProgress[index];
  7782. var pos = other._intersectionsInProgress.indexOf(this);
  7783. other._intersectionsInProgress.splice(pos, 1);
  7784. }
  7785. this._intersectionsInProgress = [];
  7786. this.releaseSubMeshes();
  7787. var index = this.getScene().meshes.indexOf(this);
  7788. if (index != -1) {
  7789. this.getScene().meshes.splice(index, 1);
  7790. }
  7791. if (!doNotRecurse) {
  7792. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  7793. if (this.getScene().particleSystems[index].emitter == this) {
  7794. this.getScene().particleSystems[index].dispose();
  7795. index--;
  7796. }
  7797. }
  7798. var objects = this.getScene().meshes.slice(0);
  7799. for (index = 0; index < objects.length; index++) {
  7800. if (objects[index].parent == this) {
  7801. objects[index].dispose();
  7802. }
  7803. }
  7804. } else {
  7805. for (index = 0; index < this.getScene().meshes.length; index++) {
  7806. var obj = this.getScene().meshes[index];
  7807. if (obj.parent === this) {
  7808. obj.parent = null;
  7809. obj.computeWorldMatrix(true);
  7810. }
  7811. }
  7812. }
  7813. this._isDisposed = true;
  7814. if (this.onDispose) {
  7815. this.onDispose();
  7816. }
  7817. };
  7818. AbstractMesh._BILLBOARDMODE_NONE = 0;
  7819. AbstractMesh._BILLBOARDMODE_X = 1;
  7820. AbstractMesh._BILLBOARDMODE_Y = 2;
  7821. AbstractMesh._BILLBOARDMODE_Z = 4;
  7822. AbstractMesh._BILLBOARDMODE_ALL = 7;
  7823. return AbstractMesh;
  7824. })(BABYLON.Node);
  7825. BABYLON.AbstractMesh = AbstractMesh;
  7826. })(BABYLON || (BABYLON = {}));
  7827. var __extends = this.__extends || function (d, b) {
  7828. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7829. function __() { this.constructor = d; }
  7830. __.prototype = b.prototype;
  7831. d.prototype = new __();
  7832. };
  7833. var BABYLON;
  7834. (function (BABYLON) {
  7835. var _InstancesBatch = (function () {
  7836. function _InstancesBatch() {
  7837. this.mustReturn = false;
  7838. this.visibleInstances = new Array();
  7839. this.renderSelf = new Array();
  7840. }
  7841. return _InstancesBatch;
  7842. })();
  7843. BABYLON._InstancesBatch = _InstancesBatch;
  7844. var Mesh = (function (_super) {
  7845. __extends(Mesh, _super);
  7846. function Mesh(name, scene) {
  7847. _super.call(this, name, scene);
  7848. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  7849. this.instances = new Array();
  7850. this._onBeforeRenderCallbacks = new Array();
  7851. this._onAfterRenderCallbacks = new Array();
  7852. this._visibleInstances = {};
  7853. this._renderIdForInstances = new Array();
  7854. this._batchCache = new _InstancesBatch();
  7855. this._instancesBufferSize = 32 * 16 * 4;
  7856. }
  7857. Mesh.prototype.getTotalVertices = function () {
  7858. if (!this._geometry) {
  7859. return 0;
  7860. }
  7861. return this._geometry.getTotalVertices();
  7862. };
  7863. Mesh.prototype.getVerticesData = function (kind) {
  7864. if (!this._geometry) {
  7865. return null;
  7866. }
  7867. return this._geometry.getVerticesData(kind);
  7868. };
  7869. Mesh.prototype.getVertexBuffer = function (kind) {
  7870. if (!this._geometry) {
  7871. return undefined;
  7872. }
  7873. return this._geometry.getVertexBuffer(kind);
  7874. };
  7875. Mesh.prototype.isVerticesDataPresent = function (kind) {
  7876. if (!this._geometry) {
  7877. if (this._delayInfo) {
  7878. return this._delayInfo.indexOf(kind) !== -1;
  7879. }
  7880. return false;
  7881. }
  7882. return this._geometry.isVerticesDataPresent(kind);
  7883. };
  7884. Mesh.prototype.getVerticesDataKinds = function () {
  7885. if (!this._geometry) {
  7886. var result = [];
  7887. if (this._delayInfo) {
  7888. for (var kind in this._delayInfo) {
  7889. result.push(kind);
  7890. }
  7891. }
  7892. return result;
  7893. }
  7894. return this._geometry.getVerticesDataKinds();
  7895. };
  7896. Mesh.prototype.getTotalIndices = function () {
  7897. if (!this._geometry) {
  7898. return 0;
  7899. }
  7900. return this._geometry.getTotalIndices();
  7901. };
  7902. Mesh.prototype.getIndices = function () {
  7903. if (!this._geometry) {
  7904. return [];
  7905. }
  7906. return this._geometry.getIndices();
  7907. };
  7908. Mesh.prototype.isReady = function () {
  7909. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7910. return false;
  7911. }
  7912. return _super.prototype.isReady.call(this);
  7913. };
  7914. Mesh.prototype.isDisposed = function () {
  7915. return this._isDisposed;
  7916. };
  7917. Mesh.prototype._preActivate = function () {
  7918. var sceneRenderId = this.getScene().getRenderId();
  7919. if (this._preActivateId == sceneRenderId) {
  7920. return;
  7921. }
  7922. this._preActivateId = sceneRenderId;
  7923. this._visibleInstances = null;
  7924. };
  7925. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  7926. if (!this._visibleInstances) {
  7927. this._visibleInstances = {};
  7928. this._visibleInstances.defaultRenderId = renderId;
  7929. this._visibleInstances.selfDefaultRenderId = this._renderId;
  7930. }
  7931. if (!this._visibleInstances[renderId]) {
  7932. this._visibleInstances[renderId] = new Array();
  7933. }
  7934. this._visibleInstances[renderId].push(instance);
  7935. };
  7936. Mesh.prototype.refreshBoundingInfo = function () {
  7937. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7938. if (data) {
  7939. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  7940. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  7941. }
  7942. if (this.subMeshes) {
  7943. for (var index = 0; index < this.subMeshes.length; index++) {
  7944. this.subMeshes[index].refreshBoundingInfo();
  7945. }
  7946. }
  7947. this._updateBoundingInfo();
  7948. };
  7949. Mesh.prototype._createGlobalSubMesh = function () {
  7950. var totalVertices = this.getTotalVertices();
  7951. if (!totalVertices || !this.getIndices()) {
  7952. return null;
  7953. }
  7954. this.releaseSubMeshes();
  7955. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  7956. };
  7957. Mesh.prototype.subdivide = function (count) {
  7958. if (count < 1) {
  7959. return;
  7960. }
  7961. var totalIndices = this.getTotalIndices();
  7962. var subdivisionSize = (totalIndices / count) | 0;
  7963. var offset = 0;
  7964. while (subdivisionSize % 3 != 0) {
  7965. subdivisionSize++;
  7966. }
  7967. this.releaseSubMeshes();
  7968. for (var index = 0; index < count; index++) {
  7969. if (offset >= totalIndices) {
  7970. break;
  7971. }
  7972. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  7973. offset += subdivisionSize;
  7974. }
  7975. this.synchronizeInstances();
  7976. };
  7977. Mesh.prototype.setVerticesData = function (kind, data, updatable) {
  7978. if (kind instanceof Array) {
  7979. var temp = data;
  7980. data = kind;
  7981. kind = temp;
  7982. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  7983. }
  7984. if (!this._geometry) {
  7985. var vertexData = new BABYLON.VertexData();
  7986. vertexData.set(data, kind);
  7987. var scene = this.getScene();
  7988. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  7989. } else {
  7990. this._geometry.setVerticesData(kind, data, updatable);
  7991. }
  7992. };
  7993. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  7994. if (!this._geometry) {
  7995. return;
  7996. }
  7997. if (!makeItUnique) {
  7998. this._geometry.updateVerticesData(kind, data, updateExtends);
  7999. } else {
  8000. this.makeGeometryUnique();
  8001. this.updateVerticesData(kind, data, updateExtends, false);
  8002. }
  8003. };
  8004. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, makeItUnique) {
  8005. if (!this._geometry) {
  8006. return;
  8007. }
  8008. if (!makeItUnique) {
  8009. this._geometry.updateVerticesDataDirectly(kind, data);
  8010. } else {
  8011. this.makeGeometryUnique();
  8012. this.updateVerticesDataDirectly(kind, data, false);
  8013. }
  8014. };
  8015. Mesh.prototype.makeGeometryUnique = function () {
  8016. if (!this._geometry) {
  8017. return;
  8018. }
  8019. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  8020. geometry.applyToMesh(this);
  8021. };
  8022. Mesh.prototype.setIndices = function (indices) {
  8023. if (!this._geometry) {
  8024. var vertexData = new BABYLON.VertexData();
  8025. vertexData.indices = indices;
  8026. var scene = this.getScene();
  8027. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  8028. } else {
  8029. this._geometry.setIndices(indices);
  8030. }
  8031. };
  8032. Mesh.prototype._bind = function (subMesh, effect, wireframe) {
  8033. var engine = this.getScene().getEngine();
  8034. var indexToBind = this._geometry.getIndexBuffer();
  8035. if (wireframe) {
  8036. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  8037. }
  8038. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  8039. };
  8040. Mesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  8041. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8042. return;
  8043. }
  8044. var engine = this.getScene().getEngine();
  8045. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  8046. };
  8047. Mesh.prototype._fullDraw = function (subMesh, useTriangles, instancesCount) {
  8048. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8049. return;
  8050. }
  8051. var engine = this.getScene().getEngine();
  8052. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  8053. };
  8054. Mesh.prototype.registerBeforeRender = function (func) {
  8055. this._onBeforeRenderCallbacks.push(func);
  8056. };
  8057. Mesh.prototype.unregisterBeforeRender = function (func) {
  8058. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8059. if (index > -1) {
  8060. this._onBeforeRenderCallbacks.splice(index, 1);
  8061. }
  8062. };
  8063. Mesh.prototype.registerAfterRender = function (func) {
  8064. this._onAfterRenderCallbacks.push(func);
  8065. };
  8066. Mesh.prototype.unregisterAfterRender = function (func) {
  8067. var index = this._onAfterRenderCallbacks.indexOf(func);
  8068. if (index > -1) {
  8069. this._onAfterRenderCallbacks.splice(index, 1);
  8070. }
  8071. };
  8072. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  8073. var scene = this.getScene();
  8074. this._batchCache.mustReturn = false;
  8075. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  8076. this._batchCache.visibleInstances[subMeshId] = null;
  8077. if (this._visibleInstances) {
  8078. var currentRenderId = scene.getRenderId();
  8079. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  8080. var selfRenderId = this._renderId;
  8081. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  8082. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  8083. currentRenderId = this._visibleInstances.defaultRenderId;
  8084. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  8085. }
  8086. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  8087. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  8088. this._batchCache.mustReturn = true;
  8089. return this._batchCache;
  8090. }
  8091. if (currentRenderId !== selfRenderId) {
  8092. this._batchCache.renderSelf[subMeshId] = false;
  8093. }
  8094. }
  8095. this._renderIdForInstances[subMeshId] = currentRenderId;
  8096. }
  8097. return this._batchCache;
  8098. };
  8099. Mesh.prototype._renderWithInstances = function (subMesh, wireFrame, batch, effect, engine) {
  8100. var matricesCount = this.instances.length + 1;
  8101. var bufferSize = matricesCount * 16 * 4;
  8102. while (this._instancesBufferSize < bufferSize) {
  8103. this._instancesBufferSize *= 2;
  8104. }
  8105. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  8106. if (this._worldMatricesInstancesBuffer) {
  8107. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8108. }
  8109. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  8110. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  8111. }
  8112. var offset = 0;
  8113. var instancesCount = 0;
  8114. var world = this.getWorldMatrix();
  8115. if (batch.renderSelf[subMesh._id]) {
  8116. world.copyToArray(this._worldMatricesInstancesArray, offset);
  8117. offset += 16;
  8118. instancesCount++;
  8119. }
  8120. var visibleInstances = batch.visibleInstances[subMesh._id];
  8121. if (visibleInstances) {
  8122. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  8123. var instance = visibleInstances[instanceIndex];
  8124. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  8125. offset += 16;
  8126. instancesCount++;
  8127. }
  8128. }
  8129. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  8130. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  8131. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  8132. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  8133. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  8134. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  8135. this._draw(subMesh, !wireFrame, instancesCount);
  8136. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  8137. };
  8138. Mesh.prototype.render = function (subMesh) {
  8139. var scene = this.getScene();
  8140. var batch = this._getInstancesRenderList(subMesh._id);
  8141. if (batch.mustReturn) {
  8142. return;
  8143. }
  8144. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8145. return;
  8146. }
  8147. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8148. this._onBeforeRenderCallbacks[callbackIndex]();
  8149. }
  8150. var engine = scene.getEngine();
  8151. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8152. var effectiveMaterial = subMesh.getMaterial();
  8153. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  8154. return;
  8155. }
  8156. var savedDepthWrite = engine.getDepthWrite();
  8157. if (this.renderOutline) {
  8158. engine.setDepthWrite(false);
  8159. scene.getOutlineRenderer().render(subMesh, batch);
  8160. }
  8161. effectiveMaterial._preBind();
  8162. var effect = effectiveMaterial.getEffect();
  8163. var wireFrame = engine.forceWireframe || effectiveMaterial.wireframe;
  8164. this._bind(subMesh, effect, wireFrame);
  8165. var world = this.getWorldMatrix();
  8166. effectiveMaterial.bind(world, this);
  8167. if (hardwareInstancedRendering) {
  8168. this._renderWithInstances(subMesh, wireFrame, batch, effect, engine);
  8169. } else {
  8170. if (batch.renderSelf[subMesh._id]) {
  8171. this._draw(subMesh, !wireFrame);
  8172. }
  8173. if (batch.visibleInstances[subMesh._id]) {
  8174. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  8175. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  8176. world = instance.getWorldMatrix();
  8177. effectiveMaterial.bindOnlyWorldMatrix(world);
  8178. this._draw(subMesh, !wireFrame);
  8179. }
  8180. }
  8181. }
  8182. effectiveMaterial.unbind();
  8183. if (this.renderOutline && savedDepthWrite) {
  8184. engine.setDepthWrite(true);
  8185. engine.setColorWrite(false);
  8186. scene.getOutlineRenderer().render(subMesh, batch);
  8187. engine.setColorWrite(true);
  8188. }
  8189. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8190. this._onAfterRenderCallbacks[callbackIndex]();
  8191. }
  8192. };
  8193. Mesh.prototype.getEmittedParticleSystems = function () {
  8194. var results = new Array();
  8195. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8196. var particleSystem = this.getScene().particleSystems[index];
  8197. if (particleSystem.emitter === this) {
  8198. results.push(particleSystem);
  8199. }
  8200. }
  8201. return results;
  8202. };
  8203. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  8204. var results = new Array();
  8205. var descendants = this.getDescendants();
  8206. descendants.push(this);
  8207. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8208. var particleSystem = this.getScene().particleSystems[index];
  8209. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  8210. results.push(particleSystem);
  8211. }
  8212. }
  8213. return results;
  8214. };
  8215. Mesh.prototype.getChildren = function () {
  8216. var results = [];
  8217. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8218. var mesh = this.getScene().meshes[index];
  8219. if (mesh.parent == this) {
  8220. results.push(mesh);
  8221. }
  8222. }
  8223. return results;
  8224. };
  8225. Mesh.prototype._checkDelayState = function () {
  8226. var _this = this;
  8227. var that = this;
  8228. var scene = this.getScene();
  8229. if (this._geometry) {
  8230. this._geometry.load(scene);
  8231. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8232. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  8233. scene._addPendingData(that);
  8234. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  8235. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  8236. if (data instanceof ArrayBuffer) {
  8237. _this._delayLoadingFunction(data, _this);
  8238. } else {
  8239. _this._delayLoadingFunction(JSON.parse(data), _this);
  8240. }
  8241. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  8242. scene._removePendingData(_this);
  8243. }, function () {
  8244. }, scene.database, getBinaryData);
  8245. }
  8246. };
  8247. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  8248. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8249. return false;
  8250. }
  8251. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  8252. return false;
  8253. }
  8254. this._checkDelayState();
  8255. return true;
  8256. };
  8257. Mesh.prototype.setMaterialByID = function (id) {
  8258. var materials = this.getScene().materials;
  8259. for (var index = 0; index < materials.length; index++) {
  8260. if (materials[index].id == id) {
  8261. this.material = materials[index];
  8262. return;
  8263. }
  8264. }
  8265. var multiMaterials = this.getScene().multiMaterials;
  8266. for (index = 0; index < multiMaterials.length; index++) {
  8267. if (multiMaterials[index].id == id) {
  8268. this.material = multiMaterials[index];
  8269. return;
  8270. }
  8271. }
  8272. };
  8273. Mesh.prototype.getAnimatables = function () {
  8274. var results = [];
  8275. if (this.material) {
  8276. results.push(this.material);
  8277. }
  8278. if (this.skeleton) {
  8279. results.push(this.skeleton);
  8280. }
  8281. return results;
  8282. };
  8283. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  8284. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  8285. return;
  8286. }
  8287. this._resetPointsArrayCache();
  8288. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8289. var temp = [];
  8290. for (var index = 0; index < data.length; index += 3) {
  8291. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8292. }
  8293. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  8294. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8295. return;
  8296. }
  8297. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8298. for (index = 0; index < data.length; index += 3) {
  8299. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8300. }
  8301. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  8302. };
  8303. Mesh.prototype._resetPointsArrayCache = function () {
  8304. this._positions = null;
  8305. };
  8306. Mesh.prototype._generatePointsArray = function () {
  8307. if (this._positions)
  8308. return true;
  8309. this._positions = [];
  8310. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8311. if (!data) {
  8312. return false;
  8313. }
  8314. for (var index = 0; index < data.length; index += 3) {
  8315. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  8316. }
  8317. return true;
  8318. };
  8319. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8320. var result = new BABYLON.Mesh(name, this.getScene());
  8321. this._geometry.applyToMesh(result);
  8322. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  8323. result.material = this.material;
  8324. if (newParent) {
  8325. result.parent = newParent;
  8326. }
  8327. if (!doNotCloneChildren) {
  8328. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8329. var mesh = this.getScene().meshes[index];
  8330. if (mesh.parent == this) {
  8331. mesh.clone(mesh.name, result);
  8332. }
  8333. }
  8334. }
  8335. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8336. var system = this.getScene().particleSystems[index];
  8337. if (system.emitter == this) {
  8338. system.clone(system.name, result);
  8339. }
  8340. }
  8341. result.computeWorldMatrix(true);
  8342. return result;
  8343. };
  8344. Mesh.prototype.dispose = function (doNotRecurse) {
  8345. if (this._geometry) {
  8346. this._geometry.releaseForMesh(this, true);
  8347. }
  8348. if (this._worldMatricesInstancesBuffer) {
  8349. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8350. this._worldMatricesInstancesBuffer = null;
  8351. }
  8352. while (this.instances.length) {
  8353. this.instances[0].dispose();
  8354. }
  8355. _super.prototype.dispose.call(this, doNotRecurse);
  8356. };
  8357. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  8358. var _this = this;
  8359. var scene = this.getScene();
  8360. var onload = function (img) {
  8361. var canvas = document.createElement("canvas");
  8362. var context = canvas.getContext("2d");
  8363. var heightMapWidth = img.width;
  8364. var heightMapHeight = img.height;
  8365. canvas.width = heightMapWidth;
  8366. canvas.height = heightMapHeight;
  8367. context.drawImage(img, 0, 0);
  8368. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8369. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  8370. };
  8371. BABYLON.Tools.LoadImage(url, onload, function () {
  8372. }, scene.database);
  8373. };
  8374. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  8375. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8376. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  8377. return;
  8378. }
  8379. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8380. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8381. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8382. var position = BABYLON.Vector3.Zero();
  8383. var normal = BABYLON.Vector3.Zero();
  8384. var uv = BABYLON.Vector2.Zero();
  8385. for (var index = 0; index < positions.length; index += 3) {
  8386. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  8387. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  8388. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  8389. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  8390. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  8391. var pos = (u + v * heightMapWidth) * 4;
  8392. var r = buffer[pos] / 255.0;
  8393. var g = buffer[pos + 1] / 255.0;
  8394. var b = buffer[pos + 2] / 255.0;
  8395. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  8396. normal.normalize();
  8397. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  8398. position = position.add(normal);
  8399. position.toArray(positions, index);
  8400. }
  8401. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  8402. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  8403. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  8404. };
  8405. Mesh.prototype.convertToFlatShadedMesh = function () {
  8406. var kinds = this.getVerticesDataKinds();
  8407. var vbs = [];
  8408. var data = [];
  8409. var newdata = [];
  8410. var updatableNormals = false;
  8411. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8412. var kind = kinds[kindIndex];
  8413. var vertexBuffer = this.getVertexBuffer(kind);
  8414. if (kind === BABYLON.VertexBuffer.NormalKind) {
  8415. updatableNormals = vertexBuffer.isUpdatable();
  8416. kinds.splice(kindIndex, 1);
  8417. kindIndex--;
  8418. continue;
  8419. }
  8420. vbs[kind] = vertexBuffer;
  8421. data[kind] = vbs[kind].getData();
  8422. newdata[kind] = [];
  8423. }
  8424. var previousSubmeshes = this.subMeshes.slice(0);
  8425. var indices = this.getIndices();
  8426. var totalIndices = this.getTotalIndices();
  8427. for (index = 0; index < totalIndices; index++) {
  8428. var vertexIndex = indices[index];
  8429. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8430. kind = kinds[kindIndex];
  8431. var stride = vbs[kind].getStrideSize();
  8432. for (var offset = 0; offset < stride; offset++) {
  8433. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  8434. }
  8435. }
  8436. }
  8437. var normals = [];
  8438. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  8439. for (var index = 0; index < totalIndices; index += 3) {
  8440. indices[index] = index;
  8441. indices[index + 1] = index + 1;
  8442. indices[index + 2] = index + 2;
  8443. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  8444. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  8445. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  8446. var p1p2 = p1.subtract(p2);
  8447. var p3p2 = p3.subtract(p2);
  8448. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  8449. for (var localIndex = 0; localIndex < 3; localIndex++) {
  8450. normals.push(normal.x);
  8451. normals.push(normal.y);
  8452. normals.push(normal.z);
  8453. }
  8454. }
  8455. this.setIndices(indices);
  8456. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  8457. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8458. kind = kinds[kindIndex];
  8459. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  8460. }
  8461. this.releaseSubMeshes();
  8462. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  8463. var previousOne = previousSubmeshes[submeshIndex];
  8464. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  8465. }
  8466. this.synchronizeInstances();
  8467. };
  8468. Mesh.prototype.createInstance = function (name) {
  8469. return new BABYLON.InstancedMesh(name, this);
  8470. };
  8471. Mesh.prototype.synchronizeInstances = function () {
  8472. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  8473. var instance = this.instances[instanceIndex];
  8474. instance._syncSubMeshes();
  8475. }
  8476. };
  8477. Mesh.CreateBox = function (name, size, scene, updatable) {
  8478. var box = new BABYLON.Mesh(name, scene);
  8479. var vertexData = BABYLON.VertexData.CreateBox(size);
  8480. vertexData.applyToMesh(box, updatable);
  8481. return box;
  8482. };
  8483. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  8484. var sphere = new BABYLON.Mesh(name, scene);
  8485. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  8486. vertexData.applyToMesh(sphere, updatable);
  8487. return sphere;
  8488. };
  8489. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  8490. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  8491. if (scene !== undefined) {
  8492. updatable = scene;
  8493. }
  8494. scene = subdivisions;
  8495. subdivisions = 1;
  8496. }
  8497. var cylinder = new BABYLON.Mesh(name, scene);
  8498. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  8499. vertexData.applyToMesh(cylinder, updatable);
  8500. return cylinder;
  8501. };
  8502. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  8503. var torus = new BABYLON.Mesh(name, scene);
  8504. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  8505. vertexData.applyToMesh(torus, updatable);
  8506. return torus;
  8507. };
  8508. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  8509. var torusKnot = new BABYLON.Mesh(name, scene);
  8510. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  8511. vertexData.applyToMesh(torusKnot, updatable);
  8512. return torusKnot;
  8513. };
  8514. Mesh.CreateLines = function (name, points, scene, updatable) {
  8515. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  8516. var vertexData = BABYLON.VertexData.CreateLines(points);
  8517. vertexData.applyToMesh(lines, updatable);
  8518. return lines;
  8519. };
  8520. Mesh.CreatePlane = function (name, size, scene, updatable) {
  8521. var plane = new BABYLON.Mesh(name, scene);
  8522. var vertexData = BABYLON.VertexData.CreatePlane(size);
  8523. vertexData.applyToMesh(plane, updatable);
  8524. return plane;
  8525. };
  8526. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  8527. var ground = new BABYLON.GroundMesh(name, scene);
  8528. ground._setReady(false);
  8529. ground._subdivisions = subdivisions;
  8530. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  8531. vertexData.applyToMesh(ground, updatable);
  8532. ground._setReady(true);
  8533. return ground;
  8534. };
  8535. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  8536. var tiledGround = new BABYLON.Mesh(name, scene);
  8537. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  8538. vertexData.applyToMesh(tiledGround, updatable);
  8539. return tiledGround;
  8540. };
  8541. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  8542. var ground = new BABYLON.GroundMesh(name, scene);
  8543. ground._subdivisions = subdivisions;
  8544. ground._setReady(false);
  8545. var onload = function (img) {
  8546. var canvas = document.createElement("canvas");
  8547. var context = canvas.getContext("2d");
  8548. var heightMapWidth = img.width;
  8549. var heightMapHeight = img.height;
  8550. canvas.width = heightMapWidth;
  8551. canvas.height = heightMapHeight;
  8552. context.drawImage(img, 0, 0);
  8553. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8554. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  8555. vertexData.applyToMesh(ground, updatable);
  8556. ground._setReady(true);
  8557. };
  8558. BABYLON.Tools.LoadImage(url, onload, function () {
  8559. }, scene.database);
  8560. return ground;
  8561. };
  8562. Mesh.MinMax = function (meshes) {
  8563. var minVector = null;
  8564. var maxVector = null;
  8565. for (var i in meshes) {
  8566. var mesh = meshes[i];
  8567. var boundingBox = mesh.getBoundingInfo().boundingBox;
  8568. if (!minVector) {
  8569. minVector = boundingBox.minimumWorld;
  8570. maxVector = boundingBox.maximumWorld;
  8571. continue;
  8572. }
  8573. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  8574. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  8575. }
  8576. return {
  8577. min: minVector,
  8578. max: maxVector
  8579. };
  8580. };
  8581. Mesh.Center = function (meshesOrMinMaxVector) {
  8582. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8583. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  8584. };
  8585. return Mesh;
  8586. })(BABYLON.AbstractMesh);
  8587. BABYLON.Mesh = Mesh;
  8588. })(BABYLON || (BABYLON = {}));
  8589. var __extends = this.__extends || function (d, b) {
  8590. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8591. function __() { this.constructor = d; }
  8592. __.prototype = b.prototype;
  8593. d.prototype = new __();
  8594. };
  8595. var BABYLON;
  8596. (function (BABYLON) {
  8597. var GroundMesh = (function (_super) {
  8598. __extends(GroundMesh, _super);
  8599. function GroundMesh(name, scene) {
  8600. _super.call(this, name, scene);
  8601. this.generateOctree = false;
  8602. this._worldInverse = new BABYLON.Matrix();
  8603. }
  8604. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  8605. get: function () {
  8606. return this._subdivisions;
  8607. },
  8608. enumerable: true,
  8609. configurable: true
  8610. });
  8611. GroundMesh.prototype.optimize = function (chunksCount) {
  8612. this.subdivide(this._subdivisions);
  8613. this.createOrUpdateSubmeshesOctree(32);
  8614. };
  8615. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  8616. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  8617. this.getWorldMatrix().invertToRef(this._worldInverse);
  8618. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  8619. var pickInfo = this.intersects(ray);
  8620. if (pickInfo.hit) {
  8621. return pickInfo.pickedPoint.y;
  8622. }
  8623. return 0;
  8624. };
  8625. return GroundMesh;
  8626. })(BABYLON.Mesh);
  8627. BABYLON.GroundMesh = GroundMesh;
  8628. })(BABYLON || (BABYLON = {}));
  8629. var __extends = this.__extends || function (d, b) {
  8630. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8631. function __() { this.constructor = d; }
  8632. __.prototype = b.prototype;
  8633. d.prototype = new __();
  8634. };
  8635. var BABYLON;
  8636. (function (BABYLON) {
  8637. var InstancedMesh = (function (_super) {
  8638. __extends(InstancedMesh, _super);
  8639. function InstancedMesh(name, source) {
  8640. _super.call(this, name, source.getScene());
  8641. source.instances.push(this);
  8642. this._sourceMesh = source;
  8643. this.position.copyFrom(source.position);
  8644. this.rotation.copyFrom(source.rotation);
  8645. this.scaling.copyFrom(source.scaling);
  8646. if (source.rotationQuaternion) {
  8647. this.rotationQuaternion = source.rotationQuaternion.clone();
  8648. }
  8649. this.infiniteDistance = source.infiniteDistance;
  8650. this.setPivotMatrix(source.getPivotMatrix());
  8651. this.refreshBoundingInfo();
  8652. this._syncSubMeshes();
  8653. }
  8654. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  8655. get: function () {
  8656. return this._sourceMesh.receiveShadows;
  8657. },
  8658. enumerable: true,
  8659. configurable: true
  8660. });
  8661. Object.defineProperty(InstancedMesh.prototype, "material", {
  8662. get: function () {
  8663. return this._sourceMesh.material;
  8664. },
  8665. enumerable: true,
  8666. configurable: true
  8667. });
  8668. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  8669. get: function () {
  8670. return this._sourceMesh.visibility;
  8671. },
  8672. enumerable: true,
  8673. configurable: true
  8674. });
  8675. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  8676. get: function () {
  8677. return this._sourceMesh.skeleton;
  8678. },
  8679. enumerable: true,
  8680. configurable: true
  8681. });
  8682. InstancedMesh.prototype.getTotalVertices = function () {
  8683. return this._sourceMesh.getTotalVertices();
  8684. };
  8685. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  8686. get: function () {
  8687. return this._sourceMesh;
  8688. },
  8689. enumerable: true,
  8690. configurable: true
  8691. });
  8692. InstancedMesh.prototype.getVerticesData = function (kind) {
  8693. return this._sourceMesh.getVerticesData(kind);
  8694. };
  8695. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  8696. return this._sourceMesh.isVerticesDataPresent(kind);
  8697. };
  8698. InstancedMesh.prototype.getIndices = function () {
  8699. return this._sourceMesh.getIndices();
  8700. };
  8701. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  8702. get: function () {
  8703. return this._sourceMesh._positions;
  8704. },
  8705. enumerable: true,
  8706. configurable: true
  8707. });
  8708. InstancedMesh.prototype.refreshBoundingInfo = function () {
  8709. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8710. if (data) {
  8711. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  8712. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8713. }
  8714. this._updateBoundingInfo();
  8715. };
  8716. InstancedMesh.prototype._preActivate = function () {
  8717. this.sourceMesh._preActivate();
  8718. };
  8719. InstancedMesh.prototype._activate = function (renderId) {
  8720. this.sourceMesh._registerInstanceForRenderId(this, renderId);
  8721. };
  8722. InstancedMesh.prototype._syncSubMeshes = function () {
  8723. this.releaseSubMeshes();
  8724. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  8725. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  8726. }
  8727. };
  8728. InstancedMesh.prototype._generatePointsArray = function () {
  8729. return this._sourceMesh._generatePointsArray();
  8730. };
  8731. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8732. var result = this._sourceMesh.createInstance(name);
  8733. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  8734. this.refreshBoundingInfo();
  8735. if (newParent) {
  8736. result.parent = newParent;
  8737. }
  8738. if (!doNotCloneChildren) {
  8739. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8740. var mesh = this.getScene().meshes[index];
  8741. if (mesh.parent == this) {
  8742. mesh.clone(mesh.name, result);
  8743. }
  8744. }
  8745. }
  8746. result.computeWorldMatrix(true);
  8747. return result;
  8748. };
  8749. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  8750. var index = this._sourceMesh.instances.indexOf(this);
  8751. this._sourceMesh.instances.splice(index, 1);
  8752. _super.prototype.dispose.call(this, doNotRecurse);
  8753. };
  8754. return InstancedMesh;
  8755. })(BABYLON.AbstractMesh);
  8756. BABYLON.InstancedMesh = InstancedMesh;
  8757. })(BABYLON || (BABYLON = {}));
  8758. var BABYLON;
  8759. (function (BABYLON) {
  8760. var SubMesh = (function () {
  8761. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  8762. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  8763. this.materialIndex = materialIndex;
  8764. this.verticesStart = verticesStart;
  8765. this.verticesCount = verticesCount;
  8766. this.indexStart = indexStart;
  8767. this.indexCount = indexCount;
  8768. this._renderId = 0;
  8769. this._mesh = mesh;
  8770. this._renderingMesh = renderingMesh || mesh;
  8771. mesh.subMeshes.push(this);
  8772. this._id = mesh.subMeshes.length - 1;
  8773. if (createBoundingBox) {
  8774. this.refreshBoundingInfo();
  8775. }
  8776. }
  8777. SubMesh.prototype.getBoundingInfo = function () {
  8778. return this._boundingInfo;
  8779. };
  8780. SubMesh.prototype.getMesh = function () {
  8781. return this._mesh;
  8782. };
  8783. SubMesh.prototype.getRenderingMesh = function () {
  8784. return this._renderingMesh;
  8785. };
  8786. SubMesh.prototype.getMaterial = function () {
  8787. var rootMaterial = this._renderingMesh.material;
  8788. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  8789. var multiMaterial = rootMaterial;
  8790. return multiMaterial.getSubMaterial(this.materialIndex);
  8791. }
  8792. if (!rootMaterial) {
  8793. return this._mesh.getScene().defaultMaterial;
  8794. }
  8795. return rootMaterial;
  8796. };
  8797. SubMesh.prototype.refreshBoundingInfo = function () {
  8798. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8799. if (!data) {
  8800. this._boundingInfo = this._mesh._boundingInfo;
  8801. return;
  8802. }
  8803. var indices = this._renderingMesh.getIndices();
  8804. var extend;
  8805. if (this.indexStart === 0 && this.indexCount === indices.length) {
  8806. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  8807. } else {
  8808. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  8809. }
  8810. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8811. };
  8812. SubMesh.prototype._checkCollision = function (collider) {
  8813. return this._boundingInfo._checkCollision(collider);
  8814. };
  8815. SubMesh.prototype.updateBoundingInfo = function (world) {
  8816. if (!this._boundingInfo) {
  8817. this.refreshBoundingInfo();
  8818. }
  8819. this._boundingInfo._update(world);
  8820. };
  8821. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  8822. return this._boundingInfo.isInFrustum(frustumPlanes);
  8823. };
  8824. SubMesh.prototype.render = function () {
  8825. this._renderingMesh.render(this);
  8826. };
  8827. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  8828. if (!this._linesIndexBuffer) {
  8829. var linesIndices = [];
  8830. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8831. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  8832. }
  8833. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  8834. this.linesIndexCount = linesIndices.length;
  8835. }
  8836. return this._linesIndexBuffer;
  8837. };
  8838. SubMesh.prototype.canIntersects = function (ray) {
  8839. return ray.intersectsBox(this._boundingInfo.boundingBox);
  8840. };
  8841. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  8842. var intersectInfo = null;
  8843. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8844. var p0 = positions[indices[index]];
  8845. var p1 = positions[indices[index + 1]];
  8846. var p2 = positions[indices[index + 2]];
  8847. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  8848. if (currentIntersectInfo) {
  8849. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8850. intersectInfo = currentIntersectInfo;
  8851. intersectInfo.faceId = index / 3;
  8852. if (fastCheck) {
  8853. break;
  8854. }
  8855. }
  8856. }
  8857. }
  8858. return intersectInfo;
  8859. };
  8860. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  8861. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  8862. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  8863. return result;
  8864. };
  8865. SubMesh.prototype.dispose = function () {
  8866. if (this._linesIndexBuffer) {
  8867. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  8868. this._linesIndexBuffer = null;
  8869. }
  8870. var index = this._mesh.subMeshes.indexOf(this);
  8871. this._mesh.subMeshes.splice(index, 1);
  8872. };
  8873. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  8874. var minVertexIndex = Number.MAX_VALUE;
  8875. var maxVertexIndex = -Number.MAX_VALUE;
  8876. renderingMesh = renderingMesh || mesh;
  8877. var indices = renderingMesh.getIndices();
  8878. for (var index = startIndex; index < startIndex + indexCount; index++) {
  8879. var vertexIndex = indices[index];
  8880. if (vertexIndex < minVertexIndex)
  8881. minVertexIndex = vertexIndex;
  8882. if (vertexIndex > maxVertexIndex)
  8883. maxVertexIndex = vertexIndex;
  8884. }
  8885. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  8886. };
  8887. return SubMesh;
  8888. })();
  8889. BABYLON.SubMesh = SubMesh;
  8890. })(BABYLON || (BABYLON = {}));
  8891. var BABYLON;
  8892. (function (BABYLON) {
  8893. var BaseTexture = (function () {
  8894. function BaseTexture(scene) {
  8895. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  8896. this.hasAlpha = false;
  8897. this.getAlphaFromRGB = false;
  8898. this.level = 1;
  8899. this.isCube = false;
  8900. this.isRenderTarget = false;
  8901. this.animations = new Array();
  8902. this.coordinatesIndex = 0;
  8903. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  8904. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  8905. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  8906. this.anisotropicFilteringLevel = 4;
  8907. this._scene = scene;
  8908. this._scene.textures.push(this);
  8909. }
  8910. BaseTexture.prototype.getScene = function () {
  8911. return this._scene;
  8912. };
  8913. BaseTexture.prototype.getTextureMatrix = function () {
  8914. return null;
  8915. };
  8916. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  8917. return null;
  8918. };
  8919. BaseTexture.prototype.getInternalTexture = function () {
  8920. return this._texture;
  8921. };
  8922. BaseTexture.prototype.isReady = function () {
  8923. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8924. return true;
  8925. }
  8926. if (this._texture) {
  8927. return this._texture.isReady;
  8928. }
  8929. return false;
  8930. };
  8931. BaseTexture.prototype.getSize = function () {
  8932. if (this._texture._width) {
  8933. return { width: this._texture._width, height: this._texture._height };
  8934. }
  8935. if (this._texture._size) {
  8936. return { width: this._texture._size, height: this._texture._size };
  8937. }
  8938. return { width: 0, height: 0 };
  8939. };
  8940. BaseTexture.prototype.getBaseSize = function () {
  8941. if (!this.isReady())
  8942. return { width: 0, height: 0 };
  8943. if (this._texture._size) {
  8944. return { width: this._texture._size, height: this._texture._size };
  8945. }
  8946. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  8947. };
  8948. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  8949. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8950. for (var index = 0; index < texturesCache.length; index++) {
  8951. var texturesCacheEntry = texturesCache[index];
  8952. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  8953. texturesCacheEntry.references++;
  8954. return texturesCacheEntry;
  8955. }
  8956. }
  8957. return null;
  8958. };
  8959. BaseTexture.prototype.delayLoad = function () {
  8960. };
  8961. BaseTexture.prototype.releaseInternalTexture = function () {
  8962. if (!this._texture) {
  8963. return;
  8964. }
  8965. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8966. this._texture.references--;
  8967. if (this._texture.references == 0) {
  8968. var index = texturesCache.indexOf(this._texture);
  8969. texturesCache.splice(index, 1);
  8970. this._scene.getEngine()._releaseTexture(this._texture);
  8971. delete this._texture;
  8972. }
  8973. };
  8974. BaseTexture.prototype.clone = function () {
  8975. return null;
  8976. };
  8977. BaseTexture.prototype.dispose = function () {
  8978. var index = this._scene.textures.indexOf(this);
  8979. if (index >= 0) {
  8980. this._scene.textures.splice(index, 1);
  8981. }
  8982. if (this._texture === undefined) {
  8983. return;
  8984. }
  8985. this.releaseInternalTexture();
  8986. if (this.onDispose) {
  8987. this.onDispose();
  8988. }
  8989. };
  8990. return BaseTexture;
  8991. })();
  8992. BABYLON.BaseTexture = BaseTexture;
  8993. })(BABYLON || (BABYLON = {}));
  8994. var BABYLON;
  8995. (function (BABYLON) {
  8996. var RenderingGroup = (function () {
  8997. function RenderingGroup(index, scene) {
  8998. this.index = index;
  8999. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  9000. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  9001. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  9002. this._scene = scene;
  9003. }
  9004. RenderingGroup.prototype.render = function (customRenderFunction, beforeTransparents) {
  9005. if (customRenderFunction) {
  9006. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
  9007. return true;
  9008. }
  9009. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  9010. return false;
  9011. }
  9012. var engine = this._scene.getEngine();
  9013. var subIndex;
  9014. var submesh;
  9015. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  9016. submesh = this._opaqueSubMeshes.data[subIndex];
  9017. this._activeVertices += submesh.verticesCount;
  9018. submesh.render();
  9019. }
  9020. engine.setAlphaTesting(true);
  9021. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  9022. submesh = this._alphaTestSubMeshes.data[subIndex];
  9023. this._activeVertices += submesh.verticesCount;
  9024. submesh.render();
  9025. }
  9026. engine.setAlphaTesting(false);
  9027. if (beforeTransparents) {
  9028. beforeTransparents();
  9029. }
  9030. if (this._transparentSubMeshes.length) {
  9031. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  9032. submesh = this._transparentSubMeshes.data[subIndex];
  9033. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  9034. }
  9035. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  9036. sortedArray.sort(function (a, b) {
  9037. if (a._distanceToCamera < b._distanceToCamera) {
  9038. return 1;
  9039. }
  9040. if (a._distanceToCamera > b._distanceToCamera) {
  9041. return -1;
  9042. }
  9043. return 0;
  9044. });
  9045. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9046. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  9047. submesh = sortedArray[subIndex];
  9048. this._activeVertices += submesh.verticesCount;
  9049. submesh.render();
  9050. }
  9051. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  9052. }
  9053. return true;
  9054. };
  9055. RenderingGroup.prototype.prepare = function () {
  9056. this._opaqueSubMeshes.reset();
  9057. this._transparentSubMeshes.reset();
  9058. this._alphaTestSubMeshes.reset();
  9059. };
  9060. RenderingGroup.prototype.dispatch = function (subMesh) {
  9061. var material = subMesh.getMaterial();
  9062. var mesh = subMesh.getMesh();
  9063. if (material.needAlphaBlending() || mesh.visibility < 1.0) {
  9064. if (material.alpha > 0 || mesh.visibility < 1.0) {
  9065. this._transparentSubMeshes.push(subMesh);
  9066. }
  9067. } else if (material.needAlphaTesting()) {
  9068. this._alphaTestSubMeshes.push(subMesh);
  9069. } else {
  9070. this._opaqueSubMeshes.push(subMesh);
  9071. }
  9072. };
  9073. return RenderingGroup;
  9074. })();
  9075. BABYLON.RenderingGroup = RenderingGroup;
  9076. })(BABYLON || (BABYLON = {}));
  9077. var BABYLON;
  9078. (function (BABYLON) {
  9079. var RenderingManager = (function () {
  9080. function RenderingManager(scene) {
  9081. this._renderingGroups = new Array();
  9082. this._scene = scene;
  9083. }
  9084. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  9085. if (this._scene._activeParticleSystems.length === 0) {
  9086. return;
  9087. }
  9088. var beforeParticlesDate = new Date().getTime();
  9089. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  9090. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  9091. if (particleSystem.renderingGroupId !== index) {
  9092. continue;
  9093. }
  9094. this._clearDepthBuffer();
  9095. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  9096. this._scene._activeParticles += particleSystem.render();
  9097. }
  9098. }
  9099. this._scene._particlesDuration += new Date().getTime() - beforeParticlesDate;
  9100. };
  9101. RenderingManager.prototype._renderSprites = function (index) {
  9102. if (this._scene.spriteManagers.length === 0) {
  9103. return;
  9104. }
  9105. var beforeSpritessDate = new Date().getTime();
  9106. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  9107. var spriteManager = this._scene.spriteManagers[id];
  9108. if (spriteManager.renderingGroupId === index) {
  9109. this._clearDepthBuffer();
  9110. spriteManager.render();
  9111. }
  9112. }
  9113. this._scene._spritesDuration += new Date().getTime() - beforeSpritessDate;
  9114. };
  9115. RenderingManager.prototype._clearDepthBuffer = function () {
  9116. if (this._depthBufferAlreadyCleaned) {
  9117. return;
  9118. }
  9119. this._scene.getEngine().clear(0, false, true);
  9120. this._depthBufferAlreadyCleaned = true;
  9121. };
  9122. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  9123. var _this = this;
  9124. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  9125. this._depthBufferAlreadyCleaned = false;
  9126. var renderingGroup = this._renderingGroups[index];
  9127. if (renderingGroup) {
  9128. this._clearDepthBuffer();
  9129. if (!renderingGroup.render(customRenderFunction, function () {
  9130. if (renderSprites) {
  9131. _this._renderSprites(index);
  9132. }
  9133. })) {
  9134. this._renderingGroups.splice(index, 1);
  9135. }
  9136. } else if (renderSprites) {
  9137. this._renderSprites(index);
  9138. }
  9139. if (renderParticles) {
  9140. this._renderParticles(index, activeMeshes);
  9141. }
  9142. }
  9143. };
  9144. RenderingManager.prototype.reset = function () {
  9145. for (var index in this._renderingGroups) {
  9146. var renderingGroup = this._renderingGroups[index];
  9147. renderingGroup.prepare();
  9148. }
  9149. };
  9150. RenderingManager.prototype.dispatch = function (subMesh) {
  9151. var mesh = subMesh.getMesh();
  9152. var renderingGroupId = mesh.renderingGroupId || 0;
  9153. if (!this._renderingGroups[renderingGroupId]) {
  9154. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  9155. }
  9156. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  9157. };
  9158. RenderingManager.MAX_RENDERINGGROUPS = 4;
  9159. return RenderingManager;
  9160. })();
  9161. BABYLON.RenderingManager = RenderingManager;
  9162. })(BABYLON || (BABYLON = {}));
  9163. var __extends = this.__extends || function (d, b) {
  9164. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9165. function __() { this.constructor = d; }
  9166. __.prototype = b.prototype;
  9167. d.prototype = new __();
  9168. };
  9169. var BABYLON;
  9170. (function (BABYLON) {
  9171. var Texture = (function (_super) {
  9172. __extends(Texture, _super);
  9173. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  9174. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  9175. if (typeof onLoad === "undefined") { onLoad = null; }
  9176. if (typeof onError === "undefined") { onError = null; }
  9177. if (typeof buffer === "undefined") { buffer = null; }
  9178. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  9179. _super.call(this, scene);
  9180. this.uOffset = 0;
  9181. this.vOffset = 0;
  9182. this.uScale = 1.0;
  9183. this.vScale = 1.0;
  9184. this.uAng = 0;
  9185. this.vAng = 0;
  9186. this.wAng = 0;
  9187. this.name = url;
  9188. this.url = url;
  9189. this._noMipmap = noMipmap;
  9190. this._invertY = invertY;
  9191. this._samplingMode = samplingMode;
  9192. this._buffer = buffer;
  9193. this._deleteBuffer = deleteBuffer;
  9194. if (!url) {
  9195. return;
  9196. }
  9197. this._texture = this._getFromCache(url, noMipmap);
  9198. if (!this._texture) {
  9199. if (!scene.useDelayedTextureLoading) {
  9200. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  9201. if (deleteBuffer) {
  9202. delete this._buffer;
  9203. }
  9204. } else {
  9205. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9206. }
  9207. }
  9208. }
  9209. Texture.prototype.delayLoad = function () {
  9210. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9211. return;
  9212. }
  9213. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9214. this._texture = this._getFromCache(this.url, this._noMipmap);
  9215. if (!this._texture) {
  9216. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  9217. if (this._deleteBuffer) {
  9218. delete this._buffer;
  9219. }
  9220. }
  9221. };
  9222. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  9223. x -= this.uOffset + 0.5;
  9224. y -= this.vOffset + 0.5;
  9225. z -= 0.5;
  9226. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  9227. t.x *= this.uScale;
  9228. t.y *= this.vScale;
  9229. t.x += 0.5;
  9230. t.y += 0.5;
  9231. t.z += 0.5;
  9232. };
  9233. Texture.prototype.getTextureMatrix = function () {
  9234. 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) {
  9235. return this._cachedTextureMatrix;
  9236. }
  9237. this._cachedUOffset = this.uOffset;
  9238. this._cachedVOffset = this.vOffset;
  9239. this._cachedUScale = this.uScale;
  9240. this._cachedVScale = this.vScale;
  9241. this._cachedUAng = this.uAng;
  9242. this._cachedVAng = this.vAng;
  9243. this._cachedWAng = this.wAng;
  9244. if (!this._cachedTextureMatrix) {
  9245. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9246. this._rowGenerationMatrix = new BABYLON.Matrix();
  9247. this._t0 = BABYLON.Vector3.Zero();
  9248. this._t1 = BABYLON.Vector3.Zero();
  9249. this._t2 = BABYLON.Vector3.Zero();
  9250. }
  9251. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  9252. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  9253. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  9254. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  9255. this._t1.subtractInPlace(this._t0);
  9256. this._t2.subtractInPlace(this._t0);
  9257. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9258. this._cachedTextureMatrix.m[0] = this._t1.x;
  9259. this._cachedTextureMatrix.m[1] = this._t1.y;
  9260. this._cachedTextureMatrix.m[2] = this._t1.z;
  9261. this._cachedTextureMatrix.m[4] = this._t2.x;
  9262. this._cachedTextureMatrix.m[5] = this._t2.y;
  9263. this._cachedTextureMatrix.m[6] = this._t2.z;
  9264. this._cachedTextureMatrix.m[8] = this._t0.x;
  9265. this._cachedTextureMatrix.m[9] = this._t0.y;
  9266. this._cachedTextureMatrix.m[10] = this._t0.z;
  9267. return this._cachedTextureMatrix;
  9268. };
  9269. Texture.prototype.getReflectionTextureMatrix = function () {
  9270. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  9271. return this._cachedTextureMatrix;
  9272. }
  9273. if (!this._cachedTextureMatrix) {
  9274. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9275. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  9276. }
  9277. switch (this.coordinatesMode) {
  9278. case BABYLON.Texture.SPHERICAL_MODE:
  9279. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9280. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  9281. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  9282. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  9283. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  9284. break;
  9285. case BABYLON.Texture.PLANAR_MODE:
  9286. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9287. this._cachedTextureMatrix[0] = this.uScale;
  9288. this._cachedTextureMatrix[5] = this.vScale;
  9289. this._cachedTextureMatrix[12] = this.uOffset;
  9290. this._cachedTextureMatrix[13] = this.vOffset;
  9291. break;
  9292. case BABYLON.Texture.PROJECTION_MODE:
  9293. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  9294. this._projectionModeMatrix.m[0] = 0.5;
  9295. this._projectionModeMatrix.m[5] = -0.5;
  9296. this._projectionModeMatrix.m[10] = 0.0;
  9297. this._projectionModeMatrix.m[12] = 0.5;
  9298. this._projectionModeMatrix.m[13] = 0.5;
  9299. this._projectionModeMatrix.m[14] = 1.0;
  9300. this._projectionModeMatrix.m[15] = 1.0;
  9301. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  9302. break;
  9303. default:
  9304. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9305. break;
  9306. }
  9307. return this._cachedTextureMatrix;
  9308. };
  9309. Texture.prototype.clone = function () {
  9310. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  9311. newTexture.hasAlpha = this.hasAlpha;
  9312. newTexture.level = this.level;
  9313. newTexture.wrapU = this.wrapU;
  9314. newTexture.wrapV = this.wrapV;
  9315. newTexture.coordinatesIndex = this.coordinatesIndex;
  9316. newTexture.coordinatesMode = this.coordinatesMode;
  9317. newTexture.uOffset = this.uOffset;
  9318. newTexture.vOffset = this.vOffset;
  9319. newTexture.uScale = this.uScale;
  9320. newTexture.vScale = this.vScale;
  9321. newTexture.uAng = this.uAng;
  9322. newTexture.vAng = this.vAng;
  9323. newTexture.wAng = this.wAng;
  9324. return newTexture;
  9325. };
  9326. Texture.NEAREST_SAMPLINGMODE = 1;
  9327. Texture.BILINEAR_SAMPLINGMODE = 2;
  9328. Texture.TRILINEAR_SAMPLINGMODE = 3;
  9329. Texture.EXPLICIT_MODE = 0;
  9330. Texture.SPHERICAL_MODE = 1;
  9331. Texture.PLANAR_MODE = 2;
  9332. Texture.CUBIC_MODE = 3;
  9333. Texture.PROJECTION_MODE = 4;
  9334. Texture.SKYBOX_MODE = 5;
  9335. Texture.CLAMP_ADDRESSMODE = 0;
  9336. Texture.WRAP_ADDRESSMODE = 1;
  9337. Texture.MIRROR_ADDRESSMODE = 2;
  9338. return Texture;
  9339. })(BABYLON.BaseTexture);
  9340. BABYLON.Texture = Texture;
  9341. })(BABYLON || (BABYLON = {}));
  9342. var __extends = this.__extends || function (d, b) {
  9343. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9344. function __() { this.constructor = d; }
  9345. __.prototype = b.prototype;
  9346. d.prototype = new __();
  9347. };
  9348. var BABYLON;
  9349. (function (BABYLON) {
  9350. var CubeTexture = (function (_super) {
  9351. __extends(CubeTexture, _super);
  9352. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  9353. _super.call(this, scene);
  9354. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  9355. this.name = rootUrl;
  9356. this.url = rootUrl;
  9357. this._noMipmap = noMipmap;
  9358. this.hasAlpha = false;
  9359. this._texture = this._getFromCache(rootUrl, noMipmap);
  9360. if (!extensions) {
  9361. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  9362. }
  9363. this._extensions = extensions;
  9364. if (!this._texture) {
  9365. if (!scene.useDelayedTextureLoading) {
  9366. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  9367. } else {
  9368. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9369. }
  9370. }
  9371. this.isCube = true;
  9372. this._textureMatrix = BABYLON.Matrix.Identity();
  9373. }
  9374. CubeTexture.prototype.clone = function () {
  9375. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  9376. newTexture.level = this.level;
  9377. newTexture.wrapU = this.wrapU;
  9378. newTexture.wrapV = this.wrapV;
  9379. newTexture.coordinatesIndex = this.coordinatesIndex;
  9380. newTexture.coordinatesMode = this.coordinatesMode;
  9381. return newTexture;
  9382. };
  9383. CubeTexture.prototype.delayLoad = function () {
  9384. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9385. return;
  9386. }
  9387. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9388. this._texture = this._getFromCache(this.url, this._noMipmap);
  9389. if (!this._texture) {
  9390. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  9391. }
  9392. };
  9393. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  9394. return this._textureMatrix;
  9395. };
  9396. return CubeTexture;
  9397. })(BABYLON.BaseTexture);
  9398. BABYLON.CubeTexture = CubeTexture;
  9399. })(BABYLON || (BABYLON = {}));
  9400. var __extends = this.__extends || function (d, b) {
  9401. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9402. function __() { this.constructor = d; }
  9403. __.prototype = b.prototype;
  9404. d.prototype = new __();
  9405. };
  9406. var BABYLON;
  9407. (function (BABYLON) {
  9408. var RenderTargetTexture = (function (_super) {
  9409. __extends(RenderTargetTexture, _super);
  9410. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  9411. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  9412. _super.call(this, null, scene, !generateMipMaps);
  9413. this.renderList = new Array();
  9414. this.renderParticles = true;
  9415. this.renderSprites = false;
  9416. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  9417. this._currentRefreshId = -1;
  9418. this._refreshRate = 1;
  9419. this.name = name;
  9420. this.isRenderTarget = true;
  9421. this._size = size;
  9422. this._generateMipMaps = generateMipMaps;
  9423. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  9424. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  9425. this._renderingManager = new BABYLON.RenderingManager(scene);
  9426. }
  9427. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  9428. this._currentRefreshId = -1;
  9429. };
  9430. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  9431. get: function () {
  9432. return this._refreshRate;
  9433. },
  9434. set: function (value) {
  9435. this._refreshRate = value;
  9436. this.resetRefreshCounter();
  9437. },
  9438. enumerable: true,
  9439. configurable: true
  9440. });
  9441. RenderTargetTexture.prototype._shouldRender = function () {
  9442. if (this._currentRefreshId === -1) {
  9443. this._currentRefreshId = 1;
  9444. return true;
  9445. }
  9446. if (this.refreshRate == this._currentRefreshId) {
  9447. this._currentRefreshId = 1;
  9448. return true;
  9449. }
  9450. this._currentRefreshId++;
  9451. return false;
  9452. };
  9453. RenderTargetTexture.prototype.getRenderSize = function () {
  9454. return this._size;
  9455. };
  9456. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  9457. this.releaseInternalTexture();
  9458. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  9459. };
  9460. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  9461. var scene = this.getScene();
  9462. var engine = scene.getEngine();
  9463. if (this._waitingRenderList) {
  9464. this.renderList = [];
  9465. for (var index = 0; index < this._waitingRenderList.length; index++) {
  9466. var id = this._waitingRenderList[index];
  9467. this.renderList.push(scene.getMeshByID(id));
  9468. }
  9469. delete this._waitingRenderList;
  9470. }
  9471. if (!this.renderList) {
  9472. return;
  9473. }
  9474. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  9475. engine.bindFramebuffer(this._texture);
  9476. }
  9477. engine.clear(scene.clearColor, true, true);
  9478. this._renderingManager.reset();
  9479. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  9480. var mesh = this.renderList[meshIndex];
  9481. if (mesh) {
  9482. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  9483. this.resetRefreshCounter();
  9484. continue;
  9485. }
  9486. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  9487. mesh._activate(scene.getRenderId());
  9488. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  9489. var subMesh = mesh.subMeshes[subIndex];
  9490. scene._activeVertices += subMesh.verticesCount;
  9491. this._renderingManager.dispatch(subMesh);
  9492. }
  9493. }
  9494. }
  9495. }
  9496. if (!this._doNotChangeAspectRatio) {
  9497. scene.updateTransformMatrix(true);
  9498. }
  9499. if (this.onBeforeRender) {
  9500. this.onBeforeRender();
  9501. }
  9502. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  9503. if (useCameraPostProcess) {
  9504. scene.postProcessManager._finalizeFrame(false, this._texture);
  9505. }
  9506. if (this.onAfterRender) {
  9507. this.onAfterRender();
  9508. }
  9509. engine.unBindFramebuffer(this._texture);
  9510. if (!this._doNotChangeAspectRatio) {
  9511. scene.updateTransformMatrix(true);
  9512. }
  9513. };
  9514. RenderTargetTexture.prototype.clone = function () {
  9515. var textureSize = this.getSize();
  9516. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9517. newTexture.hasAlpha = this.hasAlpha;
  9518. newTexture.level = this.level;
  9519. newTexture.coordinatesMode = this.coordinatesMode;
  9520. newTexture.renderList = this.renderList.slice(0);
  9521. return newTexture;
  9522. };
  9523. return RenderTargetTexture;
  9524. })(BABYLON.Texture);
  9525. BABYLON.RenderTargetTexture = RenderTargetTexture;
  9526. })(BABYLON || (BABYLON = {}));
  9527. var __extends = this.__extends || function (d, b) {
  9528. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9529. function __() { this.constructor = d; }
  9530. __.prototype = b.prototype;
  9531. d.prototype = new __();
  9532. };
  9533. var BABYLON;
  9534. (function (BABYLON) {
  9535. var MirrorTexture = (function (_super) {
  9536. __extends(MirrorTexture, _super);
  9537. function MirrorTexture(name, size, scene, generateMipMaps) {
  9538. var _this = this;
  9539. _super.call(this, name, size, scene, generateMipMaps, true);
  9540. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  9541. this._transformMatrix = BABYLON.Matrix.Zero();
  9542. this._mirrorMatrix = BABYLON.Matrix.Zero();
  9543. this.onBeforeRender = function () {
  9544. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  9545. _this._savedViewMatrix = scene.getViewMatrix();
  9546. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  9547. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  9548. scene.clipPlane = _this.mirrorPlane;
  9549. scene.getEngine().cullBackFaces = false;
  9550. };
  9551. this.onAfterRender = function () {
  9552. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  9553. scene.getEngine().cullBackFaces = true;
  9554. delete scene.clipPlane;
  9555. };
  9556. }
  9557. MirrorTexture.prototype.clone = function () {
  9558. var textureSize = this.getSize();
  9559. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9560. newTexture.hasAlpha = this.hasAlpha;
  9561. newTexture.level = this.level;
  9562. newTexture.mirrorPlane = this.mirrorPlane.clone();
  9563. newTexture.renderList = this.renderList.slice(0);
  9564. return newTexture;
  9565. };
  9566. return MirrorTexture;
  9567. })(BABYLON.RenderTargetTexture);
  9568. BABYLON.MirrorTexture = MirrorTexture;
  9569. })(BABYLON || (BABYLON = {}));
  9570. var __extends = this.__extends || function (d, b) {
  9571. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9572. function __() { this.constructor = d; }
  9573. __.prototype = b.prototype;
  9574. d.prototype = new __();
  9575. };
  9576. var BABYLON;
  9577. (function (BABYLON) {
  9578. var DynamicTexture = (function (_super) {
  9579. __extends(DynamicTexture, _super);
  9580. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  9581. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9582. _super.call(this, null, scene, !generateMipMaps);
  9583. this.name = name;
  9584. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9585. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9586. this._generateMipMaps = generateMipMaps;
  9587. if (options.getContext) {
  9588. this._canvas = options;
  9589. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  9590. } else {
  9591. this._canvas = document.createElement("canvas");
  9592. if (options.width) {
  9593. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  9594. } else {
  9595. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  9596. }
  9597. }
  9598. var textureSize = this.getSize();
  9599. this._canvas.width = textureSize.width;
  9600. this._canvas.height = textureSize.height;
  9601. this._context = this._canvas.getContext("2d");
  9602. }
  9603. DynamicTexture.prototype.getContext = function () {
  9604. return this._context;
  9605. };
  9606. DynamicTexture.prototype.update = function (invertY) {
  9607. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  9608. };
  9609. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  9610. var size = this.getSize();
  9611. if (clearColor) {
  9612. this._context.fillStyle = clearColor;
  9613. this._context.fillRect(0, 0, size.width, size.height);
  9614. }
  9615. this._context.font = font;
  9616. if (x === null) {
  9617. var textSize = this._context.measureText(text);
  9618. x = (size.width - textSize.width) / 2;
  9619. }
  9620. this._context.fillStyle = color;
  9621. this._context.fillText(text, x, y);
  9622. this.update(invertY);
  9623. };
  9624. DynamicTexture.prototype.clone = function () {
  9625. var textureSize = this.getSize();
  9626. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9627. newTexture.hasAlpha = this.hasAlpha;
  9628. newTexture.level = this.level;
  9629. newTexture.wrapU = this.wrapU;
  9630. newTexture.wrapV = this.wrapV;
  9631. return newTexture;
  9632. };
  9633. return DynamicTexture;
  9634. })(BABYLON.Texture);
  9635. BABYLON.DynamicTexture = DynamicTexture;
  9636. })(BABYLON || (BABYLON = {}));
  9637. var __extends = this.__extends || function (d, b) {
  9638. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9639. function __() { this.constructor = d; }
  9640. __.prototype = b.prototype;
  9641. d.prototype = new __();
  9642. };
  9643. var BABYLON;
  9644. (function (BABYLON) {
  9645. var VideoTexture = (function (_super) {
  9646. __extends(VideoTexture, _super);
  9647. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  9648. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9649. var _this = this;
  9650. _super.call(this, null, scene, !generateMipMaps, invertY);
  9651. this._autoLaunch = true;
  9652. this.name = name;
  9653. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  9654. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  9655. var requiredWidth = size.width || size;
  9656. var requiredHeight = size.height || size;
  9657. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  9658. var textureSize = this.getSize();
  9659. this.video = document.createElement("video");
  9660. this.video.width = textureSize.width;
  9661. this.video.height = textureSize.height;
  9662. this.video.autoplay = false;
  9663. this.video.loop = true;
  9664. this.video.addEventListener("canplaythrough", function () {
  9665. if (_this._texture) {
  9666. _this._texture.isReady = true;
  9667. }
  9668. });
  9669. urls.forEach(function (url) {
  9670. var source = document.createElement("source");
  9671. source.src = url;
  9672. _this.video.appendChild(source);
  9673. });
  9674. this._lastUpdate = new Date().getTime();
  9675. }
  9676. VideoTexture.prototype.update = function () {
  9677. if (this._autoLaunch) {
  9678. this._autoLaunch = false;
  9679. this.video.play();
  9680. }
  9681. var now = new Date().getTime();
  9682. if (now - this._lastUpdate < 15) {
  9683. return false;
  9684. }
  9685. this._lastUpdate = now;
  9686. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  9687. return true;
  9688. };
  9689. return VideoTexture;
  9690. })(BABYLON.Texture);
  9691. BABYLON.VideoTexture = VideoTexture;
  9692. })(BABYLON || (BABYLON = {}));
  9693. var BABYLON;
  9694. (function (BABYLON) {
  9695. var EffectFallbacks = (function () {
  9696. function EffectFallbacks() {
  9697. this._defines = {};
  9698. this._currentRank = 32;
  9699. this._maxRank = -1;
  9700. }
  9701. EffectFallbacks.prototype.addFallback = function (rank, define) {
  9702. if (!this._defines[rank]) {
  9703. if (rank < this._currentRank) {
  9704. this._currentRank = rank;
  9705. }
  9706. if (rank > this._maxRank) {
  9707. this._maxRank = rank;
  9708. }
  9709. this._defines[rank] = new Array();
  9710. }
  9711. this._defines[rank].push(define);
  9712. };
  9713. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  9714. get: function () {
  9715. return this._currentRank <= this._maxRank;
  9716. },
  9717. enumerable: true,
  9718. configurable: true
  9719. });
  9720. EffectFallbacks.prototype.reduce = function (currentDefines) {
  9721. var currentFallbacks = this._defines[this._currentRank];
  9722. for (var index = 0; index < currentFallbacks.length; index++) {
  9723. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  9724. }
  9725. this._currentRank++;
  9726. return currentDefines;
  9727. };
  9728. return EffectFallbacks;
  9729. })();
  9730. BABYLON.EffectFallbacks = EffectFallbacks;
  9731. var Effect = (function () {
  9732. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  9733. var _this = this;
  9734. this._isReady = false;
  9735. this._compilationError = "";
  9736. this._valueCache = [];
  9737. this._engine = engine;
  9738. this.name = baseName;
  9739. this.defines = defines;
  9740. this._uniformsNames = uniformsNames.concat(samplers);
  9741. this._samplers = samplers;
  9742. this._attributesNames = attributesNames;
  9743. this.onError = onError;
  9744. this.onCompiled = onCompiled;
  9745. var vertexSource;
  9746. var fragmentSource;
  9747. if (baseName.vertexElement) {
  9748. vertexSource = document.getElementById(baseName.vertexElement);
  9749. if (!vertexSource) {
  9750. vertexSource = baseName.vertexElement;
  9751. }
  9752. } else {
  9753. vertexSource = baseName.vertex || baseName;
  9754. }
  9755. if (baseName.fragmentElement) {
  9756. fragmentSource = document.getElementById(baseName.fragmentElement);
  9757. if (!fragmentSource) {
  9758. fragmentSource = baseName.fragmentElement;
  9759. }
  9760. } else {
  9761. fragmentSource = baseName.fragment || baseName;
  9762. }
  9763. this._loadVertexShader(vertexSource, function (vertexCode) {
  9764. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  9765. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  9766. });
  9767. });
  9768. }
  9769. Effect.prototype.isReady = function () {
  9770. return this._isReady;
  9771. };
  9772. Effect.prototype.getProgram = function () {
  9773. return this._program;
  9774. };
  9775. Effect.prototype.getAttributesNames = function () {
  9776. return this._attributesNames;
  9777. };
  9778. Effect.prototype.getAttributeLocation = function (index) {
  9779. return this._attributes[index];
  9780. };
  9781. Effect.prototype.getAttributeLocationByName = function (name) {
  9782. var index = this._attributesNames.indexOf(name);
  9783. return this._attributes[index];
  9784. };
  9785. Effect.prototype.getAttributesCount = function () {
  9786. return this._attributes.length;
  9787. };
  9788. Effect.prototype.getUniformIndex = function (uniformName) {
  9789. return this._uniformsNames.indexOf(uniformName);
  9790. };
  9791. Effect.prototype.getUniform = function (uniformName) {
  9792. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  9793. };
  9794. Effect.prototype.getSamplers = function () {
  9795. return this._samplers;
  9796. };
  9797. Effect.prototype.getCompilationError = function () {
  9798. return this._compilationError;
  9799. };
  9800. Effect.prototype._loadVertexShader = function (vertex, callback) {
  9801. if (vertex instanceof HTMLElement) {
  9802. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  9803. callback(vertexCode);
  9804. return;
  9805. }
  9806. if (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
  9807. callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
  9808. return;
  9809. }
  9810. var vertexShaderUrl;
  9811. if (vertex[0] === ".") {
  9812. vertexShaderUrl = vertex;
  9813. } else {
  9814. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  9815. }
  9816. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  9817. };
  9818. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  9819. if (fragment instanceof HTMLElement) {
  9820. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  9821. callback(fragmentCode);
  9822. return;
  9823. }
  9824. if (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
  9825. callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
  9826. return;
  9827. }
  9828. if (BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]) {
  9829. callback(BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]);
  9830. return;
  9831. }
  9832. var fragmentShaderUrl;
  9833. if (fragment[0] === ".") {
  9834. fragmentShaderUrl = fragment;
  9835. } else {
  9836. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  9837. }
  9838. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  9839. };
  9840. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  9841. try {
  9842. var engine = this._engine;
  9843. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  9844. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  9845. this._attributes = engine.getAttributes(this._program, attributesNames);
  9846. for (var index = 0; index < this._samplers.length; index++) {
  9847. var sampler = this.getUniform(this._samplers[index]);
  9848. if (sampler == null) {
  9849. this._samplers.splice(index, 1);
  9850. index--;
  9851. }
  9852. }
  9853. engine.bindSamplers(this);
  9854. this._isReady = true;
  9855. if (this.onCompiled) {
  9856. this.onCompiled(this);
  9857. }
  9858. } catch (e) {
  9859. if (fallbacks && fallbacks.isMoreFallbacks) {
  9860. defines = fallbacks.reduce(defines);
  9861. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  9862. } else {
  9863. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  9864. BABYLON.Tools.Error("Defines: " + defines);
  9865. BABYLON.Tools.Error("Error: " + e.message);
  9866. this._compilationError = e.message;
  9867. if (this.onError) {
  9868. this.onError(this, this._compilationError);
  9869. }
  9870. }
  9871. }
  9872. };
  9873. Effect.prototype._bindTexture = function (channel, texture) {
  9874. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  9875. };
  9876. Effect.prototype.setTexture = function (channel, texture) {
  9877. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  9878. };
  9879. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  9880. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  9881. };
  9882. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  9883. if (!this._valueCache[uniformName]) {
  9884. this._valueCache[uniformName] = [x, y];
  9885. return;
  9886. }
  9887. this._valueCache[uniformName][0] = x;
  9888. this._valueCache[uniformName][1] = y;
  9889. };
  9890. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  9891. if (!this._valueCache[uniformName]) {
  9892. this._valueCache[uniformName] = [x, y, z];
  9893. return;
  9894. }
  9895. this._valueCache[uniformName][0] = x;
  9896. this._valueCache[uniformName][1] = y;
  9897. this._valueCache[uniformName][2] = z;
  9898. };
  9899. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  9900. if (!this._valueCache[uniformName]) {
  9901. this._valueCache[uniformName] = [x, y, z, w];
  9902. return;
  9903. }
  9904. this._valueCache[uniformName][0] = x;
  9905. this._valueCache[uniformName][1] = y;
  9906. this._valueCache[uniformName][2] = z;
  9907. this._valueCache[uniformName][3] = w;
  9908. };
  9909. Effect.prototype.setArray = function (uniformName, array) {
  9910. this._engine.setArray(this.getUniform(uniformName), array);
  9911. return this;
  9912. };
  9913. Effect.prototype.setMatrices = function (uniformName, matrices) {
  9914. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  9915. return this;
  9916. };
  9917. Effect.prototype.setMatrix = function (uniformName, matrix) {
  9918. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  9919. return this;
  9920. };
  9921. Effect.prototype.setFloat = function (uniformName, value) {
  9922. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  9923. return this;
  9924. this._valueCache[uniformName] = value;
  9925. this._engine.setFloat(this.getUniform(uniformName), value);
  9926. return this;
  9927. };
  9928. Effect.prototype.setBool = function (uniformName, bool) {
  9929. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  9930. return this;
  9931. this._valueCache[uniformName] = bool;
  9932. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  9933. return this;
  9934. };
  9935. Effect.prototype.setVector2 = function (uniformName, vector2) {
  9936. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector2.x && this._valueCache[uniformName][1] == vector2.y)
  9937. return this;
  9938. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  9939. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  9940. return this;
  9941. };
  9942. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  9943. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y)
  9944. return this;
  9945. this._cacheFloat2(uniformName, x, y);
  9946. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  9947. return this;
  9948. };
  9949. Effect.prototype.setVector3 = function (uniformName, vector3) {
  9950. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector3.x && this._valueCache[uniformName][1] == vector3.y && this._valueCache[uniformName][2] == vector3.z)
  9951. return this;
  9952. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  9953. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  9954. return this;
  9955. };
  9956. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  9957. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z)
  9958. return this;
  9959. this._cacheFloat3(uniformName, x, y, z);
  9960. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  9961. return this;
  9962. };
  9963. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  9964. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z && this._valueCache[uniformName][3] == w)
  9965. return this;
  9966. this._cacheFloat4(uniformName, x, y, z, w);
  9967. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  9968. return this;
  9969. };
  9970. Effect.prototype.setColor3 = function (uniformName, color3) {
  9971. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b)
  9972. return this;
  9973. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  9974. this._engine.setColor3(this.getUniform(uniformName), color3);
  9975. return this;
  9976. };
  9977. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  9978. 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)
  9979. return this;
  9980. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  9981. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  9982. return this;
  9983. };
  9984. 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}",
  9985. 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}",
  9986. 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}",
  9987. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  9988. 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}",
  9989. 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}",
  9990. 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}",
  9991. 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}",
  9992. 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}",
  9993. 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}",
  9994. 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}",
  9995. 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}",
  9996. 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}",
  9997. 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}",
  9998. 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}",
  9999. 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}",
  10000. 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}",
  10001. 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\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}",
  10002. 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}",
  10003. 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}",
  10004. 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}",
  10005. 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}",
  10006. 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}",
  10007. 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}",
  10008. 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}",
  10009. 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}",
  10010. 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}",
  10011. 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}",
  10012. 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}",
  10013. };
  10014. return Effect;
  10015. })();
  10016. BABYLON.Effect = Effect;
  10017. })(BABYLON || (BABYLON = {}));
  10018. var BABYLON;
  10019. (function (BABYLON) {
  10020. var Material = (function () {
  10021. function Material(name, scene, doNotAdd) {
  10022. this.name = name;
  10023. this.checkReadyOnEveryCall = true;
  10024. this.checkReadyOnlyOnce = false;
  10025. this.state = "";
  10026. this.alpha = 1.0;
  10027. this.wireframe = false;
  10028. this.backFaceCulling = true;
  10029. this._wasPreviouslyReady = false;
  10030. this.id = name;
  10031. this._scene = scene;
  10032. if (!doNotAdd) {
  10033. scene.materials.push(this);
  10034. }
  10035. }
  10036. Material.prototype.isReady = function (mesh, useInstances) {
  10037. return true;
  10038. };
  10039. Material.prototype.getEffect = function () {
  10040. return this._effect;
  10041. };
  10042. Material.prototype.getScene = function () {
  10043. return this._scene;
  10044. };
  10045. Material.prototype.needAlphaBlending = function () {
  10046. return (this.alpha < 1.0);
  10047. };
  10048. Material.prototype.needAlphaTesting = function () {
  10049. return false;
  10050. };
  10051. Material.prototype.getAlphaTestTexture = function () {
  10052. return null;
  10053. };
  10054. Material.prototype.trackCreation = function (onCompiled, onError) {
  10055. };
  10056. Material.prototype._preBind = function () {
  10057. var engine = this._scene.getEngine();
  10058. engine.enableEffect(this._effect);
  10059. engine.setState(this.backFaceCulling);
  10060. };
  10061. Material.prototype.bind = function (world, mesh) {
  10062. };
  10063. Material.prototype.bindOnlyWorldMatrix = function (world) {
  10064. };
  10065. Material.prototype.unbind = function () {
  10066. };
  10067. Material.prototype.dispose = function (forceDisposeEffect) {
  10068. var index = this._scene.materials.indexOf(this);
  10069. this._scene.materials.splice(index, 1);
  10070. if (forceDisposeEffect && this._effect) {
  10071. this._scene.getEngine()._releaseEffect(this._effect);
  10072. this._effect = null;
  10073. }
  10074. if (this.onDispose) {
  10075. this.onDispose();
  10076. }
  10077. };
  10078. return Material;
  10079. })();
  10080. BABYLON.Material = Material;
  10081. })(BABYLON || (BABYLON = {}));
  10082. var __extends = this.__extends || function (d, b) {
  10083. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10084. function __() { this.constructor = d; }
  10085. __.prototype = b.prototype;
  10086. d.prototype = new __();
  10087. };
  10088. var BABYLON;
  10089. (function (BABYLON) {
  10090. var maxSimultaneousLights = 4;
  10091. var FresnelParameters = (function () {
  10092. function FresnelParameters() {
  10093. this.isEnabled = true;
  10094. this.leftColor = BABYLON.Color3.White();
  10095. this.rightColor = BABYLON.Color3.Black();
  10096. this.bias = 0;
  10097. this.power = 1;
  10098. }
  10099. return FresnelParameters;
  10100. })();
  10101. BABYLON.FresnelParameters = FresnelParameters;
  10102. var StandardMaterial = (function (_super) {
  10103. __extends(StandardMaterial, _super);
  10104. function StandardMaterial(name, scene) {
  10105. var _this = this;
  10106. _super.call(this, name, scene);
  10107. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  10108. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  10109. this.specularColor = new BABYLON.Color3(1, 1, 1);
  10110. this.specularPower = 64;
  10111. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  10112. this.useAlphaFromDiffuseTexture = false;
  10113. this.useSpecularOverAlpha = true;
  10114. this._cachedDefines = null;
  10115. this._renderTargets = new BABYLON.SmartArray(16);
  10116. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  10117. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  10118. this._scaledDiffuse = new BABYLON.Color3();
  10119. this._scaledSpecular = new BABYLON.Color3();
  10120. this.getRenderTargetTextures = function () {
  10121. _this._renderTargets.reset();
  10122. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  10123. _this._renderTargets.push(_this.reflectionTexture);
  10124. }
  10125. return _this._renderTargets;
  10126. };
  10127. }
  10128. StandardMaterial.prototype.needAlphaBlending = function () {
  10129. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  10130. };
  10131. StandardMaterial.prototype.needAlphaTesting = function () {
  10132. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  10133. };
  10134. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  10135. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  10136. };
  10137. StandardMaterial.prototype.getAlphaTestTexture = function () {
  10138. return this.diffuseTexture;
  10139. };
  10140. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  10141. if (this.checkReadyOnlyOnce) {
  10142. if (this._wasPreviouslyReady) {
  10143. return true;
  10144. }
  10145. }
  10146. var scene = this.getScene();
  10147. if (!this.checkReadyOnEveryCall) {
  10148. if (this._renderId === scene.getRenderId()) {
  10149. return true;
  10150. }
  10151. }
  10152. var engine = scene.getEngine();
  10153. var defines = [];
  10154. var fallbacks = new BABYLON.EffectFallbacks();
  10155. if (scene.texturesEnabled) {
  10156. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  10157. if (!this.diffuseTexture.isReady()) {
  10158. return false;
  10159. } else {
  10160. defines.push("#define DIFFUSE");
  10161. }
  10162. }
  10163. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  10164. if (!this.ambientTexture.isReady()) {
  10165. return false;
  10166. } else {
  10167. defines.push("#define AMBIENT");
  10168. }
  10169. }
  10170. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  10171. if (!this.opacityTexture.isReady()) {
  10172. return false;
  10173. } else {
  10174. defines.push("#define OPACITY");
  10175. if (this.opacityTexture.getAlphaFromRGB) {
  10176. defines.push("#define OPACITYRGB");
  10177. }
  10178. }
  10179. }
  10180. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  10181. if (!this.reflectionTexture.isReady()) {
  10182. return false;
  10183. } else {
  10184. defines.push("#define REFLECTION");
  10185. fallbacks.addFallback(0, "REFLECTION");
  10186. }
  10187. }
  10188. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10189. if (!this.emissiveTexture.isReady()) {
  10190. return false;
  10191. } else {
  10192. defines.push("#define EMISSIVE");
  10193. }
  10194. }
  10195. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10196. if (!this.specularTexture.isReady()) {
  10197. return false;
  10198. } else {
  10199. defines.push("#define SPECULAR");
  10200. fallbacks.addFallback(0, "SPECULAR");
  10201. }
  10202. }
  10203. }
  10204. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10205. if (!this.bumpTexture.isReady()) {
  10206. return false;
  10207. } else {
  10208. defines.push("#define BUMP");
  10209. fallbacks.addFallback(0, "BUMP");
  10210. }
  10211. }
  10212. if (this.useSpecularOverAlpha) {
  10213. defines.push("#define SPECULAROVERALPHA");
  10214. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  10215. }
  10216. if (scene.clipPlane) {
  10217. defines.push("#define CLIPPLANE");
  10218. }
  10219. if (engine.getAlphaTesting()) {
  10220. defines.push("#define ALPHATEST");
  10221. }
  10222. if (this._shouldUseAlphaFromDiffuseTexture()) {
  10223. defines.push("#define ALPHAFROMDIFFUSE");
  10224. }
  10225. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10226. defines.push("#define FOG");
  10227. fallbacks.addFallback(1, "FOG");
  10228. }
  10229. var shadowsActivated = false;
  10230. var lightIndex = 0;
  10231. if (scene.lightsEnabled) {
  10232. for (var index = 0; index < scene.lights.length; index++) {
  10233. var light = scene.lights[index];
  10234. if (!light.isEnabled()) {
  10235. continue;
  10236. }
  10237. if (light._excludedMeshesIds.length > 0) {
  10238. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  10239. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  10240. if (excludedMesh) {
  10241. light.excludedMeshes.push(excludedMesh);
  10242. }
  10243. }
  10244. light._excludedMeshesIds = [];
  10245. }
  10246. if (light._includedOnlyMeshesIds.length > 0) {
  10247. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  10248. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  10249. if (includedOnlyMesh) {
  10250. light.includedOnlyMeshes.push(includedOnlyMesh);
  10251. }
  10252. }
  10253. light._includedOnlyMeshesIds = [];
  10254. }
  10255. if (!light.canAffectMesh(mesh)) {
  10256. continue;
  10257. }
  10258. defines.push("#define LIGHT" + lightIndex);
  10259. if (lightIndex > 0) {
  10260. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  10261. }
  10262. var type;
  10263. if (light instanceof BABYLON.SpotLight) {
  10264. type = "#define SPOTLIGHT" + lightIndex;
  10265. } else if (light instanceof BABYLON.HemisphericLight) {
  10266. type = "#define HEMILIGHT" + lightIndex;
  10267. } else {
  10268. type = "#define POINTDIRLIGHT" + lightIndex;
  10269. }
  10270. defines.push(type);
  10271. if (lightIndex > 0) {
  10272. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  10273. }
  10274. var shadowGenerator = light.getShadowGenerator();
  10275. if (mesh && mesh.receiveShadows && shadowGenerator) {
  10276. defines.push("#define SHADOW" + lightIndex);
  10277. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  10278. if (!shadowsActivated) {
  10279. defines.push("#define SHADOWS");
  10280. shadowsActivated = true;
  10281. }
  10282. if (shadowGenerator.useVarianceShadowMap) {
  10283. defines.push("#define SHADOWVSM" + lightIndex);
  10284. if (lightIndex > 0) {
  10285. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  10286. }
  10287. }
  10288. if (shadowGenerator.usePoissonSampling) {
  10289. defines.push("#define SHADOWPCF" + lightIndex);
  10290. if (lightIndex > 0) {
  10291. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  10292. }
  10293. }
  10294. }
  10295. lightIndex++;
  10296. if (lightIndex == maxSimultaneousLights)
  10297. break;
  10298. }
  10299. }
  10300. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10301. var fresnelRank = 1;
  10302. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10303. defines.push("#define DIFFUSEFRESNEL");
  10304. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  10305. fresnelRank++;
  10306. }
  10307. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10308. defines.push("#define OPACITYFRESNEL");
  10309. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  10310. fresnelRank++;
  10311. }
  10312. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10313. defines.push("#define REFLECTIONFRESNEL");
  10314. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  10315. fresnelRank++;
  10316. }
  10317. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10318. defines.push("#define EMISSIVEFRESNEL");
  10319. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  10320. fresnelRank++;
  10321. }
  10322. defines.push("#define FRESNEL");
  10323. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  10324. }
  10325. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  10326. if (mesh) {
  10327. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10328. attribs.push(BABYLON.VertexBuffer.UVKind);
  10329. defines.push("#define UV1");
  10330. }
  10331. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10332. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10333. defines.push("#define UV2");
  10334. }
  10335. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  10336. attribs.push(BABYLON.VertexBuffer.ColorKind);
  10337. defines.push("#define VERTEXCOLOR");
  10338. }
  10339. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10340. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10341. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10342. defines.push("#define BONES");
  10343. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10344. defines.push("#define BONES4");
  10345. fallbacks.addFallback(0, "BONES4");
  10346. }
  10347. if (useInstances) {
  10348. defines.push("#define INSTANCES");
  10349. attribs.push("world0");
  10350. attribs.push("world1");
  10351. attribs.push("world2");
  10352. attribs.push("world3");
  10353. }
  10354. }
  10355. var join = defines.join("\n");
  10356. if (this._cachedDefines != join) {
  10357. this._cachedDefines = join;
  10358. var shaderName = "default";
  10359. if (!scene.getEngine().getCaps().standardDerivatives) {
  10360. shaderName = "legacydefault";
  10361. }
  10362. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  10363. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  10364. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  10365. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  10366. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  10367. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  10368. "vFogInfos", "vFogColor",
  10369. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  10370. "mBones",
  10371. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  10372. "darkness0", "darkness1", "darkness2", "darkness3",
  10373. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  10374. ], [
  10375. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  10376. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  10377. ], join, fallbacks, this.onCompiled, this.onError);
  10378. }
  10379. if (!this._effect.isReady()) {
  10380. return false;
  10381. }
  10382. this._renderId = scene.getRenderId();
  10383. this._wasPreviouslyReady = true;
  10384. return true;
  10385. };
  10386. StandardMaterial.prototype.unbind = function () {
  10387. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  10388. this._effect.setTexture("reflection2DSampler", null);
  10389. }
  10390. };
  10391. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  10392. this._effect.setMatrix("world", world);
  10393. };
  10394. StandardMaterial.prototype.bind = function (world, mesh) {
  10395. var scene = this.getScene();
  10396. this.bindOnlyWorldMatrix(world);
  10397. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  10398. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10399. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  10400. }
  10401. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10402. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  10403. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  10404. }
  10405. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10406. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  10407. }
  10408. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10409. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  10410. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  10411. }
  10412. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10413. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  10414. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  10415. }
  10416. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  10417. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  10418. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  10419. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  10420. }
  10421. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  10422. this._effect.setTexture("ambientSampler", this.ambientTexture);
  10423. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  10424. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  10425. }
  10426. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  10427. this._effect.setTexture("opacitySampler", this.opacityTexture);
  10428. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  10429. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  10430. }
  10431. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  10432. if (this.reflectionTexture.isCube) {
  10433. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  10434. } else {
  10435. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  10436. }
  10437. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  10438. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  10439. }
  10440. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10441. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  10442. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  10443. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  10444. }
  10445. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10446. this._effect.setTexture("specularSampler", this.specularTexture);
  10447. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  10448. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  10449. }
  10450. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10451. this._effect.setTexture("bumpSampler", this.bumpTexture);
  10452. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
  10453. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  10454. }
  10455. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  10456. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  10457. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  10458. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  10459. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  10460. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  10461. if (scene.lightsEnabled) {
  10462. var lightIndex = 0;
  10463. for (var index = 0; index < scene.lights.length; index++) {
  10464. var light = scene.lights[index];
  10465. if (!light.isEnabled()) {
  10466. continue;
  10467. }
  10468. if (!light.canAffectMesh(mesh)) {
  10469. continue;
  10470. }
  10471. if (light instanceof BABYLON.PointLight) {
  10472. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10473. } else if (light instanceof BABYLON.DirectionalLight) {
  10474. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10475. } else if (light instanceof BABYLON.SpotLight) {
  10476. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  10477. } else if (light instanceof BABYLON.HemisphericLight) {
  10478. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  10479. }
  10480. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  10481. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  10482. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  10483. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  10484. var shadowGenerator = light.getShadowGenerator();
  10485. if (mesh.receiveShadows && shadowGenerator) {
  10486. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  10487. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  10488. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  10489. }
  10490. lightIndex++;
  10491. if (lightIndex == maxSimultaneousLights)
  10492. break;
  10493. }
  10494. }
  10495. if (scene.clipPlane) {
  10496. var clipPlane = scene.clipPlane;
  10497. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  10498. }
  10499. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  10500. this._effect.setMatrix("view", scene.getViewMatrix());
  10501. }
  10502. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10503. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  10504. this._effect.setColor3("vFogColor", scene.fogColor);
  10505. }
  10506. };
  10507. StandardMaterial.prototype.getAnimatables = function () {
  10508. var results = [];
  10509. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  10510. results.push(this.diffuseTexture);
  10511. }
  10512. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  10513. results.push(this.ambientTexture);
  10514. }
  10515. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  10516. results.push(this.opacityTexture);
  10517. }
  10518. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  10519. results.push(this.reflectionTexture);
  10520. }
  10521. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  10522. results.push(this.emissiveTexture);
  10523. }
  10524. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  10525. results.push(this.specularTexture);
  10526. }
  10527. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  10528. results.push(this.bumpTexture);
  10529. }
  10530. return results;
  10531. };
  10532. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  10533. if (this.diffuseTexture) {
  10534. this.diffuseTexture.dispose();
  10535. }
  10536. if (this.ambientTexture) {
  10537. this.ambientTexture.dispose();
  10538. }
  10539. if (this.opacityTexture) {
  10540. this.opacityTexture.dispose();
  10541. }
  10542. if (this.reflectionTexture) {
  10543. this.reflectionTexture.dispose();
  10544. }
  10545. if (this.emissiveTexture) {
  10546. this.emissiveTexture.dispose();
  10547. }
  10548. if (this.specularTexture) {
  10549. this.specularTexture.dispose();
  10550. }
  10551. if (this.bumpTexture) {
  10552. this.bumpTexture.dispose();
  10553. }
  10554. _super.prototype.dispose.call(this, forceDisposeEffect);
  10555. };
  10556. StandardMaterial.prototype.clone = function (name) {
  10557. var newStandardMaterial = new BABYLON.StandardMaterial(name, this.getScene());
  10558. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  10559. newStandardMaterial.alpha = this.alpha;
  10560. newStandardMaterial.wireframe = this.wireframe;
  10561. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  10562. if (this.diffuseTexture && this.diffuseTexture.clone) {
  10563. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  10564. }
  10565. if (this.ambientTexture && this.ambientTexture.clone) {
  10566. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  10567. }
  10568. if (this.opacityTexture && this.opacityTexture.clone) {
  10569. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  10570. }
  10571. if (this.reflectionTexture && this.reflectionTexture.clone) {
  10572. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  10573. }
  10574. if (this.emissiveTexture && this.emissiveTexture.clone) {
  10575. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  10576. }
  10577. if (this.specularTexture && this.specularTexture.clone) {
  10578. newStandardMaterial.specularTexture = this.specularTexture.clone();
  10579. }
  10580. if (this.bumpTexture && this.bumpTexture.clone) {
  10581. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  10582. }
  10583. newStandardMaterial.ambientColor = this.ambientColor.clone();
  10584. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  10585. newStandardMaterial.specularColor = this.specularColor.clone();
  10586. newStandardMaterial.specularPower = this.specularPower;
  10587. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  10588. return newStandardMaterial;
  10589. };
  10590. StandardMaterial.DiffuseTextureEnabled = true;
  10591. StandardMaterial.AmbientTextureEnabled = true;
  10592. StandardMaterial.OpacityTextureEnabled = true;
  10593. StandardMaterial.ReflectionTextureEnabled = true;
  10594. StandardMaterial.EmissiveTextureEnabled = true;
  10595. StandardMaterial.SpecularTextureEnabled = true;
  10596. StandardMaterial.BumpTextureEnabled = true;
  10597. return StandardMaterial;
  10598. })(BABYLON.Material);
  10599. BABYLON.StandardMaterial = StandardMaterial;
  10600. })(BABYLON || (BABYLON = {}));
  10601. var __extends = this.__extends || function (d, b) {
  10602. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10603. function __() { this.constructor = d; }
  10604. __.prototype = b.prototype;
  10605. d.prototype = new __();
  10606. };
  10607. var BABYLON;
  10608. (function (BABYLON) {
  10609. var MultiMaterial = (function (_super) {
  10610. __extends(MultiMaterial, _super);
  10611. function MultiMaterial(name, scene) {
  10612. _super.call(this, name, scene, true);
  10613. this.subMaterials = new Array();
  10614. scene.multiMaterials.push(this);
  10615. }
  10616. MultiMaterial.prototype.getSubMaterial = function (index) {
  10617. if (index < 0 || index >= this.subMaterials.length) {
  10618. return this.getScene().defaultMaterial;
  10619. }
  10620. return this.subMaterials[index];
  10621. };
  10622. MultiMaterial.prototype.isReady = function (mesh) {
  10623. for (var index = 0; index < this.subMaterials.length; index++) {
  10624. var subMaterial = this.subMaterials[index];
  10625. if (subMaterial) {
  10626. if (!this.subMaterials[index].isReady(mesh)) {
  10627. return false;
  10628. }
  10629. }
  10630. }
  10631. return true;
  10632. };
  10633. return MultiMaterial;
  10634. })(BABYLON.Material);
  10635. BABYLON.MultiMaterial = MultiMaterial;
  10636. })(BABYLON || (BABYLON = {}));
  10637. var BABYLON;
  10638. (function (BABYLON) {
  10639. var Database = (function () {
  10640. function Database(urlToScene, callbackManifestChecked) {
  10641. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  10642. this.callbackManifestChecked = callbackManifestChecked;
  10643. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  10644. this.db = null;
  10645. this.enableSceneOffline = false;
  10646. this.enableTexturesOffline = false;
  10647. this.manifestVersionFound = 0;
  10648. this.mustUpdateRessources = false;
  10649. this.hasReachedQuota = false;
  10650. this.checkManifestFile();
  10651. }
  10652. Database.prototype.checkManifestFile = function () {
  10653. var _this = this;
  10654. function noManifestFile() {
  10655. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  10656. that.enableSceneOffline = false;
  10657. that.enableTexturesOffline = false;
  10658. that.callbackManifestChecked(false);
  10659. }
  10660. var that = this;
  10661. var manifestURL = this.currentSceneUrl + ".manifest";
  10662. var xhr = new XMLHttpRequest();
  10663. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  10664. xhr.open("GET", manifestURLTimeStamped, true);
  10665. xhr.addEventListener("load", function () {
  10666. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  10667. try {
  10668. var manifestFile = JSON.parse(xhr.response);
  10669. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  10670. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  10671. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  10672. _this.manifestVersionFound = manifestFile.version;
  10673. }
  10674. if (_this.callbackManifestChecked) {
  10675. _this.callbackManifestChecked(true);
  10676. }
  10677. } catch (ex) {
  10678. noManifestFile();
  10679. }
  10680. } else {
  10681. noManifestFile();
  10682. }
  10683. }, false);
  10684. xhr.addEventListener("error", function (event) {
  10685. noManifestFile();
  10686. }, false);
  10687. try {
  10688. xhr.send();
  10689. } catch (ex) {
  10690. BABYLON.Tools.Error("Error on XHR send request.");
  10691. that.callbackManifestChecked(false);
  10692. }
  10693. };
  10694. Database.prototype.openAsync = function (successCallback, errorCallback) {
  10695. var _this = this;
  10696. function handleError() {
  10697. that.isSupported = false;
  10698. if (errorCallback)
  10699. errorCallback();
  10700. }
  10701. var that = this;
  10702. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  10703. this.isSupported = false;
  10704. if (errorCallback)
  10705. errorCallback();
  10706. } else {
  10707. if (!this.db) {
  10708. this.hasReachedQuota = false;
  10709. this.isSupported = true;
  10710. var request = this.idbFactory.open("babylonjs", 1);
  10711. request.onerror = function (event) {
  10712. handleError();
  10713. };
  10714. request.onblocked = function (event) {
  10715. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  10716. handleError();
  10717. };
  10718. request.onsuccess = function (event) {
  10719. _this.db = request.result;
  10720. successCallback();
  10721. };
  10722. request.onupgradeneeded = function (event) {
  10723. _this.db = (event.target).result;
  10724. try {
  10725. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  10726. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  10727. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  10728. } catch (ex) {
  10729. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  10730. handleError();
  10731. }
  10732. };
  10733. } else {
  10734. if (successCallback)
  10735. successCallback();
  10736. }
  10737. }
  10738. };
  10739. Database.prototype.loadImageFromDB = function (url, image) {
  10740. var _this = this;
  10741. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  10742. var saveAndLoadImage = function () {
  10743. if (!_this.hasReachedQuota && _this.db !== null) {
  10744. _this._saveImageIntoDBAsync(completeURL, image);
  10745. } else {
  10746. image.src = url;
  10747. }
  10748. };
  10749. if (!this.mustUpdateRessources) {
  10750. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  10751. } else {
  10752. saveAndLoadImage();
  10753. }
  10754. };
  10755. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  10756. if (this.isSupported && this.db !== null) {
  10757. var texture;
  10758. var transaction = this.db.transaction(["textures"]);
  10759. transaction.onabort = function (event) {
  10760. image.src = url;
  10761. };
  10762. transaction.oncomplete = function (event) {
  10763. var blobTextureURL;
  10764. if (texture) {
  10765. var URL = window.URL || window.webkitURL;
  10766. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  10767. image.onerror = function () {
  10768. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  10769. image.src = url;
  10770. };
  10771. image.src = blobTextureURL;
  10772. } else {
  10773. notInDBCallback();
  10774. }
  10775. };
  10776. var getRequest = transaction.objectStore("textures").get(url);
  10777. getRequest.onsuccess = function (event) {
  10778. texture = (event.target).result;
  10779. };
  10780. getRequest.onerror = function (event) {
  10781. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  10782. image.src = url;
  10783. };
  10784. } else {
  10785. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10786. image.src = url;
  10787. }
  10788. };
  10789. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  10790. var _this = this;
  10791. if (this.isSupported) {
  10792. var generateBlobUrl = function () {
  10793. var blobTextureURL;
  10794. if (blob) {
  10795. var URL = window.URL || window.webkitURL;
  10796. try {
  10797. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  10798. } catch (ex) {
  10799. blobTextureURL = URL.createObjectURL(blob);
  10800. }
  10801. }
  10802. image.src = blobTextureURL;
  10803. };
  10804. if (BABYLON.Database.isUASupportingBlobStorage) {
  10805. var xhr = new XMLHttpRequest(), blob;
  10806. xhr.open("GET", url, true);
  10807. xhr.responseType = "blob";
  10808. xhr.addEventListener("load", function () {
  10809. if (xhr.status === 200) {
  10810. blob = xhr.response;
  10811. var transaction = _this.db.transaction(["textures"], "readwrite");
  10812. transaction.onabort = function (event) {
  10813. try {
  10814. if (event.srcElement.error.name === "QuotaExceededError") {
  10815. this.hasReachedQuota = true;
  10816. }
  10817. } catch (ex) {
  10818. }
  10819. generateBlobUrl();
  10820. };
  10821. transaction.oncomplete = function (event) {
  10822. generateBlobUrl();
  10823. };
  10824. var newTexture = { textureUrl: url, data: blob };
  10825. try {
  10826. var addRequest = transaction.objectStore("textures").put(newTexture);
  10827. addRequest.onsuccess = function (event) {
  10828. };
  10829. addRequest.onerror = function (event) {
  10830. generateBlobUrl();
  10831. };
  10832. } catch (ex) {
  10833. if (ex.code === 25) {
  10834. BABYLON.Database.isUASupportingBlobStorage = false;
  10835. }
  10836. image.src = url;
  10837. }
  10838. } else {
  10839. image.src = url;
  10840. }
  10841. }, false);
  10842. xhr.addEventListener("error", function (event) {
  10843. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  10844. image.src = url;
  10845. }, false);
  10846. xhr.send();
  10847. } else {
  10848. image.src = url;
  10849. }
  10850. } else {
  10851. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10852. image.src = url;
  10853. }
  10854. };
  10855. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  10856. var _this = this;
  10857. var updateVersion = function (event) {
  10858. _this._saveVersionIntoDBAsync(url, versionLoaded);
  10859. };
  10860. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  10861. };
  10862. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  10863. var _this = this;
  10864. if (this.isSupported) {
  10865. var version;
  10866. try {
  10867. var transaction = this.db.transaction(["versions"]);
  10868. transaction.oncomplete = function (event) {
  10869. if (version) {
  10870. if (_this.manifestVersionFound > version.data) {
  10871. _this.mustUpdateRessources = true;
  10872. updateInDBCallback();
  10873. } else {
  10874. callback(version.data);
  10875. }
  10876. } else {
  10877. _this.mustUpdateRessources = true;
  10878. updateInDBCallback();
  10879. }
  10880. };
  10881. transaction.onabort = function (event) {
  10882. callback(-1);
  10883. };
  10884. var getRequest = transaction.objectStore("versions").get(url);
  10885. getRequest.onsuccess = function (event) {
  10886. version = (event.target).result;
  10887. };
  10888. getRequest.onerror = function (event) {
  10889. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  10890. callback(-1);
  10891. };
  10892. } catch (ex) {
  10893. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  10894. callback(-1);
  10895. }
  10896. } else {
  10897. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10898. callback(-1);
  10899. }
  10900. };
  10901. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  10902. var _this = this;
  10903. if (this.isSupported && !this.hasReachedQuota) {
  10904. try {
  10905. var transaction = this.db.transaction(["versions"], "readwrite");
  10906. transaction.onabort = function (event) {
  10907. try {
  10908. if (event.srcElement.error.name === "QuotaExceededError") {
  10909. _this.hasReachedQuota = true;
  10910. }
  10911. } catch (ex) {
  10912. }
  10913. callback(-1);
  10914. };
  10915. transaction.oncomplete = function (event) {
  10916. callback(_this.manifestVersionFound);
  10917. };
  10918. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  10919. var addRequest = transaction.objectStore("versions").put(newVersion);
  10920. addRequest.onsuccess = function (event) {
  10921. };
  10922. addRequest.onerror = function (event) {
  10923. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  10924. };
  10925. } catch (ex) {
  10926. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  10927. callback(-1);
  10928. }
  10929. } else {
  10930. callback(-1);
  10931. }
  10932. };
  10933. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  10934. var _this = this;
  10935. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  10936. var saveAndLoadFile = function (event) {
  10937. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  10938. };
  10939. this._checkVersionFromDB(completeUrl, function (version) {
  10940. if (version !== -1) {
  10941. if (!_this.mustUpdateRessources) {
  10942. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  10943. } else {
  10944. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  10945. }
  10946. } else {
  10947. errorCallback();
  10948. }
  10949. });
  10950. };
  10951. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  10952. if (this.isSupported) {
  10953. var targetStore;
  10954. if (url.indexOf(".babylon") !== -1) {
  10955. targetStore = "scenes";
  10956. } else {
  10957. targetStore = "textures";
  10958. }
  10959. var file;
  10960. var transaction = this.db.transaction([targetStore]);
  10961. transaction.oncomplete = function (event) {
  10962. if (file) {
  10963. callback(file.data);
  10964. } else {
  10965. notInDBCallback();
  10966. }
  10967. };
  10968. transaction.onabort = function (event) {
  10969. notInDBCallback();
  10970. };
  10971. var getRequest = transaction.objectStore(targetStore).get(url);
  10972. getRequest.onsuccess = function (event) {
  10973. file = (event.target).result;
  10974. };
  10975. getRequest.onerror = function (event) {
  10976. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  10977. notInDBCallback();
  10978. };
  10979. } else {
  10980. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10981. callback();
  10982. }
  10983. };
  10984. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  10985. var _this = this;
  10986. if (this.isSupported) {
  10987. var targetStore;
  10988. if (url.indexOf(".babylon") !== -1) {
  10989. targetStore = "scenes";
  10990. } else {
  10991. targetStore = "textures";
  10992. }
  10993. var xhr = new XMLHttpRequest(), fileData;
  10994. xhr.open("GET", url, true);
  10995. if (useArrayBuffer) {
  10996. xhr.responseType = "arraybuffer";
  10997. }
  10998. xhr.onprogress = progressCallback;
  10999. xhr.addEventListener("load", function () {
  11000. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  11001. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  11002. if (!_this.hasReachedQuota) {
  11003. var transaction = _this.db.transaction([targetStore], "readwrite");
  11004. transaction.onabort = function (event) {
  11005. try {
  11006. if (event.srcElement.error.name === "QuotaExceededError") {
  11007. this.hasReachedQuota = true;
  11008. }
  11009. } catch (ex) {
  11010. }
  11011. callback(fileData);
  11012. };
  11013. transaction.oncomplete = function (event) {
  11014. callback(fileData);
  11015. };
  11016. var newFile;
  11017. if (targetStore === "scenes") {
  11018. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  11019. } else {
  11020. newFile = { textureUrl: url, data: fileData };
  11021. }
  11022. try {
  11023. var addRequest = transaction.objectStore(targetStore).put(newFile);
  11024. addRequest.onsuccess = function (event) {
  11025. };
  11026. addRequest.onerror = function (event) {
  11027. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  11028. };
  11029. } catch (ex) {
  11030. callback(fileData);
  11031. }
  11032. } else {
  11033. callback(fileData);
  11034. }
  11035. } else {
  11036. callback();
  11037. }
  11038. }, false);
  11039. xhr.addEventListener("error", function (event) {
  11040. BABYLON.Tools.Error("error on XHR request.");
  11041. callback();
  11042. }, false);
  11043. xhr.send();
  11044. } else {
  11045. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11046. callback();
  11047. }
  11048. };
  11049. Database.isUASupportingBlobStorage = true;
  11050. Database.parseURL = function (url) {
  11051. var a = document.createElement('a');
  11052. a.href = url;
  11053. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  11054. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  11055. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  11056. return absLocation;
  11057. };
  11058. Database.ReturnFullUrlLocation = function (url) {
  11059. if (url.indexOf("http:/") === -1) {
  11060. return (BABYLON.Database.parseURL(window.location.href) + url);
  11061. } else {
  11062. return url;
  11063. }
  11064. };
  11065. return Database;
  11066. })();
  11067. BABYLON.Database = Database;
  11068. })(BABYLON || (BABYLON = {}));
  11069. var BABYLON;
  11070. (function (BABYLON) {
  11071. var SpriteManager = (function () {
  11072. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  11073. this.name = name;
  11074. this.cellSize = cellSize;
  11075. this.sprites = new Array();
  11076. this.renderingGroupId = 0;
  11077. this._vertexDeclaration = [3, 4, 4, 4];
  11078. this._vertexStrideSize = 15 * 4;
  11079. this._capacity = capacity;
  11080. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  11081. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11082. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11083. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  11084. this._scene = scene;
  11085. this._scene.spriteManagers.push(this);
  11086. this._vertexDeclaration = [3, 4, 4, 4];
  11087. this._vertexStrideSize = 15 * 4;
  11088. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  11089. var indices = [];
  11090. var index = 0;
  11091. for (var count = 0; count < capacity; count++) {
  11092. indices.push(index);
  11093. indices.push(index + 1);
  11094. indices.push(index + 2);
  11095. indices.push(index);
  11096. indices.push(index + 2);
  11097. indices.push(index + 3);
  11098. index += 4;
  11099. }
  11100. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11101. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  11102. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  11103. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  11104. }
  11105. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  11106. var arrayOffset = index * 15;
  11107. if (offsetX == 0)
  11108. offsetX = this._epsilon;
  11109. else if (offsetX == 1)
  11110. offsetX = 1 - this._epsilon;
  11111. if (offsetY == 0)
  11112. offsetY = this._epsilon;
  11113. else if (offsetY == 1)
  11114. offsetY = 1 - this._epsilon;
  11115. this._vertices[arrayOffset] = sprite.position.x;
  11116. this._vertices[arrayOffset + 1] = sprite.position.y;
  11117. this._vertices[arrayOffset + 2] = sprite.position.z;
  11118. this._vertices[arrayOffset + 3] = sprite.angle;
  11119. this._vertices[arrayOffset + 4] = sprite.size;
  11120. this._vertices[arrayOffset + 5] = offsetX;
  11121. this._vertices[arrayOffset + 6] = offsetY;
  11122. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  11123. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  11124. var offset = (sprite.cellIndex / rowSize) >> 0;
  11125. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  11126. this._vertices[arrayOffset + 10] = offset;
  11127. this._vertices[arrayOffset + 11] = sprite.color.r;
  11128. this._vertices[arrayOffset + 12] = sprite.color.g;
  11129. this._vertices[arrayOffset + 13] = sprite.color.b;
  11130. this._vertices[arrayOffset + 14] = sprite.color.a;
  11131. };
  11132. SpriteManager.prototype.render = function () {
  11133. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  11134. return;
  11135. var engine = this._scene.getEngine();
  11136. var baseSize = this._spriteTexture.getBaseSize();
  11137. var deltaTime = BABYLON.Tools.GetDeltaTime();
  11138. var max = Math.min(this._capacity, this.sprites.length);
  11139. var rowSize = baseSize.width / this.cellSize;
  11140. var offset = 0;
  11141. for (var index = 0; index < max; index++) {
  11142. var sprite = this.sprites[index];
  11143. if (!sprite) {
  11144. continue;
  11145. }
  11146. sprite._animate(deltaTime);
  11147. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  11148. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  11149. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  11150. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  11151. }
  11152. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
  11153. var effect = this._effectBase;
  11154. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  11155. effect = this._effectFog;
  11156. }
  11157. engine.enableEffect(effect);
  11158. var viewMatrix = this._scene.getViewMatrix();
  11159. effect.setTexture("diffuseSampler", this._spriteTexture);
  11160. effect.setMatrix("view", viewMatrix);
  11161. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  11162. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  11163. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  11164. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  11165. effect.setColor3("vFogColor", this._scene.fogColor);
  11166. }
  11167. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  11168. effect.setBool("alphaTest", true);
  11169. engine.setColorWrite(false);
  11170. engine.draw(true, 0, max * 6);
  11171. engine.setColorWrite(true);
  11172. effect.setBool("alphaTest", false);
  11173. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11174. engine.draw(true, 0, max * 6);
  11175. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11176. };
  11177. SpriteManager.prototype.dispose = function () {
  11178. if (this._vertexBuffer) {
  11179. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11180. this._vertexBuffer = null;
  11181. }
  11182. if (this._indexBuffer) {
  11183. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11184. this._indexBuffer = null;
  11185. }
  11186. if (this._spriteTexture) {
  11187. this._spriteTexture.dispose();
  11188. this._spriteTexture = null;
  11189. }
  11190. var index = this._scene.spriteManagers.indexOf(this);
  11191. this._scene.spriteManagers.splice(index, 1);
  11192. if (this.onDispose) {
  11193. this.onDispose();
  11194. }
  11195. };
  11196. return SpriteManager;
  11197. })();
  11198. BABYLON.SpriteManager = SpriteManager;
  11199. })(BABYLON || (BABYLON = {}));
  11200. var BABYLON;
  11201. (function (BABYLON) {
  11202. var Sprite = (function () {
  11203. function Sprite(name, manager) {
  11204. this.name = name;
  11205. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11206. this.size = 1.0;
  11207. this.angle = 0;
  11208. this.cellIndex = 0;
  11209. this.invertU = 0;
  11210. this.invertV = 0;
  11211. this.animations = new Array();
  11212. this._animationStarted = false;
  11213. this._loopAnimation = false;
  11214. this._fromIndex = 0;
  11215. this._toIndex = 0;
  11216. this._delay = 0;
  11217. this._direction = 1;
  11218. this._frameCount = 0;
  11219. this._time = 0;
  11220. this._manager = manager;
  11221. this._manager.sprites.push(this);
  11222. this.position = BABYLON.Vector3.Zero();
  11223. }
  11224. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  11225. this._fromIndex = from;
  11226. this._toIndex = to;
  11227. this._loopAnimation = loop;
  11228. this._delay = delay;
  11229. this._animationStarted = true;
  11230. this._direction = from < to ? 1 : -1;
  11231. this.cellIndex = from;
  11232. this._time = 0;
  11233. };
  11234. Sprite.prototype.stopAnimation = function () {
  11235. this._animationStarted = false;
  11236. };
  11237. Sprite.prototype._animate = function (deltaTime) {
  11238. if (!this._animationStarted)
  11239. return;
  11240. this._time += deltaTime;
  11241. if (this._time > this._delay) {
  11242. this._time = this._time % this._delay;
  11243. this.cellIndex += this._direction;
  11244. if (this.cellIndex == this._toIndex) {
  11245. if (this._loopAnimation) {
  11246. this.cellIndex = this._fromIndex;
  11247. } else {
  11248. this._animationStarted = false;
  11249. if (this.disposeWhenFinishedAnimating) {
  11250. this.dispose();
  11251. }
  11252. }
  11253. }
  11254. }
  11255. };
  11256. Sprite.prototype.dispose = function () {
  11257. for (var i = 0; i < this._manager.sprites.length; i++) {
  11258. if (this._manager.sprites[i] == this) {
  11259. this._manager.sprites.splice(i, 1);
  11260. }
  11261. }
  11262. };
  11263. return Sprite;
  11264. })();
  11265. BABYLON.Sprite = Sprite;
  11266. })(BABYLON || (BABYLON = {}));
  11267. var BABYLON;
  11268. (function (BABYLON) {
  11269. var Layer = (function () {
  11270. function Layer(name, imgUrl, scene, isBackground, color) {
  11271. this.name = name;
  11272. this._vertexDeclaration = [2];
  11273. this._vertexStrideSize = 2 * 4;
  11274. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  11275. this.isBackground = isBackground === undefined ? true : isBackground;
  11276. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  11277. this._scene = scene;
  11278. this._scene.layers.push(this);
  11279. var vertices = [];
  11280. vertices.push(1, 1);
  11281. vertices.push(-1, 1);
  11282. vertices.push(-1, -1);
  11283. vertices.push(1, -1);
  11284. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11285. var indices = [];
  11286. indices.push(0);
  11287. indices.push(1);
  11288. indices.push(2);
  11289. indices.push(0);
  11290. indices.push(2);
  11291. indices.push(3);
  11292. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11293. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  11294. }
  11295. Layer.prototype.render = function () {
  11296. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  11297. return;
  11298. var engine = this._scene.getEngine();
  11299. engine.enableEffect(this._effect);
  11300. engine.setState(false);
  11301. this._effect.setTexture("textureSampler", this.texture);
  11302. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  11303. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  11304. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11305. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11306. engine.draw(true, 0, 6);
  11307. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11308. };
  11309. Layer.prototype.dispose = function () {
  11310. if (this._vertexBuffer) {
  11311. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11312. this._vertexBuffer = null;
  11313. }
  11314. if (this._indexBuffer) {
  11315. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11316. this._indexBuffer = null;
  11317. }
  11318. if (this.texture) {
  11319. this.texture.dispose();
  11320. this.texture = null;
  11321. }
  11322. var index = this._scene.layers.indexOf(this);
  11323. this._scene.layers.splice(index, 1);
  11324. if (this.onDispose) {
  11325. this.onDispose();
  11326. }
  11327. };
  11328. return Layer;
  11329. })();
  11330. BABYLON.Layer = Layer;
  11331. })(BABYLON || (BABYLON = {}));
  11332. var BABYLON;
  11333. (function (BABYLON) {
  11334. var Particle = (function () {
  11335. function Particle() {
  11336. this.position = BABYLON.Vector3.Zero();
  11337. this.direction = BABYLON.Vector3.Zero();
  11338. this.color = new BABYLON.Color4(0, 0, 0, 0);
  11339. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  11340. this.lifeTime = 1.0;
  11341. this.age = 0;
  11342. this.size = 0;
  11343. this.angle = 0;
  11344. this.angularSpeed = 0;
  11345. }
  11346. return Particle;
  11347. })();
  11348. BABYLON.Particle = Particle;
  11349. })(BABYLON || (BABYLON = {}));
  11350. var BABYLON;
  11351. (function (BABYLON) {
  11352. var randomNumber = function (min, max) {
  11353. if (min == max) {
  11354. return (min);
  11355. }
  11356. var random = Math.random();
  11357. return ((random * (max - min)) + min);
  11358. };
  11359. var ParticleSystem = (function () {
  11360. function ParticleSystem(name, capacity, scene, customEffect) {
  11361. var _this = this;
  11362. this.name = name;
  11363. this.renderingGroupId = 0;
  11364. this.emitter = null;
  11365. this.emitRate = 10;
  11366. this.manualEmitCount = -1;
  11367. this.updateSpeed = 0.01;
  11368. this.targetStopDuration = 0;
  11369. this.disposeOnStop = false;
  11370. this.minEmitPower = 1;
  11371. this.maxEmitPower = 1;
  11372. this.minLifeTime = 1;
  11373. this.maxLifeTime = 1;
  11374. this.minSize = 1;
  11375. this.maxSize = 1;
  11376. this.minAngularSpeed = 0;
  11377. this.maxAngularSpeed = 0;
  11378. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  11379. this.forceDepthWrite = false;
  11380. this.gravity = BABYLON.Vector3.Zero();
  11381. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  11382. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  11383. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  11384. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11385. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11386. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11387. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  11388. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11389. this.particles = new Array();
  11390. this._vertexDeclaration = [3, 4, 4];
  11391. this._vertexStrideSize = 11 * 4;
  11392. this._stockParticles = new Array();
  11393. this._newPartsExcess = 0;
  11394. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  11395. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  11396. this._scaledDirection = BABYLON.Vector3.Zero();
  11397. this._scaledGravity = BABYLON.Vector3.Zero();
  11398. this._currentRenderId = -1;
  11399. this._started = false;
  11400. this._stopped = false;
  11401. this._actualFrame = 0;
  11402. this.id = name;
  11403. this._capacity = capacity;
  11404. this._scene = scene;
  11405. this._customEffect = customEffect;
  11406. scene.particleSystems.push(this);
  11407. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  11408. var indices = [];
  11409. var index = 0;
  11410. for (var count = 0; count < capacity; count++) {
  11411. indices.push(index);
  11412. indices.push(index + 1);
  11413. indices.push(index + 2);
  11414. indices.push(index);
  11415. indices.push(index + 2);
  11416. indices.push(index + 3);
  11417. index += 4;
  11418. }
  11419. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11420. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  11421. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  11422. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  11423. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  11424. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  11425. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  11426. };
  11427. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  11428. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  11429. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  11430. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  11431. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  11432. };
  11433. }
  11434. ParticleSystem.prototype.getCapacity = function () {
  11435. return this._capacity;
  11436. };
  11437. ParticleSystem.prototype.isAlive = function () {
  11438. return this._alive;
  11439. };
  11440. ParticleSystem.prototype.isStarted = function () {
  11441. return this._started;
  11442. };
  11443. ParticleSystem.prototype.start = function () {
  11444. this._started = true;
  11445. this._stopped = false;
  11446. this._actualFrame = 0;
  11447. };
  11448. ParticleSystem.prototype.stop = function () {
  11449. this._stopped = true;
  11450. };
  11451. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  11452. var offset = index * 11;
  11453. this._vertices[offset] = particle.position.x;
  11454. this._vertices[offset + 1] = particle.position.y;
  11455. this._vertices[offset + 2] = particle.position.z;
  11456. this._vertices[offset + 3] = particle.color.r;
  11457. this._vertices[offset + 4] = particle.color.g;
  11458. this._vertices[offset + 5] = particle.color.b;
  11459. this._vertices[offset + 6] = particle.color.a;
  11460. this._vertices[offset + 7] = particle.angle;
  11461. this._vertices[offset + 8] = particle.size;
  11462. this._vertices[offset + 9] = offsetX;
  11463. this._vertices[offset + 10] = offsetY;
  11464. };
  11465. ParticleSystem.prototype._update = function (newParticles) {
  11466. this._alive = this.particles.length > 0;
  11467. for (var index = 0; index < this.particles.length; index++) {
  11468. var particle = this.particles[index];
  11469. particle.age += this._scaledUpdateSpeed;
  11470. if (particle.age >= particle.lifeTime) {
  11471. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  11472. index--;
  11473. continue;
  11474. } else {
  11475. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  11476. particle.color.addInPlace(this._scaledColorStep);
  11477. if (particle.color.a < 0)
  11478. particle.color.a = 0;
  11479. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  11480. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  11481. particle.position.addInPlace(this._scaledDirection);
  11482. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  11483. particle.direction.addInPlace(this._scaledGravity);
  11484. }
  11485. }
  11486. var worldMatrix;
  11487. if (this.emitter.position) {
  11488. worldMatrix = this.emitter.getWorldMatrix();
  11489. } else {
  11490. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  11491. }
  11492. for (index = 0; index < newParticles; index++) {
  11493. if (this.particles.length == this._capacity) {
  11494. break;
  11495. }
  11496. if (this._stockParticles.length !== 0) {
  11497. particle = this._stockParticles.pop();
  11498. particle.age = 0;
  11499. } else {
  11500. particle = new BABYLON.Particle();
  11501. }
  11502. this.particles.push(particle);
  11503. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  11504. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  11505. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  11506. particle.size = randomNumber(this.minSize, this.maxSize);
  11507. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  11508. this.startPositionFunction(worldMatrix, particle.position);
  11509. var step = randomNumber(0, 1.0);
  11510. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  11511. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  11512. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  11513. }
  11514. };
  11515. ParticleSystem.prototype._getEffect = function () {
  11516. if (this._customEffect) {
  11517. return this._customEffect;
  11518. }
  11519. ;
  11520. var defines = [];
  11521. if (this._scene.clipPlane) {
  11522. defines.push("#define CLIPPLANE");
  11523. }
  11524. var join = defines.join("\n");
  11525. if (this._cachedDefines != join) {
  11526. this._cachedDefines = join;
  11527. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  11528. }
  11529. return this._effect;
  11530. };
  11531. ParticleSystem.prototype.animate = function () {
  11532. if (!this._started)
  11533. return;
  11534. var effect = this._getEffect();
  11535. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  11536. return;
  11537. if (this._currentRenderId === this._scene.getRenderId()) {
  11538. return;
  11539. }
  11540. this._currentRenderId = this._scene.getRenderId();
  11541. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  11542. var emitCout;
  11543. if (this.manualEmitCount > -1) {
  11544. emitCout = this.manualEmitCount;
  11545. this.manualEmitCount = 0;
  11546. } else {
  11547. emitCout = this.emitRate;
  11548. }
  11549. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  11550. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  11551. if (this._newPartsExcess > 1.0) {
  11552. newParticles += this._newPartsExcess >> 0;
  11553. this._newPartsExcess -= this._newPartsExcess >> 0;
  11554. }
  11555. this._alive = false;
  11556. if (!this._stopped) {
  11557. this._actualFrame += this._scaledUpdateSpeed;
  11558. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  11559. this.stop();
  11560. } else {
  11561. newParticles = 0;
  11562. }
  11563. this._update(newParticles);
  11564. if (this._stopped) {
  11565. if (!this._alive) {
  11566. this._started = false;
  11567. if (this.disposeOnStop) {
  11568. this._scene._toBeDisposed.push(this);
  11569. }
  11570. }
  11571. }
  11572. var offset = 0;
  11573. for (var index = 0; index < this.particles.length; index++) {
  11574. var particle = this.particles[index];
  11575. this._appendParticleVertex(offset++, particle, 0, 0);
  11576. this._appendParticleVertex(offset++, particle, 1, 0);
  11577. this._appendParticleVertex(offset++, particle, 1, 1);
  11578. this._appendParticleVertex(offset++, particle, 0, 1);
  11579. }
  11580. var engine = this._scene.getEngine();
  11581. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
  11582. };
  11583. ParticleSystem.prototype.render = function () {
  11584. var effect = this._getEffect();
  11585. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  11586. return 0;
  11587. var engine = this._scene.getEngine();
  11588. engine.enableEffect(effect);
  11589. var viewMatrix = this._scene.getViewMatrix();
  11590. effect.setTexture("diffuseSampler", this.particleTexture);
  11591. effect.setMatrix("view", viewMatrix);
  11592. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  11593. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  11594. if (this._scene.clipPlane) {
  11595. var clipPlane = this._scene.clipPlane;
  11596. var invView = viewMatrix.clone();
  11597. invView.invert();
  11598. effect.setMatrix("invView", invView);
  11599. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  11600. }
  11601. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  11602. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  11603. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  11604. } else {
  11605. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11606. }
  11607. if (this.forceDepthWrite) {
  11608. engine.setDepthWrite(true);
  11609. }
  11610. engine.draw(true, 0, this.particles.length * 6);
  11611. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11612. return this.particles.length;
  11613. };
  11614. ParticleSystem.prototype.dispose = function () {
  11615. if (this._vertexBuffer) {
  11616. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11617. this._vertexBuffer = null;
  11618. }
  11619. if (this._indexBuffer) {
  11620. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11621. this._indexBuffer = null;
  11622. }
  11623. if (this.particleTexture) {
  11624. this.particleTexture.dispose();
  11625. this.particleTexture = null;
  11626. }
  11627. var index = this._scene.particleSystems.indexOf(this);
  11628. this._scene.particleSystems.splice(index, 1);
  11629. if (this.onDispose) {
  11630. this.onDispose();
  11631. }
  11632. };
  11633. ParticleSystem.prototype.clone = function (name, newEmitter) {
  11634. var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
  11635. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  11636. if (newEmitter === undefined) {
  11637. newEmitter = this.emitter;
  11638. }
  11639. result.emitter = newEmitter;
  11640. if (this.particleTexture) {
  11641. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  11642. }
  11643. result.start();
  11644. return result;
  11645. };
  11646. ParticleSystem.BLENDMODE_ONEONE = 0;
  11647. ParticleSystem.BLENDMODE_STANDARD = 1;
  11648. return ParticleSystem;
  11649. })();
  11650. BABYLON.ParticleSystem = ParticleSystem;
  11651. })(BABYLON || (BABYLON = {}));
  11652. var BABYLON;
  11653. (function (BABYLON) {
  11654. var Animation = (function () {
  11655. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  11656. this.name = name;
  11657. this.targetProperty = targetProperty;
  11658. this.framePerSecond = framePerSecond;
  11659. this.dataType = dataType;
  11660. this.loopMode = loopMode;
  11661. this._offsetsCache = {};
  11662. this._highLimitsCache = {};
  11663. this._stopped = false;
  11664. this.targetPropertyPath = targetProperty.split(".");
  11665. this.dataType = dataType;
  11666. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  11667. }
  11668. Animation.prototype.isStopped = function () {
  11669. return this._stopped;
  11670. };
  11671. Animation.prototype.getKeys = function () {
  11672. return this._keys;
  11673. };
  11674. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  11675. return startValue + (endValue - startValue) * gradient;
  11676. };
  11677. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  11678. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  11679. };
  11680. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  11681. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  11682. };
  11683. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  11684. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  11685. };
  11686. Animation.prototype.clone = function () {
  11687. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  11688. clone.setKeys(this._keys);
  11689. return clone;
  11690. };
  11691. Animation.prototype.setKeys = function (values) {
  11692. this._keys = values.slice(0);
  11693. this._offsetsCache = {};
  11694. this._highLimitsCache = {};
  11695. };
  11696. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  11697. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  11698. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  11699. }
  11700. this.currentFrame = currentFrame;
  11701. for (var key = 0; key < this._keys.length; key++) {
  11702. if (this._keys[key + 1].frame >= currentFrame) {
  11703. var startValue = this._keys[key].value;
  11704. var endValue = this._keys[key + 1].value;
  11705. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  11706. switch (this.dataType) {
  11707. case Animation.ANIMATIONTYPE_FLOAT:
  11708. switch (loopMode) {
  11709. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11710. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11711. return this.floatInterpolateFunction(startValue, endValue, gradient);
  11712. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11713. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  11714. }
  11715. break;
  11716. case Animation.ANIMATIONTYPE_QUATERNION:
  11717. var quaternion = null;
  11718. switch (loopMode) {
  11719. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11720. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11721. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  11722. break;
  11723. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11724. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11725. break;
  11726. }
  11727. return quaternion;
  11728. case Animation.ANIMATIONTYPE_VECTOR3:
  11729. switch (loopMode) {
  11730. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11731. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11732. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  11733. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11734. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11735. }
  11736. case Animation.ANIMATIONTYPE_COLOR3:
  11737. switch (loopMode) {
  11738. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11739. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11740. return this.color3InterpolateFunction(startValue, endValue, gradient);
  11741. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11742. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11743. }
  11744. case Animation.ANIMATIONTYPE_MATRIX:
  11745. switch (loopMode) {
  11746. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11747. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11748. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11749. return startValue;
  11750. }
  11751. default:
  11752. break;
  11753. }
  11754. break;
  11755. }
  11756. }
  11757. return this._keys[this._keys.length - 1].value;
  11758. };
  11759. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  11760. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  11761. this._stopped = true;
  11762. return false;
  11763. }
  11764. var returnValue = true;
  11765. if (this._keys[0].frame != 0) {
  11766. var newKey = {
  11767. frame: 0,
  11768. value: this._keys[0].value
  11769. };
  11770. this._keys.splice(0, 0, newKey);
  11771. }
  11772. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  11773. from = this._keys[0].frame;
  11774. }
  11775. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  11776. to = this._keys[this._keys.length - 1].frame;
  11777. }
  11778. var range = to - from;
  11779. var offsetValue;
  11780. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  11781. if (ratio > range && !loop) {
  11782. returnValue = false;
  11783. highLimitValue = this._keys[this._keys.length - 1].value;
  11784. } else {
  11785. var highLimitValue = 0;
  11786. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  11787. var keyOffset = to.toString() + from.toString();
  11788. if (!this._offsetsCache[keyOffset]) {
  11789. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  11790. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  11791. switch (this.dataType) {
  11792. case Animation.ANIMATIONTYPE_FLOAT:
  11793. this._offsetsCache[keyOffset] = toValue - fromValue;
  11794. break;
  11795. case Animation.ANIMATIONTYPE_QUATERNION:
  11796. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11797. break;
  11798. case Animation.ANIMATIONTYPE_VECTOR3:
  11799. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11800. case Animation.ANIMATIONTYPE_COLOR3:
  11801. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11802. default:
  11803. break;
  11804. }
  11805. this._highLimitsCache[keyOffset] = toValue;
  11806. }
  11807. highLimitValue = this._highLimitsCache[keyOffset];
  11808. offsetValue = this._offsetsCache[keyOffset];
  11809. }
  11810. }
  11811. if (offsetValue === undefined) {
  11812. switch (this.dataType) {
  11813. case Animation.ANIMATIONTYPE_FLOAT:
  11814. offsetValue = 0;
  11815. break;
  11816. case Animation.ANIMATIONTYPE_QUATERNION:
  11817. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  11818. break;
  11819. case Animation.ANIMATIONTYPE_VECTOR3:
  11820. offsetValue = BABYLON.Vector3.Zero();
  11821. break;
  11822. case Animation.ANIMATIONTYPE_COLOR3:
  11823. offsetValue = BABYLON.Color3.Black();
  11824. }
  11825. }
  11826. var repeatCount = (ratio / range) >> 0;
  11827. var currentFrame = returnValue ? from + ratio % range : to;
  11828. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  11829. if (this.targetPropertyPath.length > 1) {
  11830. var property = this._target[this.targetPropertyPath[0]];
  11831. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  11832. property = property[this.targetPropertyPath[index]];
  11833. }
  11834. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  11835. } else {
  11836. this._target[this.targetPropertyPath[0]] = currentValue;
  11837. }
  11838. if (this._target.markAsDirty) {
  11839. this._target.markAsDirty(this.targetProperty);
  11840. }
  11841. if (!returnValue) {
  11842. this._stopped = true;
  11843. }
  11844. return returnValue;
  11845. };
  11846. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  11847. get: function () {
  11848. return Animation._ANIMATIONTYPE_FLOAT;
  11849. },
  11850. enumerable: true,
  11851. configurable: true
  11852. });
  11853. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  11854. get: function () {
  11855. return Animation._ANIMATIONTYPE_VECTOR3;
  11856. },
  11857. enumerable: true,
  11858. configurable: true
  11859. });
  11860. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  11861. get: function () {
  11862. return Animation._ANIMATIONTYPE_QUATERNION;
  11863. },
  11864. enumerable: true,
  11865. configurable: true
  11866. });
  11867. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  11868. get: function () {
  11869. return Animation._ANIMATIONTYPE_MATRIX;
  11870. },
  11871. enumerable: true,
  11872. configurable: true
  11873. });
  11874. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  11875. get: function () {
  11876. return Animation._ANIMATIONTYPE_COLOR3;
  11877. },
  11878. enumerable: true,
  11879. configurable: true
  11880. });
  11881. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  11882. get: function () {
  11883. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  11884. },
  11885. enumerable: true,
  11886. configurable: true
  11887. });
  11888. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  11889. get: function () {
  11890. return Animation._ANIMATIONLOOPMODE_CYCLE;
  11891. },
  11892. enumerable: true,
  11893. configurable: true
  11894. });
  11895. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  11896. get: function () {
  11897. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  11898. },
  11899. enumerable: true,
  11900. configurable: true
  11901. });
  11902. Animation._ANIMATIONTYPE_FLOAT = 0;
  11903. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  11904. Animation._ANIMATIONTYPE_QUATERNION = 2;
  11905. Animation._ANIMATIONTYPE_MATRIX = 3;
  11906. Animation._ANIMATIONTYPE_COLOR3 = 4;
  11907. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  11908. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  11909. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  11910. return Animation;
  11911. })();
  11912. BABYLON.Animation = Animation;
  11913. })(BABYLON || (BABYLON = {}));
  11914. var BABYLON;
  11915. (function (BABYLON) {
  11916. var Animatable = (function () {
  11917. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  11918. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  11919. if (typeof toFrame === "undefined") { toFrame = 100; }
  11920. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  11921. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  11922. this.target = target;
  11923. this.fromFrame = fromFrame;
  11924. this.toFrame = toFrame;
  11925. this.loopAnimation = loopAnimation;
  11926. this.speedRatio = speedRatio;
  11927. this.onAnimationEnd = onAnimationEnd;
  11928. this._animations = new Array();
  11929. this._paused = false;
  11930. this.animationStarted = false;
  11931. if (animations) {
  11932. this.appendAnimations(target, animations);
  11933. }
  11934. this._scene = scene;
  11935. scene._activeAnimatables.push(this);
  11936. }
  11937. Animatable.prototype.appendAnimations = function (target, animations) {
  11938. for (var index = 0; index < animations.length; index++) {
  11939. var animation = animations[index];
  11940. animation._target = target;
  11941. this._animations.push(animation);
  11942. }
  11943. };
  11944. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  11945. var animations = this._animations;
  11946. for (var index = 0; index < animations.length; index++) {
  11947. if (animations[index].targetProperty === property) {
  11948. return animations[index];
  11949. }
  11950. }
  11951. return null;
  11952. };
  11953. Animatable.prototype.pause = function () {
  11954. this._paused = true;
  11955. };
  11956. Animatable.prototype.restart = function () {
  11957. this._paused = false;
  11958. };
  11959. Animatable.prototype.stop = function () {
  11960. var index = this._scene._activeAnimatables.indexOf(this);
  11961. if (index > -1) {
  11962. this._scene._activeAnimatables.splice(index, 1);
  11963. }
  11964. if (this.onAnimationEnd) {
  11965. this.onAnimationEnd();
  11966. }
  11967. };
  11968. Animatable.prototype._animate = function (delay) {
  11969. if (this._paused) {
  11970. return true;
  11971. }
  11972. if (!this._localDelayOffset) {
  11973. this._localDelayOffset = delay;
  11974. }
  11975. var running = false;
  11976. var animations = this._animations;
  11977. for (var index = 0; index < animations.length; index++) {
  11978. var animation = animations[index];
  11979. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  11980. running = running || isRunning;
  11981. }
  11982. if (!running && this.onAnimationEnd) {
  11983. this.onAnimationEnd();
  11984. }
  11985. return running;
  11986. };
  11987. return Animatable;
  11988. })();
  11989. BABYLON.Animatable = Animatable;
  11990. })(BABYLON || (BABYLON = {}));
  11991. var BABYLON;
  11992. (function (BABYLON) {
  11993. var Octree = (function () {
  11994. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  11995. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  11996. this.maxDepth = maxDepth;
  11997. this.dynamicContent = new Array();
  11998. this._maxBlockCapacity = maxBlockCapacity || 64;
  11999. this._selectionContent = new BABYLON.SmartArray(1024);
  12000. this._creationFunc = creationFunc;
  12001. }
  12002. Octree.prototype.update = function (worldMin, worldMax, entries) {
  12003. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  12004. };
  12005. Octree.prototype.addMesh = function (entry) {
  12006. for (var index = 0; index < this.blocks.length; index++) {
  12007. var block = this.blocks[index];
  12008. block.addEntry(entry);
  12009. }
  12010. };
  12011. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  12012. this._selectionContent.reset();
  12013. for (var index = 0; index < this.blocks.length; index++) {
  12014. var block = this.blocks[index];
  12015. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  12016. }
  12017. if (allowDuplicate) {
  12018. this._selectionContent.concat(this.dynamicContent);
  12019. } else {
  12020. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  12021. }
  12022. return this._selectionContent;
  12023. };
  12024. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  12025. this._selectionContent.reset();
  12026. for (var index = 0; index < this.blocks.length; index++) {
  12027. var block = this.blocks[index];
  12028. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  12029. }
  12030. if (allowDuplicate) {
  12031. this._selectionContent.concat(this.dynamicContent);
  12032. } else {
  12033. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  12034. }
  12035. return this._selectionContent;
  12036. };
  12037. Octree.prototype.intersectsRay = function (ray) {
  12038. this._selectionContent.reset();
  12039. for (var index = 0; index < this.blocks.length; index++) {
  12040. var block = this.blocks[index];
  12041. block.intersectsRay(ray, this._selectionContent);
  12042. }
  12043. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  12044. return this._selectionContent;
  12045. };
  12046. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  12047. target.blocks = new Array();
  12048. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  12049. for (var x = 0; x < 2; x++) {
  12050. for (var y = 0; y < 2; y++) {
  12051. for (var z = 0; z < 2; z++) {
  12052. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  12053. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  12054. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  12055. block.addEntries(entries);
  12056. target.blocks.push(block);
  12057. }
  12058. }
  12059. }
  12060. };
  12061. Octree.CreationFuncForMeshes = function (entry, block) {
  12062. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  12063. block.entries.push(entry);
  12064. }
  12065. };
  12066. Octree.CreationFuncForSubMeshes = function (entry, block) {
  12067. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  12068. block.entries.push(entry);
  12069. }
  12070. };
  12071. return Octree;
  12072. })();
  12073. BABYLON.Octree = Octree;
  12074. })(BABYLON || (BABYLON = {}));
  12075. var BABYLON;
  12076. (function (BABYLON) {
  12077. var OctreeBlock = (function () {
  12078. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  12079. this.entries = new Array();
  12080. this._boundingVectors = new Array();
  12081. this._capacity = capacity;
  12082. this._depth = depth;
  12083. this._maxDepth = maxDepth;
  12084. this._creationFunc = creationFunc;
  12085. this._minPoint = minPoint;
  12086. this._maxPoint = maxPoint;
  12087. this._boundingVectors.push(minPoint.clone());
  12088. this._boundingVectors.push(maxPoint.clone());
  12089. this._boundingVectors.push(minPoint.clone());
  12090. this._boundingVectors[2].x = maxPoint.x;
  12091. this._boundingVectors.push(minPoint.clone());
  12092. this._boundingVectors[3].y = maxPoint.y;
  12093. this._boundingVectors.push(minPoint.clone());
  12094. this._boundingVectors[4].z = maxPoint.z;
  12095. this._boundingVectors.push(maxPoint.clone());
  12096. this._boundingVectors[5].z = minPoint.z;
  12097. this._boundingVectors.push(maxPoint.clone());
  12098. this._boundingVectors[6].x = minPoint.x;
  12099. this._boundingVectors.push(maxPoint.clone());
  12100. this._boundingVectors[7].y = minPoint.y;
  12101. }
  12102. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  12103. get: function () {
  12104. return this._capacity;
  12105. },
  12106. enumerable: true,
  12107. configurable: true
  12108. });
  12109. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  12110. get: function () {
  12111. return this._minPoint;
  12112. },
  12113. enumerable: true,
  12114. configurable: true
  12115. });
  12116. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  12117. get: function () {
  12118. return this._maxPoint;
  12119. },
  12120. enumerable: true,
  12121. configurable: true
  12122. });
  12123. OctreeBlock.prototype.addEntry = function (entry) {
  12124. if (this.blocks) {
  12125. for (var index = 0; index < this.blocks.length; index++) {
  12126. var block = this.blocks[index];
  12127. block.addEntry(entry);
  12128. }
  12129. return;
  12130. }
  12131. this._creationFunc(entry, this);
  12132. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  12133. this.createInnerBlocks();
  12134. }
  12135. };
  12136. OctreeBlock.prototype.addEntries = function (entries) {
  12137. for (var index = 0; index < entries.length; index++) {
  12138. var mesh = entries[index];
  12139. this.addEntry(mesh);
  12140. }
  12141. };
  12142. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  12143. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  12144. if (this.blocks) {
  12145. for (var index = 0; index < this.blocks.length; index++) {
  12146. var block = this.blocks[index];
  12147. block.select(frustumPlanes, selection, allowDuplicate);
  12148. }
  12149. return;
  12150. }
  12151. if (allowDuplicate) {
  12152. selection.concat(this.entries);
  12153. } else {
  12154. selection.concatWithNoDuplicate(this.entries);
  12155. }
  12156. }
  12157. };
  12158. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  12159. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  12160. if (this.blocks) {
  12161. for (var index = 0; index < this.blocks.length; index++) {
  12162. var block = this.blocks[index];
  12163. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  12164. }
  12165. return;
  12166. }
  12167. if (allowDuplicate) {
  12168. selection.concat(this.entries);
  12169. } else {
  12170. selection.concatWithNoDuplicate(this.entries);
  12171. }
  12172. }
  12173. };
  12174. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  12175. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  12176. if (this.blocks) {
  12177. for (var index = 0; index < this.blocks.length; index++) {
  12178. var block = this.blocks[index];
  12179. block.intersectsRay(ray, selection);
  12180. }
  12181. return;
  12182. }
  12183. selection.concatWithNoDuplicate(this.entries);
  12184. }
  12185. };
  12186. OctreeBlock.prototype.createInnerBlocks = function () {
  12187. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  12188. };
  12189. return OctreeBlock;
  12190. })();
  12191. BABYLON.OctreeBlock = OctreeBlock;
  12192. })(BABYLON || (BABYLON = {}));
  12193. var BABYLON;
  12194. (function (BABYLON) {
  12195. var Bone = (function () {
  12196. function Bone(name, skeleton, parentBone, matrix) {
  12197. this.name = name;
  12198. this.children = new Array();
  12199. this.animations = new Array();
  12200. this._worldTransform = new BABYLON.Matrix();
  12201. this._absoluteTransform = new BABYLON.Matrix();
  12202. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  12203. this._skeleton = skeleton;
  12204. this._matrix = matrix;
  12205. this._baseMatrix = matrix;
  12206. skeleton.bones.push(this);
  12207. if (parentBone) {
  12208. this._parent = parentBone;
  12209. parentBone.children.push(this);
  12210. } else {
  12211. this._parent = null;
  12212. }
  12213. this._updateDifferenceMatrix();
  12214. }
  12215. Bone.prototype.getParent = function () {
  12216. return this._parent;
  12217. };
  12218. Bone.prototype.getLocalMatrix = function () {
  12219. return this._matrix;
  12220. };
  12221. Bone.prototype.getBaseMatrix = function () {
  12222. return this._baseMatrix;
  12223. };
  12224. Bone.prototype.getWorldMatrix = function () {
  12225. return this._worldTransform;
  12226. };
  12227. Bone.prototype.getInvertedAbsoluteTransform = function () {
  12228. return this._invertedAbsoluteTransform;
  12229. };
  12230. Bone.prototype.getAbsoluteMatrix = function () {
  12231. var matrix = this._matrix.clone();
  12232. var parent = this._parent;
  12233. while (parent) {
  12234. matrix = matrix.multiply(parent.getLocalMatrix());
  12235. parent = parent.getParent();
  12236. }
  12237. return matrix;
  12238. };
  12239. Bone.prototype.updateMatrix = function (matrix) {
  12240. this._matrix = matrix;
  12241. this._skeleton._markAsDirty();
  12242. this._updateDifferenceMatrix();
  12243. };
  12244. Bone.prototype._updateDifferenceMatrix = function () {
  12245. if (this._parent) {
  12246. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  12247. } else {
  12248. this._absoluteTransform.copyFrom(this._matrix);
  12249. }
  12250. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  12251. for (var index = 0; index < this.children.length; index++) {
  12252. this.children[index]._updateDifferenceMatrix();
  12253. }
  12254. };
  12255. Bone.prototype.markAsDirty = function () {
  12256. this._skeleton._markAsDirty();
  12257. };
  12258. return Bone;
  12259. })();
  12260. BABYLON.Bone = Bone;
  12261. })(BABYLON || (BABYLON = {}));
  12262. var BABYLON;
  12263. (function (BABYLON) {
  12264. var Skeleton = (function () {
  12265. function Skeleton(name, id, scene) {
  12266. this.name = name;
  12267. this.id = id;
  12268. this.bones = new Array();
  12269. this._isDirty = true;
  12270. this._identity = BABYLON.Matrix.Identity();
  12271. this.bones = [];
  12272. this._scene = scene;
  12273. scene.skeletons.push(this);
  12274. }
  12275. Skeleton.prototype.getTransformMatrices = function () {
  12276. return this._transformMatrices;
  12277. };
  12278. Skeleton.prototype._markAsDirty = function () {
  12279. this._isDirty = true;
  12280. };
  12281. Skeleton.prototype.prepare = function () {
  12282. if (!this._isDirty) {
  12283. return;
  12284. }
  12285. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  12286. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  12287. }
  12288. for (var index = 0; index < this.bones.length; index++) {
  12289. var bone = this.bones[index];
  12290. var parentBone = bone.getParent();
  12291. if (parentBone) {
  12292. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  12293. } else {
  12294. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  12295. }
  12296. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  12297. }
  12298. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  12299. this._isDirty = false;
  12300. };
  12301. Skeleton.prototype.getAnimatables = function () {
  12302. if (!this._animatables || this._animatables.length != this.bones.length) {
  12303. this._animatables = [];
  12304. for (var index = 0; index < this.bones.length; index++) {
  12305. this._animatables.push(this.bones[index]);
  12306. }
  12307. }
  12308. return this._animatables;
  12309. };
  12310. Skeleton.prototype.clone = function (name, id) {
  12311. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  12312. for (var index = 0; index < this.bones.length; index++) {
  12313. var source = this.bones[index];
  12314. var parentBone = null;
  12315. if (source.getParent()) {
  12316. var parentIndex = this.bones.indexOf(source.getParent());
  12317. parentBone = result.bones[parentIndex];
  12318. }
  12319. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  12320. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  12321. }
  12322. return result;
  12323. };
  12324. return Skeleton;
  12325. })();
  12326. BABYLON.Skeleton = Skeleton;
  12327. })(BABYLON || (BABYLON = {}));
  12328. var BABYLON;
  12329. (function (BABYLON) {
  12330. var PostProcess = (function () {
  12331. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  12332. this.name = name;
  12333. this.width = -1;
  12334. this.height = -1;
  12335. this._reusable = false;
  12336. this._textures = new BABYLON.SmartArray(2);
  12337. this._currentRenderTextureInd = 0;
  12338. if (camera != null) {
  12339. this._camera = camera;
  12340. this._scene = camera.getScene();
  12341. camera.attachPostProcess(this);
  12342. this._engine = this._scene.getEngine();
  12343. } else {
  12344. this._engine = engine;
  12345. }
  12346. this._renderRatio = ratio;
  12347. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12348. this._reusable = reusable || false;
  12349. samplers = samplers || [];
  12350. samplers.push("textureSampler");
  12351. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  12352. }
  12353. PostProcess.prototype.isReusable = function () {
  12354. return this._reusable;
  12355. };
  12356. PostProcess.prototype.activate = function (camera, sourceTexture) {
  12357. camera = camera || this._camera;
  12358. var scene = camera.getScene();
  12359. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  12360. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  12361. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  12362. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  12363. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  12364. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  12365. if (this._textures.length > 0) {
  12366. for (var i = 0; i < this._textures.length; i++) {
  12367. this._engine._releaseTexture(this._textures.data[i]);
  12368. }
  12369. this._textures.reset();
  12370. }
  12371. this.width = desiredWidth;
  12372. this.height = desiredHeight;
  12373. 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 }));
  12374. if (this._reusable) {
  12375. 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 }));
  12376. }
  12377. if (this.onSizeChanged) {
  12378. this.onSizeChanged();
  12379. }
  12380. }
  12381. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  12382. if (this.onActivate) {
  12383. this.onActivate(camera);
  12384. }
  12385. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  12386. if (this._reusable) {
  12387. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  12388. }
  12389. };
  12390. PostProcess.prototype.apply = function () {
  12391. if (!this._effect.isReady())
  12392. return null;
  12393. this._engine.enableEffect(this._effect);
  12394. this._engine.setState(false);
  12395. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12396. this._engine.setDepthBuffer(false);
  12397. this._engine.setDepthWrite(false);
  12398. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  12399. if (this.onApply) {
  12400. this.onApply(this._effect);
  12401. }
  12402. return this._effect;
  12403. };
  12404. PostProcess.prototype.dispose = function (camera) {
  12405. camera = camera || this._camera;
  12406. if (this._textures.length > 0) {
  12407. for (var i = 0; i < this._textures.length; i++) {
  12408. this._engine._releaseTexture(this._textures.data[i]);
  12409. }
  12410. this._textures.reset();
  12411. }
  12412. camera.detachPostProcess(this);
  12413. var index = camera._postProcesses.indexOf(this);
  12414. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  12415. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1;
  12416. }
  12417. };
  12418. return PostProcess;
  12419. })();
  12420. BABYLON.PostProcess = PostProcess;
  12421. })(BABYLON || (BABYLON = {}));
  12422. var BABYLON;
  12423. (function (BABYLON) {
  12424. var PostProcessManager = (function () {
  12425. function PostProcessManager(scene) {
  12426. this._vertexDeclaration = [2];
  12427. this._vertexStrideSize = 2 * 4;
  12428. this._scene = scene;
  12429. var vertices = [];
  12430. vertices.push(1, 1);
  12431. vertices.push(-1, 1);
  12432. vertices.push(-1, -1);
  12433. vertices.push(1, -1);
  12434. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12435. var indices = [];
  12436. indices.push(0);
  12437. indices.push(1);
  12438. indices.push(2);
  12439. indices.push(0);
  12440. indices.push(2);
  12441. indices.push(3);
  12442. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12443. }
  12444. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  12445. var postProcesses = this._scene.activeCamera._postProcesses;
  12446. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12447. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12448. return false;
  12449. }
  12450. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  12451. return true;
  12452. };
  12453. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  12454. var postProcesses = this._scene.activeCamera._postProcesses;
  12455. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12456. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12457. return;
  12458. }
  12459. var engine = this._scene.getEngine();
  12460. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  12461. if (index < postProcessesTakenIndices.length - 1) {
  12462. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  12463. } else {
  12464. if (targetTexture) {
  12465. engine.bindFramebuffer(targetTexture);
  12466. } else {
  12467. engine.restoreDefaultFramebuffer();
  12468. }
  12469. }
  12470. if (doNotPresent) {
  12471. break;
  12472. }
  12473. var pp = postProcesses[postProcessesTakenIndices[index]];
  12474. var effect = pp.apply();
  12475. if (effect) {
  12476. if (pp.onBeforeRender) {
  12477. pp.onBeforeRender(effect);
  12478. }
  12479. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12480. engine.draw(true, 0, 6);
  12481. }
  12482. }
  12483. engine.setDepthBuffer(true);
  12484. engine.setDepthWrite(true);
  12485. };
  12486. PostProcessManager.prototype.dispose = function () {
  12487. if (this._vertexBuffer) {
  12488. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12489. this._vertexBuffer = null;
  12490. }
  12491. if (this._indexBuffer) {
  12492. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12493. this._indexBuffer = null;
  12494. }
  12495. };
  12496. return PostProcessManager;
  12497. })();
  12498. BABYLON.PostProcessManager = PostProcessManager;
  12499. })(BABYLON || (BABYLON = {}));
  12500. var __extends = this.__extends || function (d, b) {
  12501. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12502. function __() { this.constructor = d; }
  12503. __.prototype = b.prototype;
  12504. d.prototype = new __();
  12505. };
  12506. var BABYLON;
  12507. (function (BABYLON) {
  12508. var PassPostProcess = (function (_super) {
  12509. __extends(PassPostProcess, _super);
  12510. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12511. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  12512. }
  12513. return PassPostProcess;
  12514. })(BABYLON.PostProcess);
  12515. BABYLON.PassPostProcess = PassPostProcess;
  12516. })(BABYLON || (BABYLON = {}));
  12517. var __extends = this.__extends || function (d, b) {
  12518. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12519. function __() { this.constructor = d; }
  12520. __.prototype = b.prototype;
  12521. d.prototype = new __();
  12522. };
  12523. var BABYLON;
  12524. (function (BABYLON) {
  12525. var BlurPostProcess = (function (_super) {
  12526. __extends(BlurPostProcess, _super);
  12527. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  12528. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  12529. var _this = this;
  12530. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  12531. this.direction = direction;
  12532. this.blurWidth = blurWidth;
  12533. this.onApply = function (effect) {
  12534. effect.setFloat2("screenSize", _this.width, _this.height);
  12535. effect.setVector2("direction", _this.direction);
  12536. effect.setFloat("blurWidth", _this.blurWidth);
  12537. };
  12538. }
  12539. return BlurPostProcess;
  12540. })(BABYLON.PostProcess);
  12541. BABYLON.BlurPostProcess = BlurPostProcess;
  12542. })(BABYLON || (BABYLON = {}));
  12543. var __extends = this.__extends || function (d, b) {
  12544. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12545. function __() { this.constructor = d; }
  12546. __.prototype = b.prototype;
  12547. d.prototype = new __();
  12548. };
  12549. var BABYLON;
  12550. (function (BABYLON) {
  12551. var FilterPostProcess = (function (_super) {
  12552. __extends(FilterPostProcess, _super);
  12553. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  12554. var _this = this;
  12555. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  12556. this.kernelMatrix = kernelMatrix;
  12557. this.onApply = function (effect) {
  12558. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  12559. };
  12560. }
  12561. return FilterPostProcess;
  12562. })(BABYLON.PostProcess);
  12563. BABYLON.FilterPostProcess = FilterPostProcess;
  12564. })(BABYLON || (BABYLON = {}));
  12565. var __extends = this.__extends || function (d, b) {
  12566. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12567. function __() { this.constructor = d; }
  12568. __.prototype = b.prototype;
  12569. d.prototype = new __();
  12570. };
  12571. var BABYLON;
  12572. (function (BABYLON) {
  12573. var RefractionPostProcess = (function (_super) {
  12574. __extends(RefractionPostProcess, _super);
  12575. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  12576. var _this = this;
  12577. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  12578. this.color = color;
  12579. this.depth = depth;
  12580. this.colorLevel = colorLevel;
  12581. this.onActivate = function (cam) {
  12582. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  12583. };
  12584. this.onApply = function (effect) {
  12585. effect.setColor3("baseColor", _this.color);
  12586. effect.setFloat("depth", _this.depth);
  12587. effect.setFloat("colorLevel", _this.colorLevel);
  12588. effect.setTexture("refractionSampler", _this._refRexture);
  12589. };
  12590. }
  12591. RefractionPostProcess.prototype.dispose = function (camera) {
  12592. if (this._refRexture) {
  12593. this._refRexture.dispose();
  12594. }
  12595. _super.prototype.dispose.call(this, camera);
  12596. };
  12597. return RefractionPostProcess;
  12598. })(BABYLON.PostProcess);
  12599. BABYLON.RefractionPostProcess = RefractionPostProcess;
  12600. })(BABYLON || (BABYLON = {}));
  12601. var __extends = this.__extends || function (d, b) {
  12602. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12603. function __() { this.constructor = d; }
  12604. __.prototype = b.prototype;
  12605. d.prototype = new __();
  12606. };
  12607. var BABYLON;
  12608. (function (BABYLON) {
  12609. var BlackAndWhitePostProcess = (function (_super) {
  12610. __extends(BlackAndWhitePostProcess, _super);
  12611. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12612. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  12613. }
  12614. return BlackAndWhitePostProcess;
  12615. })(BABYLON.PostProcess);
  12616. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  12617. })(BABYLON || (BABYLON = {}));
  12618. var __extends = this.__extends || function (d, b) {
  12619. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12620. function __() { this.constructor = d; }
  12621. __.prototype = b.prototype;
  12622. d.prototype = new __();
  12623. };
  12624. var BABYLON;
  12625. (function (BABYLON) {
  12626. var ConvolutionPostProcess = (function (_super) {
  12627. __extends(ConvolutionPostProcess, _super);
  12628. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  12629. var _this = this;
  12630. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  12631. this.kernel = kernel;
  12632. this.onApply = function (effect) {
  12633. effect.setFloat2("screenSize", _this.width, _this.height);
  12634. effect.setArray("kernel", _this.kernel);
  12635. };
  12636. }
  12637. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  12638. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  12639. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  12640. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  12641. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  12642. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  12643. return ConvolutionPostProcess;
  12644. })(BABYLON.PostProcess);
  12645. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  12646. })(BABYLON || (BABYLON = {}));
  12647. var __extends = this.__extends || function (d, b) {
  12648. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12649. function __() { this.constructor = d; }
  12650. __.prototype = b.prototype;
  12651. d.prototype = new __();
  12652. };
  12653. var BABYLON;
  12654. (function (BABYLON) {
  12655. var FxaaPostProcess = (function (_super) {
  12656. __extends(FxaaPostProcess, _super);
  12657. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12658. var _this = this;
  12659. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  12660. this.onSizeChanged = function () {
  12661. _this.texelWidth = 1.0 / _this.width;
  12662. _this.texelHeight = 1.0 / _this.height;
  12663. };
  12664. this.onApply = function (effect) {
  12665. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  12666. };
  12667. }
  12668. return FxaaPostProcess;
  12669. })(BABYLON.PostProcess);
  12670. BABYLON.FxaaPostProcess = FxaaPostProcess;
  12671. })(BABYLON || (BABYLON = {}));
  12672. var BABYLON;
  12673. (function (BABYLON) {
  12674. var LensFlare = (function () {
  12675. function LensFlare(size, position, color, imgUrl, system) {
  12676. this.size = size;
  12677. this.position = position;
  12678. this.dispose = function () {
  12679. if (this.texture) {
  12680. this.texture.dispose();
  12681. }
  12682. var index = this._system.lensFlares.indexOf(this);
  12683. this._system.lensFlares.splice(index, 1);
  12684. };
  12685. this.color = color || new BABYLON.Color3(1, 1, 1);
  12686. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  12687. this._system = system;
  12688. system.lensFlares.push(this);
  12689. }
  12690. return LensFlare;
  12691. })();
  12692. BABYLON.LensFlare = LensFlare;
  12693. })(BABYLON || (BABYLON = {}));
  12694. var BABYLON;
  12695. (function (BABYLON) {
  12696. var LensFlareSystem = (function () {
  12697. function LensFlareSystem(name, emitter, scene) {
  12698. this.name = name;
  12699. this.lensFlares = new Array();
  12700. this.borderLimit = 300;
  12701. this._vertexDeclaration = [2];
  12702. this._vertexStrideSize = 2 * 4;
  12703. this._isEnabled = true;
  12704. this._scene = scene;
  12705. this._emitter = emitter;
  12706. scene.lensFlareSystems.push(this);
  12707. this.meshesSelectionPredicate = function (m) {
  12708. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  12709. };
  12710. var vertices = [];
  12711. vertices.push(1, 1);
  12712. vertices.push(-1, 1);
  12713. vertices.push(-1, -1);
  12714. vertices.push(1, -1);
  12715. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12716. var indices = [];
  12717. indices.push(0);
  12718. indices.push(1);
  12719. indices.push(2);
  12720. indices.push(0);
  12721. indices.push(2);
  12722. indices.push(3);
  12723. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12724. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  12725. }
  12726. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  12727. get: function () {
  12728. return this._isEnabled;
  12729. },
  12730. set: function (value) {
  12731. this._isEnabled = value;
  12732. },
  12733. enumerable: true,
  12734. configurable: true
  12735. });
  12736. LensFlareSystem.prototype.getScene = function () {
  12737. return this._scene;
  12738. };
  12739. LensFlareSystem.prototype.getEmitter = function () {
  12740. return this._emitter;
  12741. };
  12742. LensFlareSystem.prototype.getEmitterPosition = function () {
  12743. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  12744. };
  12745. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  12746. var position = this.getEmitterPosition();
  12747. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  12748. this._positionX = position.x;
  12749. this._positionY = position.y;
  12750. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  12751. if (position.z > 0) {
  12752. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  12753. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  12754. return true;
  12755. }
  12756. }
  12757. return false;
  12758. };
  12759. LensFlareSystem.prototype._isVisible = function () {
  12760. if (!this._isEnabled) {
  12761. return false;
  12762. }
  12763. var emitterPosition = this.getEmitterPosition();
  12764. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  12765. var distance = direction.length();
  12766. direction.normalize();
  12767. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  12768. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  12769. return !pickInfo.hit || pickInfo.distance > distance;
  12770. };
  12771. LensFlareSystem.prototype.render = function () {
  12772. if (!this._effect.isReady())
  12773. return false;
  12774. var engine = this._scene.getEngine();
  12775. var viewport = this._scene.activeCamera.viewport;
  12776. var globalViewport = viewport.toGlobal(engine);
  12777. if (!this.computeEffectivePosition(globalViewport)) {
  12778. return false;
  12779. }
  12780. if (!this._isVisible()) {
  12781. return false;
  12782. }
  12783. var awayX;
  12784. var awayY;
  12785. if (this._positionX < this.borderLimit + globalViewport.x) {
  12786. awayX = this.borderLimit + globalViewport.x - this._positionX;
  12787. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  12788. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  12789. } else {
  12790. awayX = 0;
  12791. }
  12792. if (this._positionY < this.borderLimit + globalViewport.y) {
  12793. awayY = this.borderLimit + globalViewport.y - this._positionY;
  12794. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  12795. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  12796. } else {
  12797. awayY = 0;
  12798. }
  12799. var away = (awayX > awayY) ? awayX : awayY;
  12800. if (away > this.borderLimit) {
  12801. away = this.borderLimit;
  12802. }
  12803. var intensity = 1.0 - (away / this.borderLimit);
  12804. if (intensity < 0) {
  12805. return false;
  12806. }
  12807. if (intensity > 1.0) {
  12808. intensity = 1.0;
  12809. }
  12810. var centerX = globalViewport.x + globalViewport.width / 2;
  12811. var centerY = globalViewport.y + globalViewport.height / 2;
  12812. var distX = centerX - this._positionX;
  12813. var distY = centerY - this._positionY;
  12814. engine.enableEffect(this._effect);
  12815. engine.setState(false);
  12816. engine.setDepthBuffer(false);
  12817. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  12818. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12819. for (var index = 0; index < this.lensFlares.length; index++) {
  12820. var flare = this.lensFlares[index];
  12821. var x = centerX - (distX * flare.position);
  12822. var y = centerY - (distY * flare.position);
  12823. var cw = flare.size;
  12824. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  12825. var cx = 2 * (x / globalViewport.width) - 1.0;
  12826. var cy = 1.0 - 2 * (y / globalViewport.height);
  12827. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  12828. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  12829. this._effect.setTexture("textureSampler", flare.texture);
  12830. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  12831. engine.draw(true, 0, 6);
  12832. }
  12833. engine.setDepthBuffer(true);
  12834. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12835. return true;
  12836. };
  12837. LensFlareSystem.prototype.dispose = function () {
  12838. if (this._vertexBuffer) {
  12839. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12840. this._vertexBuffer = null;
  12841. }
  12842. if (this._indexBuffer) {
  12843. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12844. this._indexBuffer = null;
  12845. }
  12846. while (this.lensFlares.length) {
  12847. this.lensFlares[0].dispose();
  12848. }
  12849. var index = this._scene.lensFlareSystems.indexOf(this);
  12850. this._scene.lensFlareSystems.splice(index, 1);
  12851. };
  12852. return LensFlareSystem;
  12853. })();
  12854. BABYLON.LensFlareSystem = LensFlareSystem;
  12855. })(BABYLON || (BABYLON = {}));
  12856. var BABYLON;
  12857. (function (BABYLON) {
  12858. var IntersectionInfo = (function () {
  12859. function IntersectionInfo(bu, bv, distance) {
  12860. this.bu = bu;
  12861. this.bv = bv;
  12862. this.distance = distance;
  12863. this.faceId = 0;
  12864. }
  12865. return IntersectionInfo;
  12866. })();
  12867. BABYLON.IntersectionInfo = IntersectionInfo;
  12868. var PickingInfo = (function () {
  12869. function PickingInfo() {
  12870. this.hit = false;
  12871. this.distance = 0;
  12872. this.pickedPoint = null;
  12873. this.pickedMesh = null;
  12874. this.bu = 0;
  12875. this.bv = 0;
  12876. this.faceId = -1;
  12877. }
  12878. PickingInfo.prototype.getNormal = function () {
  12879. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  12880. return null;
  12881. }
  12882. var indices = this.pickedMesh.getIndices();
  12883. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12884. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  12885. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  12886. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  12887. normal0 = normal0.scale(this.bu);
  12888. normal1 = normal1.scale(this.bv);
  12889. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  12890. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  12891. };
  12892. PickingInfo.prototype.getTextureCoordinates = function () {
  12893. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12894. return null;
  12895. }
  12896. var indices = this.pickedMesh.getIndices();
  12897. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  12898. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  12899. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  12900. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  12901. uv0 = uv0.scale(this.bu);
  12902. uv1 = uv1.scale(this.bv);
  12903. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  12904. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  12905. };
  12906. return PickingInfo;
  12907. })();
  12908. BABYLON.PickingInfo = PickingInfo;
  12909. })(BABYLON || (BABYLON = {}));
  12910. var BABYLON;
  12911. (function (BABYLON) {
  12912. var FilesInput = (function () {
  12913. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  12914. this.engine = p_engine;
  12915. this.canvas = p_canvas;
  12916. this.currentScene = p_scene;
  12917. this.sceneLoadedCallback = p_sceneLoadedCallback;
  12918. this.progressCallback = p_progressCallback;
  12919. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  12920. this.textureLoadingCallback = p_textureLoadingCallback;
  12921. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  12922. }
  12923. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  12924. var _this = this;
  12925. if (p_elementToMonitor) {
  12926. this.elementToMonitor = p_elementToMonitor;
  12927. this.elementToMonitor.addEventListener("dragenter", function (e) {
  12928. _this.drag(e);
  12929. }, false);
  12930. this.elementToMonitor.addEventListener("dragover", function (e) {
  12931. _this.drag(e);
  12932. }, false);
  12933. this.elementToMonitor.addEventListener("drop", function (e) {
  12934. _this.drop(e);
  12935. }, false);
  12936. }
  12937. };
  12938. FilesInput.prototype.renderFunction = function () {
  12939. if (this.additionnalRenderLoopLogicCallback) {
  12940. this.additionnalRenderLoopLogicCallback();
  12941. }
  12942. if (this.currentScene) {
  12943. if (this.textureLoadingCallback) {
  12944. var remaining = this.currentScene.getWaitingItemsCount();
  12945. if (remaining > 0) {
  12946. this.textureLoadingCallback(remaining);
  12947. }
  12948. }
  12949. this.currentScene.render();
  12950. }
  12951. };
  12952. FilesInput.prototype.drag = function (e) {
  12953. e.stopPropagation();
  12954. e.preventDefault();
  12955. };
  12956. FilesInput.prototype.drop = function (eventDrop) {
  12957. eventDrop.stopPropagation();
  12958. eventDrop.preventDefault();
  12959. this.loadFiles(eventDrop);
  12960. };
  12961. FilesInput.prototype.loadFiles = function (event) {
  12962. var _this = this;
  12963. var that = this;
  12964. if (this.startingProcessingFilesCallback)
  12965. this.startingProcessingFilesCallback();
  12966. var sceneFileToLoad;
  12967. var filesToLoad;
  12968. if (event && event.dataTransfer && event.dataTransfer.files) {
  12969. filesToLoad = event.dataTransfer.files;
  12970. }
  12971. if (event && event.target && event.target.files) {
  12972. filesToLoad = event.target.files;
  12973. }
  12974. if (filesToLoad && filesToLoad.length > 0) {
  12975. for (var i = 0; i < filesToLoad.length; i++) {
  12976. switch (filesToLoad[i].type) {
  12977. case "image/jpeg":
  12978. case "image/png":
  12979. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  12980. break;
  12981. case "image/targa":
  12982. case "image/vnd.ms-dds":
  12983. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  12984. break;
  12985. default:
  12986. 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) {
  12987. sceneFileToLoad = filesToLoad[i];
  12988. }
  12989. break;
  12990. }
  12991. }
  12992. if (sceneFileToLoad) {
  12993. if (this.currentScene) {
  12994. this.engine.stopRenderLoop();
  12995. this.currentScene.dispose();
  12996. }
  12997. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  12998. that.currentScene = newScene;
  12999. that.currentScene.executeWhenReady(function () {
  13000. if (that.currentScene.activeCamera) {
  13001. that.currentScene.activeCamera.attachControl(that.canvas);
  13002. }
  13003. if (that.sceneLoadedCallback) {
  13004. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  13005. }
  13006. that.engine.runRenderLoop(function () {
  13007. that.renderFunction();
  13008. });
  13009. });
  13010. }, function (progress) {
  13011. if (_this.progressCallback) {
  13012. _this.progressCallback(progress);
  13013. }
  13014. });
  13015. } else {
  13016. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  13017. }
  13018. }
  13019. };
  13020. FilesInput.FilesTextures = new Array();
  13021. FilesInput.FilesToLoad = new Array();
  13022. return FilesInput;
  13023. })();
  13024. BABYLON.FilesInput = FilesInput;
  13025. })(BABYLON || (BABYLON = {}));
  13026. var BABYLON;
  13027. (function (BABYLON) {
  13028. var OimoJSPlugin = (function () {
  13029. function OimoJSPlugin() {
  13030. this._registeredMeshes = [];
  13031. /**
  13032. * Update the body position according to the mesh position
  13033. * @param mesh
  13034. */
  13035. this.updateBodyPosition = function (mesh) {
  13036. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13037. var registeredMesh = this._registeredMeshes[index];
  13038. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13039. var body = registeredMesh.body.body;
  13040. mesh.computeWorldMatrix(true);
  13041. var center = mesh.getBoundingInfo().boundingBox.center;
  13042. body.setPosition(center.x, center.y, center.z);
  13043. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  13044. return;
  13045. }
  13046. if (registeredMesh.mesh.parent === mesh) {
  13047. mesh.computeWorldMatrix(true);
  13048. registeredMesh.mesh.computeWorldMatrix(true);
  13049. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  13050. var absoluteRotation = mesh.rotation;
  13051. body = registeredMesh.body.body;
  13052. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  13053. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  13054. return;
  13055. }
  13056. }
  13057. };
  13058. }
  13059. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  13060. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  13061. };
  13062. OimoJSPlugin.prototype.initialize = function (iterations) {
  13063. this._world = new OIMO.World();
  13064. this._world.clear();
  13065. };
  13066. OimoJSPlugin.prototype.setGravity = function (gravity) {
  13067. this._world.gravity = gravity;
  13068. };
  13069. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  13070. var body = null;
  13071. this.unregisterMesh(mesh);
  13072. mesh.computeWorldMatrix(true);
  13073. switch (impostor) {
  13074. case BABYLON.PhysicsEngine.SphereImpostor:
  13075. var bbox = mesh.getBoundingInfo().boundingBox;
  13076. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  13077. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  13078. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  13079. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  13080. var deltaPosition = mesh.position.subtract(bbox.center);
  13081. body = new OIMO.Body({
  13082. type: 'sphere',
  13083. size: [size],
  13084. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  13085. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  13086. move: options.mass != 0,
  13087. config: [options.mass, options.friction, options.restitution],
  13088. world: this._world
  13089. });
  13090. this._registeredMeshes.push({
  13091. mesh: mesh,
  13092. body: body,
  13093. delta: deltaPosition
  13094. });
  13095. break;
  13096. case BABYLON.PhysicsEngine.PlaneImpostor:
  13097. case BABYLON.PhysicsEngine.BoxImpostor:
  13098. bbox = mesh.getBoundingInfo().boundingBox;
  13099. var min = bbox.minimumWorld;
  13100. var max = bbox.maximumWorld;
  13101. var box = max.subtract(min);
  13102. var sizeX = this._checkWithEpsilon(box.x);
  13103. var sizeY = this._checkWithEpsilon(box.y);
  13104. var sizeZ = this._checkWithEpsilon(box.z);
  13105. var deltaPosition = mesh.position.subtract(bbox.center);
  13106. body = new OIMO.Body({
  13107. type: 'box',
  13108. size: [sizeX, sizeY, sizeZ],
  13109. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  13110. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  13111. move: options.mass != 0,
  13112. config: [options.mass, options.friction, options.restitution],
  13113. world: this._world
  13114. });
  13115. this._registeredMeshes.push({
  13116. mesh: mesh,
  13117. body: body,
  13118. delta: deltaPosition
  13119. });
  13120. break;
  13121. }
  13122. return body;
  13123. };
  13124. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  13125. var types = [], sizes = [], positions = [], rotations = [];
  13126. var initialMesh = parts[0].mesh;
  13127. for (var index = 0; index < parts.length; index++) {
  13128. var part = parts[index];
  13129. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  13130. types.push(bodyParameters.type);
  13131. sizes.push.apply(sizes, bodyParameters.size);
  13132. positions.push.apply(positions, bodyParameters.pos);
  13133. rotations.push.apply(rotations, bodyParameters.rot);
  13134. }
  13135. var body = new OIMO.Body({
  13136. type: types,
  13137. size: sizes,
  13138. pos: positions,
  13139. rot: rotations,
  13140. move: options.mass != 0,
  13141. config: [options.mass, options.friction, options.restitution],
  13142. world: this._world
  13143. });
  13144. this._registeredMeshes.push({
  13145. mesh: initialMesh,
  13146. body: body
  13147. });
  13148. return body;
  13149. };
  13150. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  13151. var bodyParameters = null;
  13152. var mesh = part.mesh;
  13153. switch (part.impostor) {
  13154. case BABYLON.PhysicsEngine.SphereImpostor:
  13155. var bbox = mesh.getBoundingInfo().boundingBox;
  13156. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  13157. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  13158. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  13159. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  13160. bodyParameters = {
  13161. type: 'sphere',
  13162. /* bug with oimo : sphere needs 3 sizes in this case */
  13163. size: [size, -1, -1],
  13164. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  13165. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  13166. };
  13167. break;
  13168. case BABYLON.PhysicsEngine.PlaneImpostor:
  13169. case BABYLON.PhysicsEngine.BoxImpostor:
  13170. bbox = mesh.getBoundingInfo().boundingBox;
  13171. var min = bbox.minimumWorld;
  13172. var max = bbox.maximumWorld;
  13173. var box = max.subtract(min);
  13174. var sizeX = this._checkWithEpsilon(box.x);
  13175. var sizeY = this._checkWithEpsilon(box.y);
  13176. var sizeZ = this._checkWithEpsilon(box.z);
  13177. var relativePosition = mesh.position;
  13178. bodyParameters = {
  13179. type: 'box',
  13180. size: [sizeX, sizeY, sizeZ],
  13181. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  13182. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  13183. };
  13184. break;
  13185. }
  13186. return bodyParameters;
  13187. };
  13188. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  13189. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13190. var registeredMesh = this._registeredMeshes[index];
  13191. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13192. if (registeredMesh.body) {
  13193. this._world.removeRigidBody(registeredMesh.body.body);
  13194. this._unbindBody(registeredMesh.body);
  13195. }
  13196. this._registeredMeshes.splice(index, 1);
  13197. return;
  13198. }
  13199. }
  13200. };
  13201. OimoJSPlugin.prototype._unbindBody = function (body) {
  13202. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13203. var registeredMesh = this._registeredMeshes[index];
  13204. if (registeredMesh.body === body) {
  13205. registeredMesh.body = null;
  13206. }
  13207. }
  13208. };
  13209. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  13210. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13211. var registeredMesh = this._registeredMeshes[index];
  13212. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13213. var mass = registeredMesh.body.body.massInfo.mass;
  13214. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  13215. return;
  13216. }
  13217. }
  13218. };
  13219. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13220. var body1 = null, body2 = null;
  13221. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13222. var registeredMesh = this._registeredMeshes[index];
  13223. if (registeredMesh.mesh === mesh1) {
  13224. body1 = registeredMesh.body.body;
  13225. } else if (registeredMesh.mesh === mesh2) {
  13226. body2 = registeredMesh.body.body;
  13227. }
  13228. }
  13229. if (!body1 || !body2) {
  13230. return false;
  13231. }
  13232. if (!options) {
  13233. options = {};
  13234. }
  13235. new OIMO.Link({
  13236. type: options.type,
  13237. body1: body1,
  13238. body2: body2,
  13239. min: options.min,
  13240. max: options.max,
  13241. axe1: options.axe1,
  13242. axe2: options.axe2,
  13243. pos1: [pivot1.x, pivot1.y, pivot1.z],
  13244. pos2: [pivot2.x, pivot2.y, pivot2.z],
  13245. collision: options.collision,
  13246. spring: options.spring,
  13247. world: this._world
  13248. });
  13249. return true;
  13250. };
  13251. OimoJSPlugin.prototype.dispose = function () {
  13252. this._world.clear();
  13253. while (this._registeredMeshes.length) {
  13254. this.unregisterMesh(this._registeredMeshes[0].mesh);
  13255. }
  13256. };
  13257. OimoJSPlugin.prototype.isSupported = function () {
  13258. return OIMO !== undefined;
  13259. };
  13260. OimoJSPlugin.prototype._getLastShape = function (body) {
  13261. var lastShape = body.shapes;
  13262. while (lastShape.next) {
  13263. lastShape = lastShape.next;
  13264. }
  13265. return lastShape;
  13266. };
  13267. OimoJSPlugin.prototype.runOneStep = function (time) {
  13268. this._world.step();
  13269. var i = this._registeredMeshes.length;
  13270. var m;
  13271. while (i--) {
  13272. var body = this._registeredMeshes[i].body.body;
  13273. var mesh = this._registeredMeshes[i].mesh;
  13274. var delta = this._registeredMeshes[i].delta;
  13275. if (!body.sleeping) {
  13276. if (body.shapes.next) {
  13277. var parentShape = this._getLastShape(body);
  13278. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  13279. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  13280. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  13281. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  13282. if (!mesh.rotationQuaternion) {
  13283. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13284. }
  13285. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13286. } else {
  13287. m = body.getMatrix();
  13288. mtx = BABYLON.Matrix.FromArray(m);
  13289. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  13290. if (!delta) {
  13291. mesh.position.x = bodyX;
  13292. mesh.position.y = bodyY;
  13293. mesh.position.z = bodyZ;
  13294. } else {
  13295. mesh.position.x = bodyX + delta.x;
  13296. mesh.position.y = bodyY + delta.y;
  13297. mesh.position.z = bodyZ + delta.z;
  13298. }
  13299. if (!mesh.rotationQuaternion) {
  13300. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13301. }
  13302. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13303. }
  13304. }
  13305. }
  13306. };
  13307. return OimoJSPlugin;
  13308. })();
  13309. BABYLON.OimoJSPlugin = OimoJSPlugin;
  13310. })(BABYLON || (BABYLON = {}));
  13311. var BABYLON;
  13312. (function (BABYLON) {
  13313. var PhysicsEngine = (function () {
  13314. function PhysicsEngine(plugin) {
  13315. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  13316. }
  13317. PhysicsEngine.prototype._initialize = function (gravity) {
  13318. this._currentPlugin.initialize();
  13319. this._setGravity(gravity);
  13320. };
  13321. PhysicsEngine.prototype._runOneStep = function (delta) {
  13322. if (delta > 0.1) {
  13323. delta = 0.1;
  13324. } else if (delta <= 0) {
  13325. delta = 1.0 / 60.0;
  13326. }
  13327. this._currentPlugin.runOneStep(delta);
  13328. };
  13329. PhysicsEngine.prototype._setGravity = function (gravity) {
  13330. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  13331. this._currentPlugin.setGravity(this.gravity);
  13332. };
  13333. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  13334. return this._currentPlugin.registerMesh(mesh, impostor, options);
  13335. };
  13336. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  13337. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  13338. };
  13339. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  13340. this._currentPlugin.unregisterMesh(mesh);
  13341. };
  13342. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  13343. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  13344. };
  13345. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13346. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  13347. };
  13348. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  13349. this._currentPlugin.updateBodyPosition(mesh);
  13350. };
  13351. PhysicsEngine.prototype.dispose = function () {
  13352. this._currentPlugin.dispose();
  13353. };
  13354. PhysicsEngine.prototype.isSupported = function () {
  13355. return this._currentPlugin.isSupported();
  13356. };
  13357. PhysicsEngine.NoImpostor = 0;
  13358. PhysicsEngine.SphereImpostor = 1;
  13359. PhysicsEngine.BoxImpostor = 2;
  13360. PhysicsEngine.PlaneImpostor = 3;
  13361. PhysicsEngine.MeshImpostor = 4;
  13362. PhysicsEngine.CapsuleImpostor = 5;
  13363. PhysicsEngine.ConeImpostor = 6;
  13364. PhysicsEngine.CylinderImpostor = 7;
  13365. PhysicsEngine.ConvexHullImpostor = 8;
  13366. PhysicsEngine.Epsilon = 0.001;
  13367. return PhysicsEngine;
  13368. })();
  13369. BABYLON.PhysicsEngine = PhysicsEngine;
  13370. })(BABYLON || (BABYLON = {}));
  13371. var BABYLON;
  13372. (function (BABYLON) {
  13373. var serializeLight = function (light) {
  13374. var serializationObject = {};
  13375. serializationObject.name = light.name;
  13376. serializationObject.id = light.id;
  13377. serializationObject.tags = BABYLON.Tags.GetTags(light);
  13378. if (light instanceof BABYLON.PointLight) {
  13379. serializationObject.type = 0;
  13380. serializationObject.position = light.position.asArray();
  13381. } else if (light instanceof BABYLON.DirectionalLight) {
  13382. serializationObject.type = 1;
  13383. var directionalLight = light;
  13384. serializationObject.position = directionalLight.position.asArray();
  13385. serializationObject.direction = directionalLight.direction.asArray();
  13386. } else if (light instanceof BABYLON.SpotLight) {
  13387. serializationObject.type = 2;
  13388. var spotLight = light;
  13389. serializationObject.position = spotLight.position.asArray();
  13390. serializationObject.direction = spotLight.position.asArray();
  13391. serializationObject.angle = spotLight.angle;
  13392. serializationObject.exponent = spotLight.exponent;
  13393. } else if (light instanceof BABYLON.HemisphericLight) {
  13394. serializationObject.type = 3;
  13395. var hemisphericLight = light;
  13396. serializationObject.direction = hemisphericLight.direction.asArray();
  13397. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  13398. }
  13399. if (light.intensity) {
  13400. serializationObject.intensity = light.intensity;
  13401. }
  13402. serializationObject.range = light.range;
  13403. serializationObject.diffuse = light.diffuse.asArray();
  13404. serializationObject.specular = light.specular.asArray();
  13405. return serializationObject;
  13406. };
  13407. var serializeFresnelParameter = function (fresnelParameter) {
  13408. var serializationObject = {};
  13409. serializationObject.isEnabled = fresnelParameter.isEnabled;
  13410. serializationObject.leftColor = fresnelParameter.leftColor;
  13411. serializationObject.rightColor = fresnelParameter.rightColor;
  13412. serializationObject.bias = fresnelParameter.bias;
  13413. serializationObject.power = fresnelParameter.power;
  13414. return serializationObject;
  13415. };
  13416. var serializeCamera = function (camera) {
  13417. var serializationObject = {};
  13418. serializationObject.name = camera.name;
  13419. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  13420. serializationObject.id = camera.id;
  13421. serializationObject.position = camera.position.asArray();
  13422. if (camera.parent) {
  13423. serializationObject.parentId = camera.parent.id;
  13424. }
  13425. serializationObject.rotation = camera.rotation.asArray();
  13426. if (camera.lockedTarget && camera.lockedTarget.id) {
  13427. serializationObject.lockedTargetId = camera.lockedTarget.id;
  13428. }
  13429. serializationObject.fov = camera.fov;
  13430. serializationObject.minZ = camera.minZ;
  13431. serializationObject.maxZ = camera.maxZ;
  13432. serializationObject.speed = camera.speed;
  13433. serializationObject.inertia = camera.inertia;
  13434. serializationObject.checkCollisions = camera.checkCollisions;
  13435. serializationObject.applyGravity = camera.applyGravity;
  13436. if (camera.ellipsoid) {
  13437. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  13438. }
  13439. appendAnimations(camera, serializationObject);
  13440. serializationObject.layerMask = camera.layerMask;
  13441. return serializationObject;
  13442. };
  13443. var appendAnimations = function (source, destination) {
  13444. if (source.animations) {
  13445. destination.animations = [];
  13446. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  13447. var animation = source.animations[animationIndex];
  13448. destination.animations.push(serializeAnimation(animation));
  13449. }
  13450. }
  13451. };
  13452. var serializeAnimation = function (animation) {
  13453. var serializationObject = {};
  13454. serializationObject.name = animation.name;
  13455. serializationObject.property = animation.targetProperty;
  13456. serializationObject.framePerSecond = animation.framePerSecond;
  13457. serializationObject.dataType = animation.dataType;
  13458. serializationObject.loopBehavior = animation.loopMode;
  13459. var dataType = animation.dataType;
  13460. serializationObject.keys = [];
  13461. var keys = animation.getKeys();
  13462. for (var index = 0; index < keys.length; index++) {
  13463. var animationKey = keys[index];
  13464. var key = {};
  13465. key.frame = animationKey.frame;
  13466. switch (dataType) {
  13467. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  13468. key.values = [animationKey.value];
  13469. break;
  13470. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  13471. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  13472. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  13473. key.values = animationKey.value.asArray();
  13474. break;
  13475. }
  13476. serializationObject.keys.push(key);
  13477. }
  13478. return serializationObject;
  13479. };
  13480. var serializeMultiMaterial = function (material) {
  13481. var serializationObject = {};
  13482. serializationObject.name = material.name;
  13483. serializationObject.id = material.id;
  13484. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13485. serializationObject.materials = [];
  13486. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  13487. var subMat = material.subMaterials[matIndex];
  13488. if (subMat) {
  13489. serializationObject.materials.push(subMat.id);
  13490. } else {
  13491. serializationObject.materials.push(null);
  13492. }
  13493. }
  13494. return serializationObject;
  13495. };
  13496. var serializeMaterial = function (material) {
  13497. var serializationObject = {};
  13498. serializationObject.name = material.name;
  13499. serializationObject.ambient = material.ambientColor.asArray();
  13500. serializationObject.diffuse = material.diffuseColor.asArray();
  13501. serializationObject.specular = material.specularColor.asArray();
  13502. serializationObject.specularPower = material.specularPower;
  13503. serializationObject.emissive = material.emissiveColor.asArray();
  13504. serializationObject.alpha = material.alpha;
  13505. serializationObject.id = material.id;
  13506. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13507. serializationObject.backFaceCulling = material.backFaceCulling;
  13508. if (material.diffuseTexture) {
  13509. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  13510. }
  13511. if (material.diffuseFresnelParameters) {
  13512. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  13513. }
  13514. if (material.ambientTexture) {
  13515. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  13516. }
  13517. if (material.opacityTexture) {
  13518. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  13519. }
  13520. if (material.opacityFresnelParameters) {
  13521. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  13522. }
  13523. if (material.reflectionTexture) {
  13524. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  13525. }
  13526. if (material.reflectionFresnelParameters) {
  13527. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  13528. }
  13529. if (material.emissiveTexture) {
  13530. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  13531. }
  13532. if (material.emissiveFresnelParameters) {
  13533. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  13534. }
  13535. if (material.specularTexture) {
  13536. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  13537. }
  13538. if (material.bumpTexture) {
  13539. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  13540. }
  13541. return serializationObject;
  13542. };
  13543. var serializeTexture = function (texture) {
  13544. var serializationObject = {};
  13545. if (!texture.name) {
  13546. return null;
  13547. }
  13548. if (texture instanceof BABYLON.CubeTexture) {
  13549. serializationObject.name = texture.name;
  13550. serializationObject.hasAlpha = texture.hasAlpha;
  13551. serializationObject.level = texture.level;
  13552. serializationObject.coordinatesMode = texture.coordinatesMode;
  13553. return serializationObject;
  13554. }
  13555. if (texture instanceof BABYLON.MirrorTexture) {
  13556. var mirrorTexture = texture;
  13557. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  13558. serializationObject.renderList = [];
  13559. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  13560. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  13561. }
  13562. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  13563. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  13564. var renderTargetTexture = texture;
  13565. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  13566. serializationObject.renderList = [];
  13567. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  13568. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  13569. }
  13570. }
  13571. var regularTexture = texture;
  13572. serializationObject.name = texture.name;
  13573. serializationObject.hasAlpha = texture.hasAlpha;
  13574. serializationObject.level = texture.level;
  13575. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  13576. serializationObject.coordinatesMode = texture.coordinatesMode;
  13577. serializationObject.uOffset = regularTexture.uOffset;
  13578. serializationObject.vOffset = regularTexture.vOffset;
  13579. serializationObject.uScale = regularTexture.uScale;
  13580. serializationObject.vScale = regularTexture.vScale;
  13581. serializationObject.uAng = regularTexture.uAng;
  13582. serializationObject.vAng = regularTexture.vAng;
  13583. serializationObject.wAng = regularTexture.wAng;
  13584. serializationObject.wrapU = texture.wrapU;
  13585. serializationObject.wrapV = texture.wrapV;
  13586. appendAnimations(texture, serializationObject);
  13587. return serializationObject;
  13588. };
  13589. var serializeSkeleton = function (skeleton) {
  13590. var serializationObject = {};
  13591. serializationObject.name = skeleton.name;
  13592. serializationObject.id = skeleton.id;
  13593. serializationObject.bones = [];
  13594. for (var index = 0; index < skeleton.bones.length; index++) {
  13595. var bone = skeleton.bones[index];
  13596. var serializedBone = {
  13597. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  13598. name: bone.name,
  13599. matrix: bone.getLocalMatrix().toArray()
  13600. };
  13601. serializationObject.bones.push(serializedBone);
  13602. if (bone.animations && bone.animations.length > 0) {
  13603. serializedBone.animation = serializeAnimation(bone.animations[0]);
  13604. }
  13605. }
  13606. return serializationObject;
  13607. };
  13608. var serializeParticleSystem = function (particleSystem) {
  13609. var serializationObject = {};
  13610. serializationObject.emitterId = particleSystem.emitter.id;
  13611. serializationObject.capacity = particleSystem.getCapacity();
  13612. if (particleSystem.particleTexture) {
  13613. serializationObject.textureName = particleSystem.particleTexture.name;
  13614. }
  13615. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  13616. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  13617. serializationObject.minSize = particleSystem.minSize;
  13618. serializationObject.maxSize = particleSystem.maxSize;
  13619. serializationObject.minLifeTime = particleSystem.minLifeTime;
  13620. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  13621. serializationObject.emitRate = particleSystem.emitRate;
  13622. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  13623. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  13624. serializationObject.gravity = particleSystem.gravity.asArray();
  13625. serializationObject.direction1 = particleSystem.direction1.asArray();
  13626. serializationObject.direction2 = particleSystem.direction2.asArray();
  13627. serializationObject.color1 = particleSystem.color1.asArray();
  13628. serializationObject.color2 = particleSystem.color2.asArray();
  13629. serializationObject.colorDead = particleSystem.colorDead.asArray();
  13630. serializationObject.updateSpeed = particleSystem.updateSpeed;
  13631. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  13632. serializationObject.textureMask = particleSystem.textureMask.asArray();
  13633. serializationObject.blendMode = particleSystem.blendMode;
  13634. return serializationObject;
  13635. };
  13636. var serializeLensFlareSystem = function (lensFlareSystem) {
  13637. var serializationObject = {};
  13638. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  13639. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  13640. serializationObject.flares = [];
  13641. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  13642. var flare = lensFlareSystem.lensFlares[index];
  13643. serializationObject.flares.push({
  13644. size: flare.size,
  13645. position: flare.position,
  13646. color: flare.color.asArray(),
  13647. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  13648. });
  13649. }
  13650. return serializationObject;
  13651. };
  13652. var serializeShadowGenerator = function (light) {
  13653. var serializationObject = {};
  13654. var shadowGenerator = light.getShadowGenerator();
  13655. serializationObject.lightId = light.id;
  13656. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  13657. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  13658. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  13659. serializationObject.renderList = [];
  13660. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  13661. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  13662. serializationObject.renderList.push(mesh.id);
  13663. }
  13664. return serializationObject;
  13665. };
  13666. var serializedGeometries = [];
  13667. var serializeGeometry = function (geometry, serializationGeometries) {
  13668. if (serializedGeometries[geometry.id]) {
  13669. return;
  13670. }
  13671. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  13672. serializationGeometries.boxes.push(serializeBox(geometry));
  13673. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  13674. serializationGeometries.spheres.push(serializeSphere(geometry));
  13675. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  13676. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  13677. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  13678. serializationGeometries.toruses.push(serializeTorus(geometry));
  13679. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  13680. serializationGeometries.grounds.push(serializeGround(geometry));
  13681. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  13682. serializationGeometries.planes.push(serializePlane(geometry));
  13683. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  13684. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  13685. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  13686. throw new Error("Unknow primitive type");
  13687. } else {
  13688. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  13689. }
  13690. serializedGeometries[geometry.id] = true;
  13691. };
  13692. var serializeGeometryBase = function (geometry) {
  13693. var serializationObject = {};
  13694. serializationObject.id = geometry.id;
  13695. if (BABYLON.Tags.HasTags(geometry)) {
  13696. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  13697. }
  13698. return serializationObject;
  13699. };
  13700. var serializeVertexData = function (vertexData) {
  13701. var serializationObject = serializeGeometryBase(vertexData);
  13702. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  13703. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13704. }
  13705. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13706. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13707. }
  13708. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13709. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  13710. }
  13711. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13712. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  13713. }
  13714. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13715. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  13716. }
  13717. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  13718. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  13719. serializationObject.matricesIndices._isExpanded = true;
  13720. }
  13721. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13722. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  13723. }
  13724. serializationObject.indices = vertexData.getIndices();
  13725. return serializationObject;
  13726. };
  13727. var serializePrimitive = function (primitive) {
  13728. var serializationObject = serializeGeometryBase(primitive);
  13729. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  13730. return serializationObject;
  13731. };
  13732. var serializeBox = function (box) {
  13733. var serializationObject = serializePrimitive(box);
  13734. serializationObject.size = box.size;
  13735. return serializationObject;
  13736. };
  13737. var serializeSphere = function (sphere) {
  13738. var serializationObject = serializePrimitive(sphere);
  13739. serializationObject.segments = sphere.segments;
  13740. serializationObject.diameter = sphere.diameter;
  13741. return serializationObject;
  13742. };
  13743. var serializeCylinder = function (cylinder) {
  13744. var serializationObject = serializePrimitive(cylinder);
  13745. serializationObject.height = cylinder.height;
  13746. serializationObject.diameterTop = cylinder.diameterTop;
  13747. serializationObject.diameterBottom = cylinder.diameterBottom;
  13748. serializationObject.tessellation = cylinder.tessellation;
  13749. return serializationObject;
  13750. };
  13751. var serializeTorus = function (torus) {
  13752. var serializationObject = serializePrimitive(torus);
  13753. serializationObject.diameter = torus.diameter;
  13754. serializationObject.thickness = torus.thickness;
  13755. serializationObject.tessellation = torus.tessellation;
  13756. return serializationObject;
  13757. };
  13758. var serializeGround = function (ground) {
  13759. var serializationObject = serializePrimitive(ground);
  13760. serializationObject.width = ground.width;
  13761. serializationObject.height = ground.height;
  13762. serializationObject.subdivisions = ground.subdivisions;
  13763. return serializationObject;
  13764. };
  13765. var serializePlane = function (plane) {
  13766. var serializationObject = serializePrimitive(plane);
  13767. serializationObject.size = plane.size;
  13768. return serializationObject;
  13769. };
  13770. var serializeTorusKnot = function (torusKnot) {
  13771. var serializationObject = serializePrimitive(torusKnot);
  13772. serializationObject.radius = torusKnot.radius;
  13773. serializationObject.tube = torusKnot.tube;
  13774. serializationObject.radialSegments = torusKnot.radialSegments;
  13775. serializationObject.tubularSegments = torusKnot.tubularSegments;
  13776. serializationObject.p = torusKnot.p;
  13777. serializationObject.q = torusKnot.q;
  13778. return serializationObject;
  13779. };
  13780. var serializeMesh = function (mesh, serializationScene) {
  13781. var serializationObject = {};
  13782. serializationObject.name = mesh.name;
  13783. serializationObject.id = mesh.id;
  13784. if (BABYLON.Tags.HasTags(mesh)) {
  13785. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  13786. }
  13787. serializationObject.position = mesh.position.asArray();
  13788. if (mesh.rotationQuaternion) {
  13789. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  13790. } else if (mesh.rotation) {
  13791. serializationObject.rotation = mesh.rotation.asArray();
  13792. }
  13793. serializationObject.scaling = mesh.scaling.asArray();
  13794. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  13795. serializationObject.isEnabled = mesh.isEnabled();
  13796. serializationObject.isVisible = mesh.isVisible;
  13797. serializationObject.infiniteDistance = mesh.infiniteDistance;
  13798. serializationObject.pickable = mesh.isPickable;
  13799. serializationObject.receiveShadows = mesh.receiveShadows;
  13800. serializationObject.billboardMode = mesh.billboardMode;
  13801. serializationObject.visibility = mesh.visibility;
  13802. serializationObject.checkCollisions = mesh.checkCollisions;
  13803. if (mesh.parent) {
  13804. serializationObject.parentId = mesh.parent.id;
  13805. }
  13806. var geometry = mesh._geometry;
  13807. if (geometry) {
  13808. var geometryId = geometry.id;
  13809. serializationObject.geometryId = geometryId;
  13810. if (!mesh.getScene().getGeometryByID(geometryId)) {
  13811. serializeGeometry(geometry, serializationScene.geometries);
  13812. }
  13813. serializationObject.subMeshes = [];
  13814. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  13815. var subMesh = mesh.subMeshes[subIndex];
  13816. serializationObject.subMeshes.push({
  13817. materialIndex: subMesh.materialIndex,
  13818. verticesStart: subMesh.verticesStart,
  13819. verticesCount: subMesh.verticesCount,
  13820. indexStart: subMesh.indexStart,
  13821. indexCount: subMesh.indexCount
  13822. });
  13823. }
  13824. }
  13825. if (mesh.material) {
  13826. serializationObject.materialId = mesh.material.id;
  13827. } else {
  13828. mesh.material = null;
  13829. }
  13830. if (mesh.skeleton) {
  13831. serializationObject.skeletonId = mesh.skeleton.id;
  13832. }
  13833. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  13834. serializationObject.physicsMass = mesh.getPhysicsMass();
  13835. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  13836. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  13837. switch (mesh.getPhysicsImpostor()) {
  13838. case BABYLON.PhysicsEngine.BoxImpostor:
  13839. serializationObject.physicsImpostor = 1;
  13840. break;
  13841. case BABYLON.PhysicsEngine.SphereImpostor:
  13842. serializationObject.physicsImpostor = 2;
  13843. break;
  13844. }
  13845. }
  13846. serializationObject.instances = [];
  13847. for (var index = 0; index < mesh.instances.length; index++) {
  13848. var instance = mesh.instances[index];
  13849. var serializationInstance = {
  13850. name: instance.name,
  13851. position: instance.position,
  13852. rotation: instance.rotation,
  13853. rotationQuaternion: instance.rotationQuaternion,
  13854. scaling: instance.scaling
  13855. };
  13856. serializationObject.instances.push(serializationInstance);
  13857. appendAnimations(instance, serializationInstance);
  13858. }
  13859. appendAnimations(mesh, serializationObject);
  13860. serializationObject.layerMask = mesh.layerMask;
  13861. return serializationObject;
  13862. };
  13863. var SceneSerializer = (function () {
  13864. function SceneSerializer() {
  13865. }
  13866. SceneSerializer.Serialize = function (scene) {
  13867. var serializationObject = {};
  13868. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  13869. serializationObject.autoClear = scene.autoClear;
  13870. serializationObject.clearColor = scene.clearColor.asArray();
  13871. serializationObject.ambientColor = scene.ambientColor.asArray();
  13872. serializationObject.gravity = scene.gravity.asArray();
  13873. if (scene.fogMode && scene.fogMode !== 0) {
  13874. serializationObject.fogMode = scene.fogMode;
  13875. serializationObject.fogColor = scene.fogColor.asArray();
  13876. serializationObject.fogStart = scene.fogStart;
  13877. serializationObject.fogEnd = scene.fogEnd;
  13878. serializationObject.fogDensity = scene.fogDensity;
  13879. }
  13880. serializationObject.lights = [];
  13881. for (var index = 0; index < scene.lights.length; index++) {
  13882. var light = scene.lights[index];
  13883. serializationObject.lights.push(serializeLight(light));
  13884. }
  13885. serializationObject.cameras = [];
  13886. for (index = 0; index < scene.cameras.length; index++) {
  13887. var camera = scene.cameras[index];
  13888. if (camera instanceof BABYLON.FreeCamera) {
  13889. serializationObject.cameras.push(serializeCamera(camera));
  13890. }
  13891. }
  13892. if (scene.activeCamera) {
  13893. serializationObject.activeCameraID = scene.activeCamera.id;
  13894. }
  13895. serializationObject.materials = [];
  13896. serializationObject.multiMaterials = [];
  13897. for (index = 0; index < scene.materials.length; index++) {
  13898. var material = scene.materials[index];
  13899. if (material instanceof BABYLON.StandardMaterial) {
  13900. serializationObject.materials.push(serializeMaterial(material));
  13901. } else if (material instanceof BABYLON.MultiMaterial) {
  13902. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  13903. }
  13904. }
  13905. serializationObject.skeletons = [];
  13906. for (index = 0; index < scene.skeletons.length; index++) {
  13907. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  13908. }
  13909. serializationObject.geometries = {};
  13910. serializationObject.geometries.boxes = [];
  13911. serializationObject.geometries.spheres = [];
  13912. serializationObject.geometries.cylinders = [];
  13913. serializationObject.geometries.toruses = [];
  13914. serializationObject.geometries.grounds = [];
  13915. serializationObject.geometries.planes = [];
  13916. serializationObject.geometries.torusKnots = [];
  13917. serializationObject.geometries.vertexData = [];
  13918. serializedGeometries = [];
  13919. var geometries = scene.getGeometries();
  13920. for (var index = 0; index < geometries.length; index++) {
  13921. var geometry = geometries[index];
  13922. if (geometry.isReady()) {
  13923. serializeGeometry(geometry, serializationObject.geometries);
  13924. }
  13925. }
  13926. serializationObject.meshes = [];
  13927. for (index = 0; index < scene.meshes.length; index++) {
  13928. var abstractMesh = scene.meshes[index];
  13929. if (abstractMesh instanceof BABYLON.Mesh) {
  13930. var mesh = abstractMesh;
  13931. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  13932. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  13933. }
  13934. }
  13935. }
  13936. serializationObject.particleSystems = [];
  13937. for (index = 0; index < scene.particleSystems.length; index++) {
  13938. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  13939. }
  13940. serializationObject.lensFlareSystems = [];
  13941. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  13942. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  13943. }
  13944. serializationObject.shadowGenerators = [];
  13945. for (index = 0; index < scene.lights.length; index++) {
  13946. light = scene.lights[index];
  13947. if (light.getShadowGenerator()) {
  13948. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  13949. }
  13950. }
  13951. return serializationObject;
  13952. };
  13953. return SceneSerializer;
  13954. })();
  13955. BABYLON.SceneSerializer = SceneSerializer;
  13956. })(BABYLON || (BABYLON = {}));
  13957. var BABYLON;
  13958. (function (BABYLON) {
  13959. var SceneLoader = (function () {
  13960. function SceneLoader() {
  13961. }
  13962. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  13963. get: function () {
  13964. return SceneLoader._ForceFullSceneLoadingForIncremental;
  13965. },
  13966. set: function (value) {
  13967. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  13968. },
  13969. enumerable: true,
  13970. configurable: true
  13971. });
  13972. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  13973. get: function () {
  13974. return SceneLoader._ShowLoadingScreen;
  13975. },
  13976. set: function (value) {
  13977. SceneLoader._ShowLoadingScreen = value;
  13978. },
  13979. enumerable: true,
  13980. configurable: true
  13981. });
  13982. SceneLoader._getPluginForFilename = function (sceneFilename) {
  13983. var dotPosition = sceneFilename.lastIndexOf(".");
  13984. var extension = sceneFilename.substring(dotPosition).toLowerCase();
  13985. for (var index = 0; index < this._registeredPlugins.length; index++) {
  13986. var plugin = this._registeredPlugins[index];
  13987. if (plugin.extensions.indexOf(extension) !== -1) {
  13988. return plugin;
  13989. }
  13990. }
  13991. return this._registeredPlugins[this._registeredPlugins.length - 1];
  13992. };
  13993. SceneLoader.RegisterPlugin = function (plugin) {
  13994. plugin.extensions = plugin.extensions.toLowerCase();
  13995. SceneLoader._registeredPlugins.push(plugin);
  13996. };
  13997. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  13998. var _this = this;
  13999. var manifestChecked = function (success) {
  14000. scene.database = database;
  14001. var plugin = _this._getPluginForFilename(sceneFilename);
  14002. var importMeshFromData = function (data) {
  14003. var meshes = [];
  14004. var particleSystems = [];
  14005. var skeletons = [];
  14006. try {
  14007. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  14008. if (onerror) {
  14009. onerror(scene);
  14010. }
  14011. return;
  14012. }
  14013. } catch (e) {
  14014. if (onerror) {
  14015. onerror(scene);
  14016. }
  14017. return;
  14018. }
  14019. if (onsuccess) {
  14020. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  14021. onsuccess(meshes, particleSystems, skeletons);
  14022. }
  14023. };
  14024. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  14025. importMeshFromData(sceneFilename.substr(5));
  14026. return;
  14027. }
  14028. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  14029. importMeshFromData(data);
  14030. }, progressCallBack, database);
  14031. };
  14032. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  14033. };
  14034. /**
  14035. * Load a scene
  14036. * @param rootUrl a string that defines the root url for scene and resources
  14037. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  14038. * @param engine is the instance of BABYLON.Engine to use to create the scene
  14039. */
  14040. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  14041. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  14042. };
  14043. /**
  14044. * Append a scene
  14045. * @param rootUrl a string that defines the root url for scene and resources
  14046. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  14047. * @param scene is the instance of BABYLON.Scene to append to
  14048. */
  14049. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  14050. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  14051. var database;
  14052. if (SceneLoader.ShowLoadingScreen) {
  14053. scene.getEngine().displayLoadingUI();
  14054. }
  14055. var loadSceneFromData = function (data) {
  14056. scene.database = database;
  14057. if (!plugin.load(scene, data, rootUrl)) {
  14058. if (onerror) {
  14059. onerror(scene);
  14060. }
  14061. scene.getEngine().hideLoadingUI();
  14062. return;
  14063. }
  14064. if (onsuccess) {
  14065. onsuccess(scene);
  14066. }
  14067. if (SceneLoader.ShowLoadingScreen) {
  14068. scene.executeWhenReady(function () {
  14069. scene.getEngine().hideLoadingUI();
  14070. });
  14071. }
  14072. };
  14073. var manifestChecked = function (success) {
  14074. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  14075. };
  14076. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  14077. loadSceneFromData(sceneFilename.substr(5));
  14078. return;
  14079. }
  14080. if (rootUrl.indexOf("file:") === -1) {
  14081. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  14082. } else {
  14083. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  14084. }
  14085. };
  14086. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  14087. SceneLoader._ShowLoadingScreen = true;
  14088. SceneLoader._registeredPlugins = new Array();
  14089. return SceneLoader;
  14090. })();
  14091. BABYLON.SceneLoader = SceneLoader;
  14092. ;
  14093. })(BABYLON || (BABYLON = {}));
  14094. var BABYLON;
  14095. (function (BABYLON) {
  14096. (function (Internals) {
  14097. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  14098. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  14099. texture.name = parsedTexture.name;
  14100. texture.hasAlpha = parsedTexture.hasAlpha;
  14101. texture.level = parsedTexture.level;
  14102. texture.coordinatesMode = parsedTexture.coordinatesMode;
  14103. return texture;
  14104. };
  14105. var loadTexture = function (rootUrl, parsedTexture, scene) {
  14106. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  14107. return null;
  14108. }
  14109. if (parsedTexture.isCube) {
  14110. return loadCubeTexture(rootUrl, parsedTexture, scene);
  14111. }
  14112. var texture;
  14113. if (parsedTexture.mirrorPlane) {
  14114. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  14115. texture._waitingRenderList = parsedTexture.renderList;
  14116. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  14117. } else if (parsedTexture.isRenderTarget) {
  14118. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  14119. texture._waitingRenderList = parsedTexture.renderList;
  14120. } else {
  14121. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  14122. }
  14123. texture.name = parsedTexture.name;
  14124. texture.hasAlpha = parsedTexture.hasAlpha;
  14125. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  14126. texture.level = parsedTexture.level;
  14127. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  14128. texture.coordinatesMode = parsedTexture.coordinatesMode;
  14129. texture.uOffset = parsedTexture.uOffset;
  14130. texture.vOffset = parsedTexture.vOffset;
  14131. texture.uScale = parsedTexture.uScale;
  14132. texture.vScale = parsedTexture.vScale;
  14133. texture.uAng = parsedTexture.uAng;
  14134. texture.vAng = parsedTexture.vAng;
  14135. texture.wAng = parsedTexture.wAng;
  14136. texture.wrapU = parsedTexture.wrapU;
  14137. texture.wrapV = parsedTexture.wrapV;
  14138. if (parsedTexture.animations) {
  14139. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  14140. var parsedAnimation = parsedTexture.animations[animationIndex];
  14141. texture.animations.push(parseAnimation(parsedAnimation));
  14142. }
  14143. }
  14144. return texture;
  14145. };
  14146. var parseSkeleton = function (parsedSkeleton, scene) {
  14147. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  14148. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  14149. var parsedBone = parsedSkeleton.bones[index];
  14150. var parentBone = null;
  14151. if (parsedBone.parentBoneIndex > -1) {
  14152. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  14153. }
  14154. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  14155. if (parsedBone.animation) {
  14156. bone.animations.push(parseAnimation(parsedBone.animation));
  14157. }
  14158. }
  14159. return skeleton;
  14160. };
  14161. var parseFresnelParameters = function (parsedFresnelParameters) {
  14162. var fresnelParameters = new BABYLON.FresnelParameters();
  14163. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  14164. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  14165. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  14166. fresnelParameters.bias = parsedFresnelParameters.bias;
  14167. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  14168. return fresnelParameters;
  14169. };
  14170. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  14171. var material;
  14172. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  14173. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  14174. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  14175. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  14176. material.specularPower = parsedMaterial.specularPower;
  14177. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  14178. material.alpha = parsedMaterial.alpha;
  14179. material.id = parsedMaterial.id;
  14180. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  14181. material.backFaceCulling = parsedMaterial.backFaceCulling;
  14182. material.wireframe = parsedMaterial.wireframe;
  14183. if (parsedMaterial.diffuseTexture) {
  14184. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  14185. }
  14186. if (parsedMaterial.diffuseFresnelParameters) {
  14187. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  14188. }
  14189. if (parsedMaterial.ambientTexture) {
  14190. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  14191. }
  14192. if (parsedMaterial.opacityTexture) {
  14193. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  14194. }
  14195. if (parsedMaterial.opacityFresnelParameters) {
  14196. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  14197. }
  14198. if (parsedMaterial.reflectionTexture) {
  14199. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  14200. }
  14201. if (parsedMaterial.reflectionFresnelParameters) {
  14202. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  14203. }
  14204. if (parsedMaterial.emissiveTexture) {
  14205. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  14206. }
  14207. if (parsedMaterial.emissiveFresnelParameters) {
  14208. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  14209. }
  14210. if (parsedMaterial.specularTexture) {
  14211. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  14212. }
  14213. if (parsedMaterial.bumpTexture) {
  14214. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  14215. }
  14216. return material;
  14217. };
  14218. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  14219. for (var index = 0; index < parsedData.materials.length; index++) {
  14220. var parsedMaterial = parsedData.materials[index];
  14221. if (parsedMaterial.id === id) {
  14222. return parseMaterial(parsedMaterial, scene, rootUrl);
  14223. }
  14224. }
  14225. return null;
  14226. };
  14227. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  14228. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  14229. multiMaterial.id = parsedMultiMaterial.id;
  14230. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  14231. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14232. var subMatId = parsedMultiMaterial.materials[matIndex];
  14233. if (subMatId) {
  14234. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  14235. } else {
  14236. multiMaterial.subMaterials.push(null);
  14237. }
  14238. }
  14239. return multiMaterial;
  14240. };
  14241. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  14242. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  14243. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  14244. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  14245. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  14246. var parsedFlare = parsedLensFlareSystem.flares[index];
  14247. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  14248. }
  14249. return lensFlareSystem;
  14250. };
  14251. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  14252. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  14253. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  14254. if (parsedParticleSystem.textureName) {
  14255. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  14256. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  14257. }
  14258. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  14259. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  14260. particleSystem.minSize = parsedParticleSystem.minSize;
  14261. particleSystem.maxSize = parsedParticleSystem.maxSize;
  14262. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  14263. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  14264. particleSystem.emitter = emitter;
  14265. particleSystem.emitRate = parsedParticleSystem.emitRate;
  14266. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  14267. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  14268. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  14269. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  14270. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  14271. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  14272. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  14273. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  14274. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  14275. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  14276. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  14277. particleSystem.blendMode = parsedParticleSystem.blendMode;
  14278. particleSystem.start();
  14279. return particleSystem;
  14280. };
  14281. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  14282. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  14283. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  14284. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  14285. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  14286. shadowGenerator.getShadowMap().renderList.push(mesh);
  14287. }
  14288. if (parsedShadowGenerator.usePoissonSampling) {
  14289. shadowGenerator.usePoissonSampling = true;
  14290. } else {
  14291. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  14292. }
  14293. return shadowGenerator;
  14294. };
  14295. var parseAnimation = function (parsedAnimation) {
  14296. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  14297. var dataType = parsedAnimation.dataType;
  14298. var keys = [];
  14299. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  14300. var key = parsedAnimation.keys[index];
  14301. var data;
  14302. switch (dataType) {
  14303. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  14304. data = key.values[0];
  14305. break;
  14306. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  14307. data = BABYLON.Quaternion.FromArray(key.values);
  14308. break;
  14309. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  14310. data = BABYLON.Matrix.FromArray(key.values);
  14311. break;
  14312. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  14313. default:
  14314. data = BABYLON.Vector3.FromArray(key.values);
  14315. break;
  14316. }
  14317. keys.push({
  14318. frame: key.frame,
  14319. value: data
  14320. });
  14321. }
  14322. animation.setKeys(keys);
  14323. return animation;
  14324. };
  14325. var parseLight = function (parsedLight, scene) {
  14326. var light;
  14327. switch (parsedLight.type) {
  14328. case 0:
  14329. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  14330. break;
  14331. case 1:
  14332. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14333. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  14334. break;
  14335. case 2:
  14336. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  14337. break;
  14338. case 3:
  14339. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14340. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  14341. break;
  14342. }
  14343. light.id = parsedLight.id;
  14344. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  14345. if (parsedLight.intensity !== undefined) {
  14346. light.intensity = parsedLight.intensity;
  14347. }
  14348. if (parsedLight.range) {
  14349. light.range = parsedLight.range;
  14350. }
  14351. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  14352. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  14353. if (parsedLight.excludedMeshesIds) {
  14354. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14355. }
  14356. if (parsedLight.includedOnlyMeshesIds) {
  14357. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14358. }
  14359. if (parsedLight.animations) {
  14360. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14361. var parsedAnimation = parsedLight.animations[animationIndex];
  14362. light.animations.push(parseAnimation(parsedAnimation));
  14363. }
  14364. }
  14365. if (parsedLight.autoAnimate) {
  14366. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  14367. }
  14368. };
  14369. var parseCamera = function (parsedCamera, scene) {
  14370. var camera;
  14371. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  14372. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  14373. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  14374. var alpha = parsedCamera.alpha;
  14375. var beta = parsedCamera.beta;
  14376. var radius = parsedCamera.radius;
  14377. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  14378. var eye_space = parsedCamera.eye_space;
  14379. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  14380. } else {
  14381. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  14382. }
  14383. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  14384. var eye_space = parsedCamera.eye_space;
  14385. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  14386. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  14387. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  14388. } else if (parsedCamera.type === "FollowCamera") {
  14389. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  14390. camera.heightOffset = parsedCamera.heightOffset;
  14391. camera.radius = parsedCamera.radius;
  14392. camera.rotationOffset = parsedCamera.rotationOffset;
  14393. if (lockedTargetMesh)
  14394. camera.target = lockedTargetMesh;
  14395. } else if (parsedCamera.type === "GamepadCamera") {
  14396. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  14397. } else if (parsedCamera.type === "OculusCamera") {
  14398. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  14399. } else if (parsedCamera.type === "TouchCamera") {
  14400. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  14401. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  14402. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  14403. } else if (parsedCamera.type === "WebVRCamera") {
  14404. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  14405. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  14406. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  14407. } else {
  14408. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  14409. }
  14410. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  14411. camera.lockedTarget = lockedTargetMesh;
  14412. }
  14413. camera.id = parsedCamera.id;
  14414. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  14415. if (parsedCamera.parentId) {
  14416. camera._waitingParentId = parsedCamera.parentId;
  14417. }
  14418. if (parsedCamera.target) {
  14419. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14420. } else {
  14421. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  14422. }
  14423. camera.fov = parsedCamera.fov;
  14424. camera.minZ = parsedCamera.minZ;
  14425. camera.maxZ = parsedCamera.maxZ;
  14426. camera.speed = parsedCamera.speed;
  14427. camera.inertia = parsedCamera.inertia;
  14428. camera.checkCollisions = parsedCamera.checkCollisions;
  14429. camera.applyGravity = parsedCamera.applyGravity;
  14430. if (parsedCamera.ellipsoid) {
  14431. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  14432. }
  14433. if (parsedCamera.animations) {
  14434. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14435. var parsedAnimation = parsedCamera.animations[animationIndex];
  14436. camera.animations.push(parseAnimation(parsedAnimation));
  14437. }
  14438. }
  14439. if (parsedCamera.autoAnimate) {
  14440. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  14441. }
  14442. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  14443. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  14444. } else {
  14445. camera.layerMask = 0xFFFFFFFF;
  14446. }
  14447. return camera;
  14448. };
  14449. var parseGeometry = function (parsedGeometry, scene) {
  14450. var id = parsedGeometry.id;
  14451. return scene.getGeometryByID(id);
  14452. };
  14453. var parseBox = function (parsedBox, scene) {
  14454. if (parseGeometry(parsedBox, scene)) {
  14455. return null;
  14456. }
  14457. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  14458. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  14459. scene.pushGeometry(box, true);
  14460. return box;
  14461. };
  14462. var parseSphere = function (parsedSphere, scene) {
  14463. if (parseGeometry(parsedSphere, scene)) {
  14464. return null;
  14465. }
  14466. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  14467. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  14468. scene.pushGeometry(sphere, true);
  14469. return sphere;
  14470. };
  14471. var parseCylinder = function (parsedCylinder, scene) {
  14472. if (parseGeometry(parsedCylinder, scene)) {
  14473. return null;
  14474. }
  14475. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  14476. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  14477. scene.pushGeometry(cylinder, true);
  14478. return cylinder;
  14479. };
  14480. var parseTorus = function (parsedTorus, scene) {
  14481. if (parseGeometry(parsedTorus, scene)) {
  14482. return null;
  14483. }
  14484. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  14485. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  14486. scene.pushGeometry(torus, true);
  14487. return torus;
  14488. };
  14489. var parseGround = function (parsedGround, scene) {
  14490. if (parseGeometry(parsedGround, scene)) {
  14491. return null;
  14492. }
  14493. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  14494. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  14495. scene.pushGeometry(ground, true);
  14496. return ground;
  14497. };
  14498. var parsePlane = function (parsedPlane, scene) {
  14499. if (parseGeometry(parsedPlane, scene)) {
  14500. return null;
  14501. }
  14502. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  14503. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  14504. scene.pushGeometry(plane, true);
  14505. return plane;
  14506. };
  14507. var parseTorusKnot = function (parsedTorusKnot, scene) {
  14508. if (parseGeometry(parsedTorusKnot, scene)) {
  14509. return null;
  14510. }
  14511. 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);
  14512. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  14513. scene.pushGeometry(torusKnot, true);
  14514. return torusKnot;
  14515. };
  14516. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  14517. if (parseGeometry(parsedVertexData, scene)) {
  14518. return null;
  14519. }
  14520. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  14521. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  14522. if (parsedVertexData.delayLoadingFile) {
  14523. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14524. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  14525. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  14526. geometry._delayInfo = [];
  14527. if (parsedVertexData.hasUVs) {
  14528. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  14529. }
  14530. if (parsedVertexData.hasUVs2) {
  14531. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  14532. }
  14533. if (parsedVertexData.hasColors) {
  14534. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  14535. }
  14536. if (parsedVertexData.hasMatricesIndices) {
  14537. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14538. }
  14539. if (parsedVertexData.hasMatricesWeights) {
  14540. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14541. }
  14542. geometry._delayLoadingFunction = importVertexData;
  14543. } else {
  14544. importVertexData(parsedVertexData, geometry);
  14545. }
  14546. scene.pushGeometry(geometry, true);
  14547. return geometry;
  14548. };
  14549. var parseMesh = function (parsedMesh, scene, rootUrl) {
  14550. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  14551. mesh.id = parsedMesh.id;
  14552. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  14553. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  14554. if (parsedMesh.rotationQuaternion) {
  14555. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  14556. } else if (parsedMesh.rotation) {
  14557. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  14558. }
  14559. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  14560. if (parsedMesh.localMatrix) {
  14561. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  14562. } else if (parsedMesh.pivotMatrix) {
  14563. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  14564. }
  14565. mesh.setEnabled(parsedMesh.isEnabled);
  14566. mesh.isVisible = parsedMesh.isVisible;
  14567. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  14568. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  14569. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  14570. if (parsedMesh.pickable !== undefined) {
  14571. mesh.isPickable = parsedMesh.pickable;
  14572. }
  14573. mesh.receiveShadows = parsedMesh.receiveShadows;
  14574. mesh.billboardMode = parsedMesh.billboardMode;
  14575. if (parsedMesh.visibility !== undefined) {
  14576. mesh.visibility = parsedMesh.visibility;
  14577. }
  14578. mesh.checkCollisions = parsedMesh.checkCollisions;
  14579. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  14580. if (parsedMesh.parentId) {
  14581. mesh._waitingParentId = parsedMesh.parentId;
  14582. }
  14583. if (parsedMesh.delayLoadingFile) {
  14584. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14585. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  14586. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  14587. if (parsedMesh._binaryInfo) {
  14588. mesh._binaryInfo = parsedMesh._binaryInfo;
  14589. }
  14590. mesh._delayInfo = [];
  14591. if (parsedMesh.hasUVs) {
  14592. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  14593. }
  14594. if (parsedMesh.hasUVs2) {
  14595. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  14596. }
  14597. if (parsedMesh.hasColors) {
  14598. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  14599. }
  14600. if (parsedMesh.hasMatricesIndices) {
  14601. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14602. }
  14603. if (parsedMesh.hasMatricesWeights) {
  14604. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14605. }
  14606. mesh._delayLoadingFunction = importGeometry;
  14607. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  14608. mesh._checkDelayState();
  14609. }
  14610. } else {
  14611. importGeometry(parsedMesh, mesh);
  14612. }
  14613. if (parsedMesh.materialId) {
  14614. mesh.setMaterialByID(parsedMesh.materialId);
  14615. } else {
  14616. mesh.material = null;
  14617. }
  14618. if (parsedMesh.skeletonId > -1) {
  14619. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  14620. }
  14621. if (parsedMesh.physicsImpostor) {
  14622. if (!scene.isPhysicsEnabled()) {
  14623. scene.enablePhysics();
  14624. }
  14625. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  14626. }
  14627. if (parsedMesh.animations) {
  14628. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  14629. var parsedAnimation = parsedMesh.animations[animationIndex];
  14630. mesh.animations.push(parseAnimation(parsedAnimation));
  14631. }
  14632. }
  14633. if (parsedMesh.autoAnimate) {
  14634. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  14635. }
  14636. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  14637. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  14638. } else {
  14639. mesh.layerMask = 0xFFFFFFFF;
  14640. }
  14641. if (parsedMesh.instances) {
  14642. for (var index = 0; index < parsedMesh.instances.length; index++) {
  14643. var parsedInstance = parsedMesh.instances[index];
  14644. var instance = mesh.createInstance(parsedInstance.name);
  14645. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  14646. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  14647. if (parsedInstance.rotationQuaternion) {
  14648. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  14649. } else if (parsedInstance.rotation) {
  14650. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  14651. }
  14652. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  14653. instance.checkCollisions = mesh.checkCollisions;
  14654. if (parsedMesh.animations) {
  14655. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  14656. parsedAnimation = parsedMesh.animations[animationIndex];
  14657. instance.animations.push(parseAnimation(parsedAnimation));
  14658. }
  14659. }
  14660. }
  14661. }
  14662. return mesh;
  14663. };
  14664. var isDescendantOf = function (mesh, names, hierarchyIds) {
  14665. names = (names instanceof Array) ? names : [names];
  14666. for (var i in names) {
  14667. if (mesh.name === names[i]) {
  14668. hierarchyIds.push(mesh.id);
  14669. return true;
  14670. }
  14671. }
  14672. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  14673. hierarchyIds.push(mesh.id);
  14674. return true;
  14675. }
  14676. return false;
  14677. };
  14678. var importVertexData = function (parsedVertexData, geometry) {
  14679. var vertexData = new BABYLON.VertexData();
  14680. var positions = parsedVertexData.positions;
  14681. if (positions) {
  14682. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  14683. }
  14684. var normals = parsedVertexData.normals;
  14685. if (normals) {
  14686. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  14687. }
  14688. var uvs = parsedVertexData.uvs;
  14689. if (uvs) {
  14690. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  14691. }
  14692. var uv2s = parsedVertexData.uv2s;
  14693. if (uv2s) {
  14694. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  14695. }
  14696. var colors = parsedVertexData.colors;
  14697. if (colors) {
  14698. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  14699. }
  14700. var matricesIndices = parsedVertexData.matricesIndices;
  14701. if (matricesIndices) {
  14702. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  14703. }
  14704. var matricesWeights = parsedVertexData.matricesWeights;
  14705. if (matricesWeights) {
  14706. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  14707. }
  14708. var indices = parsedVertexData.indices;
  14709. if (indices) {
  14710. vertexData.indices = indices;
  14711. }
  14712. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  14713. };
  14714. var importGeometry = function (parsedGeometry, mesh) {
  14715. var scene = mesh.getScene();
  14716. var geometryId = parsedGeometry.geometryId;
  14717. if (geometryId) {
  14718. var geometry = scene.getGeometryByID(geometryId);
  14719. if (geometry) {
  14720. geometry.applyToMesh(mesh);
  14721. }
  14722. } else if (parsedGeometry instanceof ArrayBuffer) {
  14723. var binaryInfo = mesh._binaryInfo;
  14724. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  14725. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  14726. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  14727. }
  14728. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  14729. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  14730. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  14731. }
  14732. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  14733. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  14734. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  14735. }
  14736. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  14737. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  14738. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  14739. }
  14740. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  14741. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  14742. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  14743. }
  14744. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  14745. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  14746. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  14747. }
  14748. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  14749. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  14750. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  14751. }
  14752. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  14753. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  14754. mesh.setIndices(indicesData);
  14755. }
  14756. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  14757. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  14758. mesh.subMeshes = [];
  14759. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  14760. var materialIndex = subMeshesData[(i * 5) + 0];
  14761. var verticesStart = subMeshesData[(i * 5) + 1];
  14762. var verticesCount = subMeshesData[(i * 5) + 2];
  14763. var indexStart = subMeshesData[(i * 5) + 3];
  14764. var indexCount = subMeshesData[(i * 5) + 4];
  14765. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  14766. }
  14767. }
  14768. return;
  14769. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  14770. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  14771. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  14772. if (parsedGeometry.uvs) {
  14773. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  14774. }
  14775. if (parsedGeometry.uvs2) {
  14776. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  14777. }
  14778. if (parsedGeometry.colors) {
  14779. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, parsedGeometry.colors, false);
  14780. }
  14781. if (parsedGeometry.matricesIndices) {
  14782. if (!parsedGeometry.matricesIndices._isExpanded) {
  14783. var floatIndices = [];
  14784. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  14785. var matricesIndex = parsedGeometry.matricesIndices[i];
  14786. floatIndices.push(matricesIndex & 0x000000FF);
  14787. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  14788. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  14789. floatIndices.push(matricesIndex >> 24);
  14790. }
  14791. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  14792. } else {
  14793. delete parsedGeometry.matricesIndices._isExpanded;
  14794. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  14795. }
  14796. }
  14797. if (parsedGeometry.matricesWeights) {
  14798. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  14799. }
  14800. mesh.setIndices(parsedGeometry.indices);
  14801. }
  14802. if (parsedGeometry.subMeshes) {
  14803. mesh.subMeshes = [];
  14804. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  14805. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  14806. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  14807. }
  14808. }
  14809. if (mesh._shouldGenerateFlatShading) {
  14810. mesh.convertToFlatShadedMesh();
  14811. delete mesh._shouldGenerateFlatShading;
  14812. }
  14813. mesh.computeWorldMatrix(true);
  14814. if (scene._selectionOctree) {
  14815. scene._selectionOctree.addMesh(mesh);
  14816. }
  14817. };
  14818. BABYLON.SceneLoader.RegisterPlugin({
  14819. extensions: ".babylon",
  14820. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  14821. var parsedData = JSON.parse(data);
  14822. var loadedSkeletonsIds = [];
  14823. var loadedMaterialsIds = [];
  14824. var hierarchyIds = [];
  14825. for (var index = 0; index < parsedData.meshes.length; index++) {
  14826. var parsedMesh = parsedData.meshes[index];
  14827. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  14828. if (meshesNames instanceof Array) {
  14829. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  14830. }
  14831. if (parsedMesh.materialId) {
  14832. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  14833. if (!materialFound) {
  14834. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  14835. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  14836. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  14837. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14838. var subMatId = parsedMultiMaterial.materials[matIndex];
  14839. loadedMaterialsIds.push(subMatId);
  14840. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  14841. }
  14842. loadedMaterialsIds.push(parsedMultiMaterial.id);
  14843. parseMultiMaterial(parsedMultiMaterial, scene);
  14844. materialFound = true;
  14845. break;
  14846. }
  14847. }
  14848. }
  14849. if (!materialFound) {
  14850. loadedMaterialsIds.push(parsedMesh.materialId);
  14851. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  14852. }
  14853. }
  14854. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  14855. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  14856. if (!skeletonAlreadyLoaded) {
  14857. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  14858. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  14859. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  14860. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  14861. loadedSkeletonsIds.push(parsedSkeleton.id);
  14862. }
  14863. }
  14864. }
  14865. }
  14866. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  14867. meshes.push(mesh);
  14868. }
  14869. }
  14870. for (index = 0; index < scene.meshes.length; index++) {
  14871. var currentMesh = scene.meshes[index];
  14872. if (currentMesh._waitingParentId) {
  14873. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  14874. currentMesh._waitingParentId = undefined;
  14875. }
  14876. }
  14877. if (parsedData.particleSystems) {
  14878. for (index = 0; index < parsedData.particleSystems.length; index++) {
  14879. var parsedParticleSystem = parsedData.particleSystems[index];
  14880. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  14881. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  14882. }
  14883. }
  14884. }
  14885. return true;
  14886. },
  14887. load: function (scene, data, rootUrl) {
  14888. var parsedData = JSON.parse(data);
  14889. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  14890. scene.autoClear = parsedData.autoClear;
  14891. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  14892. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  14893. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  14894. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  14895. scene.fogMode = parsedData.fogMode;
  14896. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  14897. scene.fogStart = parsedData.fogStart;
  14898. scene.fogEnd = parsedData.fogEnd;
  14899. scene.fogDensity = parsedData.fogDensity;
  14900. }
  14901. for (var index = 0; index < parsedData.lights.length; index++) {
  14902. var parsedLight = parsedData.lights[index];
  14903. parseLight(parsedLight, scene);
  14904. }
  14905. if (parsedData.materials) {
  14906. for (index = 0; index < parsedData.materials.length; index++) {
  14907. var parsedMaterial = parsedData.materials[index];
  14908. parseMaterial(parsedMaterial, scene, rootUrl);
  14909. }
  14910. }
  14911. if (parsedData.multiMaterials) {
  14912. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  14913. var parsedMultiMaterial = parsedData.multiMaterials[index];
  14914. parseMultiMaterial(parsedMultiMaterial, scene);
  14915. }
  14916. }
  14917. if (parsedData.skeletons) {
  14918. for (index = 0; index < parsedData.skeletons.length; index++) {
  14919. var parsedSkeleton = parsedData.skeletons[index];
  14920. parseSkeleton(parsedSkeleton, scene);
  14921. }
  14922. }
  14923. var geometries = parsedData.geometries;
  14924. if (geometries) {
  14925. var boxes = geometries.boxes;
  14926. if (boxes) {
  14927. for (index = 0; index < boxes.length; index++) {
  14928. var parsedBox = boxes[index];
  14929. parseBox(parsedBox, scene);
  14930. }
  14931. }
  14932. var spheres = geometries.spheres;
  14933. if (spheres) {
  14934. for (index = 0; index < spheres.length; index++) {
  14935. var parsedSphere = spheres[index];
  14936. parseSphere(parsedSphere, scene);
  14937. }
  14938. }
  14939. var cylinders = geometries.cylinders;
  14940. if (cylinders) {
  14941. for (index = 0; index < cylinders.length; index++) {
  14942. var parsedCylinder = cylinders[index];
  14943. parseCylinder(parsedCylinder, scene);
  14944. }
  14945. }
  14946. var toruses = geometries.toruses;
  14947. if (toruses) {
  14948. for (index = 0; index < toruses.length; index++) {
  14949. var parsedTorus = toruses[index];
  14950. parseTorus(parsedTorus, scene);
  14951. }
  14952. }
  14953. var grounds = geometries.grounds;
  14954. if (grounds) {
  14955. for (index = 0; index < grounds.length; index++) {
  14956. var parsedGround = grounds[index];
  14957. parseGround(parsedGround, scene);
  14958. }
  14959. }
  14960. var planes = geometries.planes;
  14961. if (planes) {
  14962. for (index = 0; index < planes.length; index++) {
  14963. var parsedPlane = planes[index];
  14964. parsePlane(parsedPlane, scene);
  14965. }
  14966. }
  14967. var torusKnots = geometries.torusKnots;
  14968. if (torusKnots) {
  14969. for (index = 0; index < torusKnots.length; index++) {
  14970. var parsedTorusKnot = torusKnots[index];
  14971. parseTorusKnot(parsedTorusKnot, scene);
  14972. }
  14973. }
  14974. var vertexData = geometries.vertexData;
  14975. if (vertexData) {
  14976. for (index = 0; index < vertexData.length; index++) {
  14977. var parsedVertexData = vertexData[index];
  14978. parseVertexData(parsedVertexData, scene, rootUrl);
  14979. }
  14980. }
  14981. }
  14982. for (index = 0; index < parsedData.meshes.length; index++) {
  14983. var parsedMesh = parsedData.meshes[index];
  14984. parseMesh(parsedMesh, scene, rootUrl);
  14985. }
  14986. for (index = 0; index < parsedData.cameras.length; index++) {
  14987. var parsedCamera = parsedData.cameras[index];
  14988. parseCamera(parsedCamera, scene);
  14989. }
  14990. if (parsedData.activeCameraID) {
  14991. scene.setActiveCameraByID(parsedData.activeCameraID);
  14992. }
  14993. for (index = 0; index < scene.cameras.length; index++) {
  14994. var camera = scene.cameras[index];
  14995. if (camera._waitingParentId) {
  14996. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  14997. camera._waitingParentId = undefined;
  14998. }
  14999. }
  15000. for (index = 0; index < scene.meshes.length; index++) {
  15001. var mesh = scene.meshes[index];
  15002. if (mesh._waitingParentId) {
  15003. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  15004. mesh._waitingParentId = undefined;
  15005. }
  15006. }
  15007. if (parsedData.particleSystems) {
  15008. for (index = 0; index < parsedData.particleSystems.length; index++) {
  15009. var parsedParticleSystem = parsedData.particleSystems[index];
  15010. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  15011. }
  15012. }
  15013. if (parsedData.lensFlareSystems) {
  15014. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  15015. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  15016. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  15017. }
  15018. }
  15019. if (parsedData.shadowGenerators) {
  15020. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  15021. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  15022. parseShadowGenerator(parsedShadowGenerator, scene);
  15023. }
  15024. }
  15025. return true;
  15026. }
  15027. });
  15028. })(BABYLON.Internals || (BABYLON.Internals = {}));
  15029. var Internals = BABYLON.Internals;
  15030. })(BABYLON || (BABYLON = {}));
  15031. var BABYLON;
  15032. (function (BABYLON) {
  15033. var currentCSGMeshId = 0;
  15034. var Vertex = (function () {
  15035. function Vertex(pos, normal, uv) {
  15036. this.pos = pos;
  15037. this.normal = normal;
  15038. this.uv = uv;
  15039. }
  15040. Vertex.prototype.clone = function () {
  15041. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  15042. };
  15043. Vertex.prototype.flip = function () {
  15044. this.normal = this.normal.scale(-1);
  15045. };
  15046. Vertex.prototype.interpolate = function (other, t) {
  15047. 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));
  15048. };
  15049. return Vertex;
  15050. })();
  15051. var Plane = (function () {
  15052. function Plane(normal, w) {
  15053. this.normal = normal;
  15054. this.w = w;
  15055. }
  15056. Plane.FromPoints = function (a, b, c) {
  15057. var v0 = c.subtract(a);
  15058. var v1 = b.subtract(a);
  15059. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  15060. return null;
  15061. }
  15062. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  15063. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  15064. };
  15065. Plane.prototype.clone = function () {
  15066. return new Plane(this.normal.clone(), this.w);
  15067. };
  15068. Plane.prototype.flip = function () {
  15069. this.normal.scaleInPlace(-1);
  15070. this.w = -this.w;
  15071. };
  15072. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  15073. var COPLANAR = 0;
  15074. var FRONT = 1;
  15075. var BACK = 2;
  15076. var SPANNING = 3;
  15077. var polygonType = 0;
  15078. var types = [];
  15079. for (var i = 0; i < polygon.vertices.length; i++) {
  15080. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  15081. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  15082. polygonType |= type;
  15083. types.push(type);
  15084. }
  15085. switch (polygonType) {
  15086. case COPLANAR:
  15087. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  15088. break;
  15089. case FRONT:
  15090. front.push(polygon);
  15091. break;
  15092. case BACK:
  15093. back.push(polygon);
  15094. break;
  15095. case SPANNING:
  15096. var f = [], b = [];
  15097. for (i = 0; i < polygon.vertices.length; i++) {
  15098. var j = (i + 1) % polygon.vertices.length;
  15099. var ti = types[i], tj = types[j];
  15100. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  15101. if (ti != BACK)
  15102. f.push(vi);
  15103. if (ti != FRONT)
  15104. b.push(ti != BACK ? vi.clone() : vi);
  15105. if ((ti | tj) == SPANNING) {
  15106. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  15107. var v = vi.interpolate(vj, t);
  15108. f.push(v);
  15109. b.push(v.clone());
  15110. }
  15111. }
  15112. if (f.length >= 3) {
  15113. var poly = new Polygon(f, polygon.shared);
  15114. if (poly.plane)
  15115. front.push(poly);
  15116. }
  15117. if (b.length >= 3) {
  15118. poly = new Polygon(b, polygon.shared);
  15119. if (poly.plane)
  15120. back.push(poly);
  15121. }
  15122. break;
  15123. }
  15124. };
  15125. Plane.EPSILON = 1e-5;
  15126. return Plane;
  15127. })();
  15128. var Polygon = (function () {
  15129. function Polygon(vertices, shared) {
  15130. this.vertices = vertices;
  15131. this.shared = shared;
  15132. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  15133. }
  15134. Polygon.prototype.clone = function () {
  15135. var vertices = this.vertices.map(function (v) {
  15136. return v.clone();
  15137. });
  15138. return new Polygon(vertices, this.shared);
  15139. };
  15140. Polygon.prototype.flip = function () {
  15141. this.vertices.reverse().map(function (v) {
  15142. v.flip();
  15143. });
  15144. this.plane.flip();
  15145. };
  15146. return Polygon;
  15147. })();
  15148. var Node = (function () {
  15149. function Node(polygons) {
  15150. this.plane = null;
  15151. this.front = null;
  15152. this.back = null;
  15153. this.polygons = [];
  15154. if (polygons) {
  15155. this.build(polygons);
  15156. }
  15157. }
  15158. Node.prototype.clone = function () {
  15159. var node = new Node();
  15160. node.plane = this.plane && this.plane.clone();
  15161. node.front = this.front && this.front.clone();
  15162. node.back = this.back && this.back.clone();
  15163. node.polygons = this.polygons.map(function (p) {
  15164. return p.clone();
  15165. });
  15166. return node;
  15167. };
  15168. Node.prototype.invert = function () {
  15169. for (var i = 0; i < this.polygons.length; i++) {
  15170. this.polygons[i].flip();
  15171. }
  15172. if (this.plane) {
  15173. this.plane.flip();
  15174. }
  15175. if (this.front) {
  15176. this.front.invert();
  15177. }
  15178. if (this.back) {
  15179. this.back.invert();
  15180. }
  15181. var temp = this.front;
  15182. this.front = this.back;
  15183. this.back = temp;
  15184. };
  15185. Node.prototype.clipPolygons = function (polygons) {
  15186. if (!this.plane)
  15187. return polygons.slice();
  15188. var front = [], back = [];
  15189. for (var i = 0; i < polygons.length; i++) {
  15190. this.plane.splitPolygon(polygons[i], front, back, front, back);
  15191. }
  15192. if (this.front) {
  15193. front = this.front.clipPolygons(front);
  15194. }
  15195. if (this.back) {
  15196. back = this.back.clipPolygons(back);
  15197. } else {
  15198. back = [];
  15199. }
  15200. return front.concat(back);
  15201. };
  15202. Node.prototype.clipTo = function (bsp) {
  15203. this.polygons = bsp.clipPolygons(this.polygons);
  15204. if (this.front)
  15205. this.front.clipTo(bsp);
  15206. if (this.back)
  15207. this.back.clipTo(bsp);
  15208. };
  15209. Node.prototype.allPolygons = function () {
  15210. var polygons = this.polygons.slice();
  15211. if (this.front)
  15212. polygons = polygons.concat(this.front.allPolygons());
  15213. if (this.back)
  15214. polygons = polygons.concat(this.back.allPolygons());
  15215. return polygons;
  15216. };
  15217. Node.prototype.build = function (polygons) {
  15218. if (!polygons.length)
  15219. return;
  15220. if (!this.plane)
  15221. this.plane = polygons[0].plane.clone();
  15222. var front = [], back = [];
  15223. for (var i = 0; i < polygons.length; i++) {
  15224. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  15225. }
  15226. if (front.length) {
  15227. if (!this.front)
  15228. this.front = new Node();
  15229. this.front.build(front);
  15230. }
  15231. if (back.length) {
  15232. if (!this.back)
  15233. this.back = new Node();
  15234. this.back.build(back);
  15235. }
  15236. };
  15237. return Node;
  15238. })();
  15239. var CSG = (function () {
  15240. function CSG() {
  15241. this.polygons = new Array();
  15242. }
  15243. CSG.FromMesh = function (mesh) {
  15244. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  15245. if (mesh instanceof BABYLON.Mesh) {
  15246. mesh.computeWorldMatrix(true);
  15247. var matrix = mesh.getWorldMatrix();
  15248. var meshPosition = mesh.position.clone();
  15249. var meshRotation = mesh.rotation.clone();
  15250. var meshScaling = mesh.scaling.clone();
  15251. } else {
  15252. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  15253. }
  15254. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15255. var subMeshes = mesh.subMeshes;
  15256. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  15257. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  15258. vertices = [];
  15259. for (var j = 0; j < 3; j++) {
  15260. normal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  15261. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  15262. position = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  15263. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, position);
  15264. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  15265. vertex = new Vertex(position, normal, uv);
  15266. vertices.push(vertex);
  15267. }
  15268. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  15269. if (polygon.plane)
  15270. polygons.push(polygon);
  15271. }
  15272. }
  15273. var csg = CSG.FromPolygons(polygons);
  15274. csg.matrix = matrix;
  15275. csg.position = meshPosition;
  15276. csg.rotation = meshRotation;
  15277. csg.scaling = meshScaling;
  15278. currentCSGMeshId++;
  15279. return csg;
  15280. };
  15281. CSG.FromPolygons = function (polygons) {
  15282. var csg = new BABYLON.CSG();
  15283. csg.polygons = polygons;
  15284. return csg;
  15285. };
  15286. CSG.prototype.clone = function () {
  15287. var csg = new BABYLON.CSG();
  15288. csg.polygons = this.polygons.map(function (p) {
  15289. return p.clone();
  15290. });
  15291. csg.copyTransformAttributes(this);
  15292. return csg;
  15293. };
  15294. CSG.prototype.toPolygons = function () {
  15295. return this.polygons;
  15296. };
  15297. CSG.prototype.union = function (csg) {
  15298. var a = new Node(this.clone().polygons);
  15299. var b = new Node(csg.clone().polygons);
  15300. a.clipTo(b);
  15301. b.clipTo(a);
  15302. b.invert();
  15303. b.clipTo(a);
  15304. b.invert();
  15305. a.build(b.allPolygons());
  15306. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15307. };
  15308. CSG.prototype.unionInPlace = function (csg) {
  15309. var a = new Node(this.polygons);
  15310. var b = new Node(csg.polygons);
  15311. a.clipTo(b);
  15312. b.clipTo(a);
  15313. b.invert();
  15314. b.clipTo(a);
  15315. b.invert();
  15316. a.build(b.allPolygons());
  15317. this.polygons = a.allPolygons();
  15318. };
  15319. CSG.prototype.subtract = function (csg) {
  15320. var a = new Node(this.clone().polygons);
  15321. var b = new Node(csg.clone().polygons);
  15322. a.invert();
  15323. a.clipTo(b);
  15324. b.clipTo(a);
  15325. b.invert();
  15326. b.clipTo(a);
  15327. b.invert();
  15328. a.build(b.allPolygons());
  15329. a.invert();
  15330. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15331. };
  15332. CSG.prototype.subtractInPlace = function (csg) {
  15333. var a = new Node(this.polygons);
  15334. var b = new Node(csg.polygons);
  15335. a.invert();
  15336. a.clipTo(b);
  15337. b.clipTo(a);
  15338. b.invert();
  15339. b.clipTo(a);
  15340. b.invert();
  15341. a.build(b.allPolygons());
  15342. a.invert();
  15343. this.polygons = a.allPolygons();
  15344. };
  15345. CSG.prototype.intersect = function (csg) {
  15346. var a = new Node(this.clone().polygons);
  15347. var b = new Node(csg.clone().polygons);
  15348. a.invert();
  15349. b.clipTo(a);
  15350. b.invert();
  15351. a.clipTo(b);
  15352. b.clipTo(a);
  15353. a.build(b.allPolygons());
  15354. a.invert();
  15355. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15356. };
  15357. CSG.prototype.intersectInPlace = function (csg) {
  15358. var a = new Node(this.polygons);
  15359. var b = new Node(csg.polygons);
  15360. a.invert();
  15361. b.clipTo(a);
  15362. b.invert();
  15363. a.clipTo(b);
  15364. b.clipTo(a);
  15365. a.build(b.allPolygons());
  15366. a.invert();
  15367. this.polygons = a.allPolygons();
  15368. };
  15369. CSG.prototype.inverse = function () {
  15370. var csg = this.clone();
  15371. csg.inverseInPlace();
  15372. return csg;
  15373. };
  15374. CSG.prototype.inverseInPlace = function () {
  15375. this.polygons.map(function (p) {
  15376. p.flip();
  15377. });
  15378. };
  15379. CSG.prototype.copyTransformAttributes = function (csg) {
  15380. this.matrix = csg.matrix;
  15381. this.position = csg.position;
  15382. this.rotation = csg.rotation;
  15383. this.scaling = csg.scaling;
  15384. return this;
  15385. };
  15386. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  15387. var matrix = this.matrix.clone();
  15388. matrix.invert();
  15389. 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;
  15390. if (keepSubMeshes) {
  15391. polygons.sort(function (a, b) {
  15392. if (a.shared.meshId === b.shared.meshId) {
  15393. return a.shared.subMeshId - b.shared.subMeshId;
  15394. } else {
  15395. return a.shared.meshId - b.shared.meshId;
  15396. }
  15397. });
  15398. }
  15399. for (var i = 0, il = polygons.length; i < il; i++) {
  15400. polygon = polygons[i];
  15401. if (!subMesh_dict[polygon.shared.meshId]) {
  15402. subMesh_dict[polygon.shared.meshId] = {};
  15403. }
  15404. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  15405. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  15406. indexStart: +Infinity,
  15407. indexEnd: -Infinity,
  15408. materialIndex: polygon.shared.materialIndex
  15409. };
  15410. }
  15411. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  15412. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  15413. polygonIndices[0] = 0;
  15414. polygonIndices[1] = j - 1;
  15415. polygonIndices[2] = j;
  15416. for (var k = 0; k < 3; k++) {
  15417. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  15418. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  15419. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  15420. BABYLON.Vector3.TransformCoordinatesToRef(vertex, matrix, vertex);
  15421. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  15422. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z];
  15423. 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)) {
  15424. vertices.push(vertex.x, vertex.y, vertex.z);
  15425. uvs.push(uv.x, uv.y);
  15426. normals.push(normal.x, normal.y, normal.z);
  15427. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z] = (vertices.length / 3) - 1;
  15428. }
  15429. indices.push(vertex_idx);
  15430. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  15431. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  15432. currentIndex++;
  15433. }
  15434. }
  15435. }
  15436. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  15437. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15438. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  15439. mesh.setIndices(indices);
  15440. if (keepSubMeshes) {
  15441. var materialIndexOffset = 0, materialMaxIndex;
  15442. mesh.subMeshes.length = 0;
  15443. for (var m in subMesh_dict) {
  15444. materialMaxIndex = -1;
  15445. for (var sm in subMesh_dict[m]) {
  15446. subMesh_obj = subMesh_dict[m][sm];
  15447. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  15448. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  15449. }
  15450. materialIndexOffset += ++materialMaxIndex;
  15451. }
  15452. }
  15453. return mesh;
  15454. };
  15455. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  15456. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  15457. mesh.material = material;
  15458. mesh.position.copyFrom(this.position);
  15459. mesh.rotation.copyFrom(this.rotation);
  15460. mesh.scaling.copyFrom(this.scaling);
  15461. mesh.computeWorldMatrix(true);
  15462. return mesh;
  15463. };
  15464. return CSG;
  15465. })();
  15466. BABYLON.CSG = CSG;
  15467. })(BABYLON || (BABYLON = {}));
  15468. var __extends = this.__extends || function (d, b) {
  15469. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15470. function __() { this.constructor = d; }
  15471. __.prototype = b.prototype;
  15472. d.prototype = new __();
  15473. };
  15474. var BABYLON;
  15475. (function (BABYLON) {
  15476. var OculusDistortionCorrectionPostProcess = (function (_super) {
  15477. __extends(OculusDistortionCorrectionPostProcess, _super);
  15478. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  15479. var _this = this;
  15480. _super.call(this, name, "oculusDistortionCorrection", [
  15481. 'LensCenter',
  15482. 'Scale',
  15483. 'ScaleIn',
  15484. 'HmdWarpParam'
  15485. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  15486. this._isRightEye = isRightEye;
  15487. this._distortionFactors = cameraSettings.DistortionK;
  15488. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  15489. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  15490. this.onSizeChanged = function () {
  15491. _this.aspectRatio = _this.width * .5 / _this.height;
  15492. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  15493. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  15494. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  15495. };
  15496. this.onApply = function (effect) {
  15497. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  15498. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  15499. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  15500. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  15501. };
  15502. }
  15503. return OculusDistortionCorrectionPostProcess;
  15504. })(BABYLON.PostProcess);
  15505. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  15506. })(BABYLON || (BABYLON = {}));
  15507. var BABYLON;
  15508. (function (BABYLON) {
  15509. (function (JoystickAxis) {
  15510. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  15511. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  15512. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  15513. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  15514. var JoystickAxis = BABYLON.JoystickAxis;
  15515. var VirtualJoystick = (function () {
  15516. function VirtualJoystick(leftJoystick) {
  15517. var _this = this;
  15518. if (leftJoystick) {
  15519. this._leftJoystick = true;
  15520. } else {
  15521. this._leftJoystick = false;
  15522. }
  15523. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  15524. VirtualJoystick._globalJoystickIndex++;
  15525. this._axisTargetedByLeftAndRight = 0 /* X */;
  15526. this._axisTargetedByUpAndDown = 1 /* Y */;
  15527. this.reverseLeftRight = false;
  15528. this.reverseUpDown = false;
  15529. this._touches = new BABYLON.VirtualJoystick.Collection();
  15530. this.deltaPosition = BABYLON.Vector3.Zero();
  15531. this._joystickSensibility = 25;
  15532. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  15533. this._rotationSpeed = 25;
  15534. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  15535. this._rotateOnAxisRelativeToMesh = false;
  15536. if (!VirtualJoystick.vjCanvas) {
  15537. window.addEventListener("resize", function () {
  15538. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  15539. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  15540. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  15541. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  15542. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  15543. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  15544. }, false);
  15545. VirtualJoystick.vjCanvas = document.createElement("canvas");
  15546. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  15547. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  15548. VirtualJoystick.vjCanvas.width = window.innerWidth;
  15549. VirtualJoystick.vjCanvas.height = window.innerHeight;
  15550. VirtualJoystick.vjCanvas.style.width = "100%";
  15551. VirtualJoystick.vjCanvas.style.height = "100%";
  15552. VirtualJoystick.vjCanvas.style.position = "absolute";
  15553. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  15554. VirtualJoystick.vjCanvas.style.top = "0px";
  15555. VirtualJoystick.vjCanvas.style.left = "0px";
  15556. VirtualJoystick.vjCanvas.style.zIndex = "5";
  15557. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  15558. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  15559. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  15560. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  15561. document.body.appendChild(VirtualJoystick.vjCanvas);
  15562. }
  15563. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  15564. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  15565. this.pressed = false;
  15566. this._joystickColor = "cyan";
  15567. this._joystickPointerID = -1;
  15568. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  15569. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  15570. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  15571. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  15572. _this._onPointerDown(evt);
  15573. }, false);
  15574. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  15575. _this._onPointerMove(evt);
  15576. }, false);
  15577. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  15578. _this._onPointerUp(evt);
  15579. }, false);
  15580. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  15581. _this._onPointerUp(evt);
  15582. }, false);
  15583. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  15584. evt.preventDefault();
  15585. }, false);
  15586. requestAnimationFrame(function () {
  15587. _this._drawVirtualJoystick();
  15588. });
  15589. }
  15590. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  15591. this._joystickSensibility = newJoystickSensibility;
  15592. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  15593. };
  15594. VirtualJoystick.prototype._onPointerDown = function (e) {
  15595. var positionOnScreenCondition;
  15596. e.preventDefault();
  15597. if (this._leftJoystick === true) {
  15598. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  15599. } else {
  15600. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  15601. }
  15602. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  15603. this._joystickPointerID = e.pointerId;
  15604. this._joystickPointerStartPos.x = e.clientX;
  15605. this._joystickPointerStartPos.y = e.clientY;
  15606. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  15607. this._deltaJoystickVector.x = 0;
  15608. this._deltaJoystickVector.y = 0;
  15609. this.pressed = true;
  15610. this._touches.add(e.pointerId.toString(), e);
  15611. } else {
  15612. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  15613. this._action();
  15614. this._touches.add(e.pointerId.toString(), e);
  15615. }
  15616. }
  15617. };
  15618. VirtualJoystick.prototype._onPointerMove = function (e) {
  15619. if (this._joystickPointerID == e.pointerId) {
  15620. this._joystickPointerPos.x = e.clientX;
  15621. this._joystickPointerPos.y = e.clientY;
  15622. this._deltaJoystickVector = this._joystickPointerPos.clone();
  15623. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  15624. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  15625. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  15626. switch (this._axisTargetedByLeftAndRight) {
  15627. case 0 /* X */:
  15628. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  15629. break;
  15630. case 1 /* Y */:
  15631. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  15632. break;
  15633. case 2 /* Z */:
  15634. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  15635. break;
  15636. }
  15637. var directionUpDown = this.reverseUpDown ? 1 : -1;
  15638. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  15639. switch (this._axisTargetedByUpAndDown) {
  15640. case 0 /* X */:
  15641. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  15642. break;
  15643. case 1 /* Y */:
  15644. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  15645. break;
  15646. case 2 /* Z */:
  15647. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  15648. break;
  15649. }
  15650. } else {
  15651. if (this._touches.item(e.pointerId.toString())) {
  15652. this._touches.item(e.pointerId.toString()).x = e.clientX;
  15653. this._touches.item(e.pointerId.toString()).y = e.clientY;
  15654. }
  15655. }
  15656. };
  15657. VirtualJoystick.prototype._onPointerUp = function (e) {
  15658. this._clearCanvas();
  15659. if (this._joystickPointerID == e.pointerId) {
  15660. this._joystickPointerID = -1;
  15661. this.pressed = false;
  15662. }
  15663. this._deltaJoystickVector.x = 0;
  15664. this._deltaJoystickVector.y = 0;
  15665. this._touches.remove(e.pointerId.toString());
  15666. };
  15667. /**
  15668. * Change the color of the virtual joystick
  15669. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  15670. */
  15671. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  15672. this._joystickColor = newColor;
  15673. };
  15674. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  15675. this._action = action;
  15676. };
  15677. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  15678. switch (axis) {
  15679. case 0 /* X */:
  15680. case 1 /* Y */:
  15681. case 2 /* Z */:
  15682. this._axisTargetedByLeftAndRight = axis;
  15683. break;
  15684. default:
  15685. this._axisTargetedByLeftAndRight = 0 /* X */;
  15686. break;
  15687. }
  15688. };
  15689. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  15690. switch (axis) {
  15691. case 0 /* X */:
  15692. case 1 /* Y */:
  15693. case 2 /* Z */:
  15694. this._axisTargetedByUpAndDown = axis;
  15695. break;
  15696. default:
  15697. this._axisTargetedByUpAndDown = 1 /* Y */;
  15698. break;
  15699. }
  15700. };
  15701. VirtualJoystick.prototype._clearCanvas = function () {
  15702. if (this._leftJoystick) {
  15703. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  15704. } else {
  15705. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  15706. }
  15707. };
  15708. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  15709. var _this = this;
  15710. if (this.pressed) {
  15711. this._clearCanvas();
  15712. this._touches.forEach(function (touch) {
  15713. if (touch.pointerId === _this._joystickPointerID) {
  15714. VirtualJoystick.vjCanvasContext.beginPath();
  15715. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15716. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  15717. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  15718. VirtualJoystick.vjCanvasContext.stroke();
  15719. VirtualJoystick.vjCanvasContext.beginPath();
  15720. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15721. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  15722. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  15723. VirtualJoystick.vjCanvasContext.stroke();
  15724. VirtualJoystick.vjCanvasContext.beginPath();
  15725. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15726. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  15727. VirtualJoystick.vjCanvasContext.stroke();
  15728. } else {
  15729. VirtualJoystick.vjCanvasContext.beginPath();
  15730. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  15731. VirtualJoystick.vjCanvasContext.beginPath();
  15732. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  15733. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  15734. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  15735. VirtualJoystick.vjCanvasContext.stroke();
  15736. }
  15737. ;
  15738. });
  15739. }
  15740. requestAnimationFrame(function () {
  15741. _this._drawVirtualJoystick();
  15742. });
  15743. };
  15744. VirtualJoystick.prototype.releaseCanvas = function () {
  15745. if (VirtualJoystick.vjCanvas) {
  15746. document.body.removeChild(VirtualJoystick.vjCanvas);
  15747. VirtualJoystick.vjCanvas = null;
  15748. }
  15749. };
  15750. VirtualJoystick._globalJoystickIndex = 0;
  15751. return VirtualJoystick;
  15752. })();
  15753. BABYLON.VirtualJoystick = VirtualJoystick;
  15754. })(BABYLON || (BABYLON = {}));
  15755. var BABYLON;
  15756. (function (BABYLON) {
  15757. (function (VirtualJoystick) {
  15758. var Collection = (function () {
  15759. function Collection() {
  15760. this._count = 0;
  15761. this._collection = new Array();
  15762. }
  15763. Collection.prototype.Count = function () {
  15764. return this._count;
  15765. };
  15766. Collection.prototype.add = function (key, item) {
  15767. if (this._collection[key] != undefined) {
  15768. return undefined;
  15769. }
  15770. this._collection[key] = item;
  15771. return ++this._count;
  15772. };
  15773. Collection.prototype.remove = function (key) {
  15774. if (this._collection[key] == undefined) {
  15775. return undefined;
  15776. }
  15777. delete this._collection[key];
  15778. return --this._count;
  15779. };
  15780. Collection.prototype.item = function (key) {
  15781. return this._collection[key];
  15782. };
  15783. Collection.prototype.forEach = function (block) {
  15784. var key;
  15785. for (key in this._collection) {
  15786. if (this._collection.hasOwnProperty(key)) {
  15787. block(this._collection[key]);
  15788. }
  15789. }
  15790. };
  15791. return Collection;
  15792. })();
  15793. VirtualJoystick.Collection = Collection;
  15794. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  15795. var VirtualJoystick = BABYLON.VirtualJoystick;
  15796. })(BABYLON || (BABYLON = {}));
  15797. var __extends = this.__extends || function (d, b) {
  15798. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15799. function __() { this.constructor = d; }
  15800. __.prototype = b.prototype;
  15801. d.prototype = new __();
  15802. };
  15803. var BABYLON;
  15804. (function (BABYLON) {
  15805. var OculusRiftDevKit2013_Metric = {
  15806. HResolution: 1280,
  15807. VResolution: 800,
  15808. HScreenSize: 0.149759993,
  15809. VScreenSize: 0.0935999975,
  15810. VScreenCenter: 0.0467999987,
  15811. EyeToScreenDistance: 0.0410000011,
  15812. LensSeparationDistance: 0.0635000020,
  15813. InterpupillaryDistance: 0.0640000030,
  15814. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  15815. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  15816. PostProcessScaleFactor: 1.714605507808412,
  15817. LensCenterOffset: 0.151976421
  15818. };
  15819. var _OculusInnerCamera = (function (_super) {
  15820. __extends(_OculusInnerCamera, _super);
  15821. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  15822. _super.call(this, name, position, scene);
  15823. this._workMatrix = new BABYLON.Matrix();
  15824. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  15825. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  15826. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  15827. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  15828. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  15829. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  15830. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  15831. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  15832. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  15833. }
  15834. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  15835. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  15836. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  15837. return this._projectionMatrix;
  15838. };
  15839. _OculusInnerCamera.prototype._getViewMatrix = function () {
  15840. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  15841. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  15842. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  15843. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  15844. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  15845. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  15846. return this._viewMatrix;
  15847. };
  15848. return _OculusInnerCamera;
  15849. })(BABYLON.FreeCamera);
  15850. var OculusCamera = (function (_super) {
  15851. __extends(OculusCamera, _super);
  15852. function OculusCamera(name, position, scene) {
  15853. _super.call(this, name, position, scene);
  15854. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  15855. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  15856. this.subCameras.push(this._leftCamera);
  15857. this.subCameras.push(this._rightCamera);
  15858. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  15859. }
  15860. OculusCamera.prototype._update = function () {
  15861. this._leftCamera.position.copyFrom(this.position);
  15862. this._rightCamera.position.copyFrom(this.position);
  15863. this._updateCamera(this._leftCamera);
  15864. this._updateCamera(this._rightCamera);
  15865. _super.prototype._update.call(this);
  15866. };
  15867. OculusCamera.prototype._updateCamera = function (camera) {
  15868. camera.minZ = this.minZ;
  15869. camera.maxZ = this.maxZ;
  15870. camera.rotation.x = this.rotation.x;
  15871. camera.rotation.y = this.rotation.y;
  15872. camera.rotation.z = this.rotation.z;
  15873. };
  15874. OculusCamera.prototype._onOrientationEvent = function (evt) {
  15875. var yaw = evt.alpha / 180 * Math.PI;
  15876. var pitch = evt.beta / 180 * Math.PI;
  15877. var roll = evt.gamma / 180 * Math.PI;
  15878. if (!this._offsetOrientation) {
  15879. this._offsetOrientation = {
  15880. yaw: yaw,
  15881. pitch: pitch,
  15882. roll: roll
  15883. };
  15884. return;
  15885. } else {
  15886. this.rotation.y += yaw - this._offsetOrientation.yaw;
  15887. this.rotation.x += pitch - this._offsetOrientation.pitch;
  15888. this.rotation.z += this._offsetOrientation.roll - roll;
  15889. this._offsetOrientation.yaw = yaw;
  15890. this._offsetOrientation.pitch = pitch;
  15891. this._offsetOrientation.roll = roll;
  15892. }
  15893. };
  15894. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  15895. _super.prototype.attachControl.call(this, element, noPreventDefault);
  15896. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  15897. };
  15898. OculusCamera.prototype.detachControl = function (element) {
  15899. _super.prototype.detachControl.call(this, element);
  15900. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  15901. };
  15902. return OculusCamera;
  15903. })(BABYLON.FreeCamera);
  15904. BABYLON.OculusCamera = OculusCamera;
  15905. })(BABYLON || (BABYLON = {}));
  15906. var __extends = this.__extends || function (d, b) {
  15907. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15908. function __() { this.constructor = d; }
  15909. __.prototype = b.prototype;
  15910. d.prototype = new __();
  15911. };
  15912. var BABYLON;
  15913. (function (BABYLON) {
  15914. var OculusRiftDevKit2013_Metric = {
  15915. HResolution: 1280,
  15916. VResolution: 800,
  15917. HScreenSize: 0.149759993,
  15918. VScreenSize: 0.0935999975,
  15919. VScreenCenter: 0.0467999987,
  15920. EyeToScreenDistance: 0.0410000011,
  15921. LensSeparationDistance: 0.0635000020,
  15922. InterpupillaryDistance: 0.0640000030,
  15923. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  15924. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  15925. PostProcessScaleFactor: 1.714605507808412,
  15926. LensCenterOffset: 0.151976421
  15927. };
  15928. var _OculusInnerGamepadCamera = (function (_super) {
  15929. __extends(_OculusInnerGamepadCamera, _super);
  15930. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  15931. _super.call(this, name, position, scene);
  15932. this._workMatrix = new BABYLON.Matrix();
  15933. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  15934. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  15935. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  15936. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  15937. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  15938. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  15939. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  15940. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  15941. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  15942. }
  15943. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  15944. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  15945. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  15946. return this._projectionMatrix;
  15947. };
  15948. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  15949. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  15950. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  15951. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  15952. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  15953. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  15954. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  15955. return this._viewMatrix;
  15956. };
  15957. return _OculusInnerGamepadCamera;
  15958. })(BABYLON.FreeCamera);
  15959. var OculusGamepadCamera = (function (_super) {
  15960. __extends(OculusGamepadCamera, _super);
  15961. function OculusGamepadCamera(name, position, scene) {
  15962. var _this = this;
  15963. _super.call(this, name, position, scene);
  15964. this.angularSensibility = 200;
  15965. this.moveSensibility = 75;
  15966. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  15967. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  15968. this.subCameras.push(this._leftCamera);
  15969. this.subCameras.push(this._rightCamera);
  15970. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  15971. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  15972. _this._onNewGameConnected(gamepad);
  15973. });
  15974. }
  15975. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  15976. if (gamepad.index === 0) {
  15977. this._gamepad = gamepad;
  15978. }
  15979. };
  15980. OculusGamepadCamera.prototype._update = function () {
  15981. this._leftCamera.position.copyFrom(this.position);
  15982. this._rightCamera.position.copyFrom(this.position);
  15983. this._updateCamera(this._leftCamera);
  15984. this._updateCamera(this._rightCamera);
  15985. _super.prototype._update.call(this);
  15986. };
  15987. OculusGamepadCamera.prototype._checkInputs = function () {
  15988. if (!this._gamepad) {
  15989. return;
  15990. }
  15991. var LSValues = this._gamepad.leftStick;
  15992. var normalizedLX = LSValues.x / this.moveSensibility;
  15993. var normalizedLY = LSValues.y / this.moveSensibility;
  15994. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  15995. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  15996. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  15997. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  15998. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  15999. };
  16000. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  16001. camera.minZ = this.minZ;
  16002. camera.maxZ = this.maxZ;
  16003. camera.rotation.x = this.rotation.x;
  16004. camera.rotation.y = this.rotation.y;
  16005. camera.rotation.z = this.rotation.z;
  16006. };
  16007. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  16008. var yaw = evt.alpha / 180 * Math.PI;
  16009. var pitch = evt.beta / 180 * Math.PI;
  16010. var roll = evt.gamma / 180 * Math.PI;
  16011. if (!this._offsetOrientation) {
  16012. this._offsetOrientation = {
  16013. yaw: yaw,
  16014. pitch: pitch,
  16015. roll: roll
  16016. };
  16017. return;
  16018. } else {
  16019. this.rotation.y += yaw - this._offsetOrientation.yaw;
  16020. this.rotation.x += pitch - this._offsetOrientation.pitch;
  16021. this.rotation.z += this._offsetOrientation.roll - roll;
  16022. this._offsetOrientation.yaw = yaw;
  16023. this._offsetOrientation.pitch = pitch;
  16024. this._offsetOrientation.roll = roll;
  16025. }
  16026. };
  16027. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  16028. _super.prototype.attachControl.call(this, element, noPreventDefault);
  16029. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  16030. };
  16031. OculusGamepadCamera.prototype.detachControl = function (element) {
  16032. _super.prototype.detachControl.call(this, element);
  16033. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  16034. };
  16035. OculusGamepadCamera.prototype.dispose = function () {
  16036. this._gamepads.dispose();
  16037. _super.prototype.dispose.call(this);
  16038. };
  16039. return OculusGamepadCamera;
  16040. })(BABYLON.FreeCamera);
  16041. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  16042. })(BABYLON || (BABYLON = {}));
  16043. var __extends = this.__extends || function (d, b) {
  16044. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16045. function __() { this.constructor = d; }
  16046. __.prototype = b.prototype;
  16047. d.prototype = new __();
  16048. };
  16049. var BABYLON;
  16050. (function (BABYLON) {
  16051. var VirtualJoysticksCamera = (function (_super) {
  16052. __extends(VirtualJoysticksCamera, _super);
  16053. function VirtualJoysticksCamera(name, position, scene) {
  16054. _super.call(this, name, position, scene);
  16055. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  16056. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  16057. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  16058. this._leftjoystick.setJoystickSensibility(0.15);
  16059. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  16060. this._rightjoystick.setAxisForUpDown(0 /* X */);
  16061. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  16062. this._rightjoystick.reverseUpDown = true;
  16063. this._rightjoystick.setJoystickSensibility(0.05);
  16064. this._rightjoystick.setJoystickColor("yellow");
  16065. }
  16066. VirtualJoysticksCamera.prototype._checkInputs = function () {
  16067. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  16068. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  16069. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  16070. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  16071. if (!this._leftjoystick.pressed) {
  16072. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  16073. }
  16074. if (!this._rightjoystick.pressed) {
  16075. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  16076. }
  16077. };
  16078. VirtualJoysticksCamera.prototype.dispose = function () {
  16079. this._leftjoystick.releaseCanvas();
  16080. _super.prototype.dispose.call(this);
  16081. };
  16082. return VirtualJoysticksCamera;
  16083. })(BABYLON.FreeCamera);
  16084. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  16085. })(BABYLON || (BABYLON = {}));
  16086. var __extends = this.__extends || function (d, b) {
  16087. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16088. function __() { this.constructor = d; }
  16089. __.prototype = b.prototype;
  16090. d.prototype = new __();
  16091. };
  16092. var BABYLON;
  16093. (function (BABYLON) {
  16094. var ShaderMaterial = (function (_super) {
  16095. __extends(ShaderMaterial, _super);
  16096. function ShaderMaterial(name, scene, shaderPath, options) {
  16097. _super.call(this, name, scene);
  16098. this._textures = new Array();
  16099. this._floats = new Array();
  16100. this._floatsArrays = {};
  16101. this._colors3 = new Array();
  16102. this._colors4 = new Array();
  16103. this._vectors2 = new Array();
  16104. this._vectors3 = new Array();
  16105. this._matrices = new Array();
  16106. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  16107. this._shaderPath = shaderPath;
  16108. options.needAlphaBlending = options.needAlphaBlending || false;
  16109. options.needAlphaTesting = options.needAlphaTesting || false;
  16110. options.attributes = options.attributes || ["position", "normal", "uv"];
  16111. options.uniforms = options.uniforms || ["worldViewProjection"];
  16112. options.samplers = options.samplers || [];
  16113. this._options = options;
  16114. }
  16115. ShaderMaterial.prototype.needAlphaBlending = function () {
  16116. return this._options.needAlphaBlending;
  16117. };
  16118. ShaderMaterial.prototype.needAlphaTesting = function () {
  16119. return this._options.needAlphaTesting;
  16120. };
  16121. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  16122. if (this._options.uniforms.indexOf(uniformName) === -1) {
  16123. this._options.uniforms.push(uniformName);
  16124. }
  16125. };
  16126. ShaderMaterial.prototype.setTexture = function (name, texture) {
  16127. if (this._options.samplers.indexOf(name) === -1) {
  16128. this._options.samplers.push(name);
  16129. }
  16130. this._textures[name] = texture;
  16131. return this;
  16132. };
  16133. ShaderMaterial.prototype.setFloat = function (name, value) {
  16134. this._checkUniform(name);
  16135. this._floats[name] = value;
  16136. return this;
  16137. };
  16138. ShaderMaterial.prototype.setFloats = function (name, value) {
  16139. this._checkUniform(name);
  16140. this._floatsArrays[name] = value;
  16141. return this;
  16142. };
  16143. ShaderMaterial.prototype.setColor3 = function (name, value) {
  16144. this._checkUniform(name);
  16145. this._colors3[name] = value;
  16146. return this;
  16147. };
  16148. ShaderMaterial.prototype.setColor4 = function (name, value) {
  16149. this._checkUniform(name);
  16150. this._colors4[name] = value;
  16151. return this;
  16152. };
  16153. ShaderMaterial.prototype.setVector2 = function (name, value) {
  16154. this._checkUniform(name);
  16155. this._vectors2[name] = value;
  16156. return this;
  16157. };
  16158. ShaderMaterial.prototype.setVector3 = function (name, value) {
  16159. this._checkUniform(name);
  16160. this._vectors3[name] = value;
  16161. return this;
  16162. };
  16163. ShaderMaterial.prototype.setMatrix = function (name, value) {
  16164. this._checkUniform(name);
  16165. this._matrices[name] = value;
  16166. return this;
  16167. };
  16168. ShaderMaterial.prototype.isReady = function () {
  16169. var engine = this.getScene().getEngine();
  16170. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  16171. if (!this._effect.isReady()) {
  16172. return false;
  16173. }
  16174. return true;
  16175. };
  16176. ShaderMaterial.prototype.bind = function (world) {
  16177. if (this._options.uniforms.indexOf("world") !== -1) {
  16178. this._effect.setMatrix("world", world);
  16179. }
  16180. if (this._options.uniforms.indexOf("view") !== -1) {
  16181. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  16182. }
  16183. if (this._options.uniforms.indexOf("worldView") !== -1) {
  16184. world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
  16185. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  16186. }
  16187. if (this._options.uniforms.indexOf("projection") !== -1) {
  16188. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  16189. }
  16190. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  16191. this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
  16192. }
  16193. for (var name in this._textures) {
  16194. this._effect.setTexture(name, this._textures[name]);
  16195. }
  16196. for (name in this._floats) {
  16197. this._effect.setFloat(name, this._floats[name]);
  16198. }
  16199. for (name in this._floatsArrays) {
  16200. this._effect.setArray(name, this._floatsArrays[name]);
  16201. }
  16202. for (name in this._colors3) {
  16203. this._effect.setColor3(name, this._colors3[name]);
  16204. }
  16205. for (name in this._colors4) {
  16206. var color = this._colors4[name];
  16207. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16208. }
  16209. for (name in this._vectors2) {
  16210. this._effect.setVector2(name, this._vectors2[name]);
  16211. }
  16212. for (name in this._vectors3) {
  16213. this._effect.setVector3(name, this._vectors3[name]);
  16214. }
  16215. for (name in this._matrices) {
  16216. this._effect.setMatrix(name, this._matrices[name]);
  16217. }
  16218. };
  16219. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  16220. for (var name in this._textures) {
  16221. this._textures[name].dispose();
  16222. }
  16223. this._textures = [];
  16224. _super.prototype.dispose.call(this, forceDisposeEffect);
  16225. };
  16226. return ShaderMaterial;
  16227. })(BABYLON.Material);
  16228. BABYLON.ShaderMaterial = ShaderMaterial;
  16229. })(BABYLON || (BABYLON = {}));
  16230. var BABYLON;
  16231. (function (BABYLON) {
  16232. var VertexData = (function () {
  16233. function VertexData() {
  16234. }
  16235. VertexData.prototype.set = function (data, kind) {
  16236. switch (kind) {
  16237. case BABYLON.VertexBuffer.PositionKind:
  16238. this.positions = data;
  16239. break;
  16240. case BABYLON.VertexBuffer.NormalKind:
  16241. this.normals = data;
  16242. break;
  16243. case BABYLON.VertexBuffer.UVKind:
  16244. this.uvs = data;
  16245. break;
  16246. case BABYLON.VertexBuffer.UV2Kind:
  16247. this.uv2s = data;
  16248. break;
  16249. case BABYLON.VertexBuffer.ColorKind:
  16250. this.colors = data;
  16251. break;
  16252. case BABYLON.VertexBuffer.MatricesIndicesKind:
  16253. this.matricesIndices = data;
  16254. break;
  16255. case BABYLON.VertexBuffer.MatricesWeightsKind:
  16256. this.matricesWeights = data;
  16257. break;
  16258. }
  16259. };
  16260. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  16261. this._applyTo(mesh, updatable);
  16262. };
  16263. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  16264. this._applyTo(geometry, updatable);
  16265. };
  16266. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  16267. this._update(mesh);
  16268. };
  16269. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  16270. this._update(geometry);
  16271. };
  16272. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  16273. if (this.positions) {
  16274. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  16275. }
  16276. if (this.normals) {
  16277. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  16278. }
  16279. if (this.uvs) {
  16280. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  16281. }
  16282. if (this.uv2s) {
  16283. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  16284. }
  16285. if (this.colors) {
  16286. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  16287. }
  16288. if (this.matricesIndices) {
  16289. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  16290. }
  16291. if (this.matricesWeights) {
  16292. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  16293. }
  16294. if (this.indices) {
  16295. meshOrGeometry.setIndices(this.indices);
  16296. }
  16297. };
  16298. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  16299. if (this.positions) {
  16300. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  16301. }
  16302. if (this.normals) {
  16303. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  16304. }
  16305. if (this.uvs) {
  16306. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  16307. }
  16308. if (this.uv2s) {
  16309. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  16310. }
  16311. if (this.colors) {
  16312. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  16313. }
  16314. if (this.matricesIndices) {
  16315. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  16316. }
  16317. if (this.matricesWeights) {
  16318. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  16319. }
  16320. if (this.indices) {
  16321. meshOrGeometry.setIndices(this.indices);
  16322. }
  16323. };
  16324. VertexData.prototype.transform = function (matrix) {
  16325. var transformed = BABYLON.Vector3.Zero();
  16326. if (this.positions) {
  16327. var position = BABYLON.Vector3.Zero();
  16328. for (var index = 0; index < this.positions.length; index += 3) {
  16329. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  16330. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  16331. this.positions[index] = transformed.x;
  16332. this.positions[index + 1] = transformed.y;
  16333. this.positions[index + 2] = transformed.z;
  16334. }
  16335. }
  16336. if (this.normals) {
  16337. var normal = BABYLON.Vector3.Zero();
  16338. for (index = 0; index < this.normals.length; index += 3) {
  16339. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  16340. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  16341. this.normals[index] = transformed.x;
  16342. this.normals[index + 1] = transformed.y;
  16343. this.normals[index + 2] = transformed.z;
  16344. }
  16345. }
  16346. };
  16347. VertexData.prototype.merge = function (other) {
  16348. if (other.indices) {
  16349. if (!this.indices) {
  16350. this.indices = [];
  16351. }
  16352. var offset = this.positions ? this.positions.length / 3 : 0;
  16353. for (var index = 0; index < other.indices.length; index++) {
  16354. this.indices.push(other.indices[index] + offset);
  16355. }
  16356. }
  16357. if (other.positions) {
  16358. if (!this.positions) {
  16359. this.positions = [];
  16360. }
  16361. for (index = 0; index < other.positions.length; index++) {
  16362. this.positions.push(other.positions[index]);
  16363. }
  16364. }
  16365. if (other.normals) {
  16366. if (!this.normals) {
  16367. this.normals = [];
  16368. }
  16369. for (index = 0; index < other.normals.length; index++) {
  16370. this.normals.push(other.normals[index]);
  16371. }
  16372. }
  16373. if (other.uvs) {
  16374. if (!this.uvs) {
  16375. this.uvs = [];
  16376. }
  16377. for (index = 0; index < other.uvs.length; index++) {
  16378. this.uvs.push(other.uvs[index]);
  16379. }
  16380. }
  16381. if (other.uv2s) {
  16382. if (!this.uv2s) {
  16383. this.uv2s = [];
  16384. }
  16385. for (index = 0; index < other.uv2s.length; index++) {
  16386. this.uv2s.push(other.uv2s[index]);
  16387. }
  16388. }
  16389. if (other.matricesIndices) {
  16390. if (!this.matricesIndices) {
  16391. this.matricesIndices = [];
  16392. }
  16393. for (index = 0; index < other.matricesIndices.length; index++) {
  16394. this.matricesIndices.push(other.matricesIndices[index]);
  16395. }
  16396. }
  16397. if (other.matricesWeights) {
  16398. if (!this.matricesWeights) {
  16399. this.matricesWeights = [];
  16400. }
  16401. for (index = 0; index < other.matricesWeights.length; index++) {
  16402. this.matricesWeights.push(other.matricesWeights[index]);
  16403. }
  16404. }
  16405. if (other.colors) {
  16406. if (!this.colors) {
  16407. this.colors = [];
  16408. }
  16409. for (index = 0; index < other.colors.length; index++) {
  16410. this.colors.push(other.colors[index]);
  16411. }
  16412. }
  16413. };
  16414. VertexData.ExtractFromMesh = function (mesh) {
  16415. return VertexData._ExtractFrom(mesh);
  16416. };
  16417. VertexData.ExtractFromGeometry = function (geometry) {
  16418. return VertexData._ExtractFrom(geometry);
  16419. };
  16420. VertexData._ExtractFrom = function (meshOrGeometry) {
  16421. var result = new BABYLON.VertexData();
  16422. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16423. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16424. }
  16425. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16426. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16427. }
  16428. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16429. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16430. }
  16431. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  16432. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  16433. }
  16434. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  16435. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  16436. }
  16437. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16438. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16439. }
  16440. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16441. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16442. }
  16443. result.indices = meshOrGeometry.getIndices();
  16444. return result;
  16445. };
  16446. VertexData.CreateBox = function (size) {
  16447. var normalsSource = [
  16448. new BABYLON.Vector3(0, 0, 1),
  16449. new BABYLON.Vector3(0, 0, -1),
  16450. new BABYLON.Vector3(1, 0, 0),
  16451. new BABYLON.Vector3(-1, 0, 0),
  16452. new BABYLON.Vector3(0, 1, 0),
  16453. new BABYLON.Vector3(0, -1, 0)
  16454. ];
  16455. var indices = [];
  16456. var positions = [];
  16457. var normals = [];
  16458. var uvs = [];
  16459. size = size || 1;
  16460. for (var index = 0; index < normalsSource.length; index++) {
  16461. var normal = normalsSource[index];
  16462. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  16463. var side2 = BABYLON.Vector3.Cross(normal, side1);
  16464. var verticesLength = positions.length / 3;
  16465. indices.push(verticesLength);
  16466. indices.push(verticesLength + 1);
  16467. indices.push(verticesLength + 2);
  16468. indices.push(verticesLength);
  16469. indices.push(verticesLength + 2);
  16470. indices.push(verticesLength + 3);
  16471. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  16472. positions.push(vertex.x, vertex.y, vertex.z);
  16473. normals.push(normal.x, normal.y, normal.z);
  16474. uvs.push(1.0, 1.0);
  16475. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  16476. positions.push(vertex.x, vertex.y, vertex.z);
  16477. normals.push(normal.x, normal.y, normal.z);
  16478. uvs.push(0.0, 1.0);
  16479. vertex = normal.add(side1).add(side2).scale(size / 2);
  16480. positions.push(vertex.x, vertex.y, vertex.z);
  16481. normals.push(normal.x, normal.y, normal.z);
  16482. uvs.push(0.0, 0.0);
  16483. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  16484. positions.push(vertex.x, vertex.y, vertex.z);
  16485. normals.push(normal.x, normal.y, normal.z);
  16486. uvs.push(1.0, 0.0);
  16487. }
  16488. var vertexData = new BABYLON.VertexData();
  16489. vertexData.indices = indices;
  16490. vertexData.positions = positions;
  16491. vertexData.normals = normals;
  16492. vertexData.uvs = uvs;
  16493. return vertexData;
  16494. };
  16495. VertexData.CreateSphere = function (segments, diameter) {
  16496. segments = segments || 32;
  16497. diameter = diameter || 1;
  16498. var radius = diameter / 2;
  16499. var totalZRotationSteps = 2 + segments;
  16500. var totalYRotationSteps = 2 * totalZRotationSteps;
  16501. var indices = [];
  16502. var positions = [];
  16503. var normals = [];
  16504. var uvs = [];
  16505. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  16506. var normalizedZ = zRotationStep / totalZRotationSteps;
  16507. var angleZ = (normalizedZ * Math.PI);
  16508. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  16509. var normalizedY = yRotationStep / totalYRotationSteps;
  16510. var angleY = normalizedY * Math.PI * 2;
  16511. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  16512. var rotationY = BABYLON.Matrix.RotationY(angleY);
  16513. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  16514. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  16515. var vertex = complete.scale(radius);
  16516. var normal = BABYLON.Vector3.Normalize(vertex);
  16517. positions.push(vertex.x, vertex.y, vertex.z);
  16518. normals.push(normal.x, normal.y, normal.z);
  16519. uvs.push(normalizedZ, normalizedY);
  16520. }
  16521. if (zRotationStep > 0) {
  16522. var verticesCount = positions.length / 3;
  16523. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  16524. indices.push((firstIndex));
  16525. indices.push((firstIndex + 1));
  16526. indices.push(firstIndex + totalYRotationSteps + 1);
  16527. indices.push((firstIndex + totalYRotationSteps + 1));
  16528. indices.push((firstIndex + 1));
  16529. indices.push((firstIndex + totalYRotationSteps + 2));
  16530. }
  16531. }
  16532. }
  16533. var vertexData = new BABYLON.VertexData();
  16534. vertexData.indices = indices;
  16535. vertexData.positions = positions;
  16536. vertexData.normals = normals;
  16537. vertexData.uvs = uvs;
  16538. return vertexData;
  16539. };
  16540. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  16541. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  16542. var radiusTop = diameterTop / 2;
  16543. var radiusBottom = diameterBottom / 2;
  16544. var indices = [];
  16545. var positions = [];
  16546. var normals = [];
  16547. var uvs = [];
  16548. height = height || 1;
  16549. diameterTop = diameterTop || 0.5;
  16550. diameterBottom = diameterBottom || 1;
  16551. tessellation = tessellation || 16;
  16552. subdivisions = subdivisions || 1;
  16553. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  16554. var getCircleVector = function (i) {
  16555. var angle = (i * 2.0 * Math.PI / tessellation);
  16556. var dx = Math.cos(angle);
  16557. var dz = Math.sin(angle);
  16558. return new BABYLON.Vector3(dx, 0, dz);
  16559. };
  16560. var createCylinderCap = function (isTop) {
  16561. var radius = isTop ? radiusTop : radiusBottom;
  16562. if (radius == 0) {
  16563. return;
  16564. }
  16565. var vbase = positions.length / 3;
  16566. var offset = new BABYLON.Vector3(0, height / 2, 0);
  16567. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  16568. if (!isTop) {
  16569. offset.scaleInPlace(-1);
  16570. textureScale.x = -textureScale.x;
  16571. }
  16572. for (i = 0; i < tessellation; i++) {
  16573. var circleVector = getCircleVector(i);
  16574. var position = circleVector.scale(radius).add(offset);
  16575. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  16576. positions.push(position.x, position.y, position.z);
  16577. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16578. }
  16579. for (var i = 0; i < tessellation - 2; i++) {
  16580. if (!isTop) {
  16581. indices.push(vbase);
  16582. indices.push(vbase + (i + 2) % tessellation);
  16583. indices.push(vbase + (i + 1) % tessellation);
  16584. } else {
  16585. indices.push(vbase);
  16586. indices.push(vbase + (i + 1) % tessellation);
  16587. indices.push(vbase + (i + 2) % tessellation);
  16588. }
  16589. }
  16590. };
  16591. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  16592. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  16593. var stride = tessellation + 1;
  16594. for (var i = 0; i <= tessellation; i++) {
  16595. var circleVector = getCircleVector(i);
  16596. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  16597. var position, radius = radiusBottom;
  16598. for (var s = 0; s <= subdivisions; s++) {
  16599. position = circleVector.scale(radius);
  16600. position.addInPlace(base.add(offset.scale(s)));
  16601. textureCoordinate.y += 1 / subdivisions;
  16602. radius += (radiusTop - radiusBottom) / subdivisions;
  16603. positions.push(position.x, position.y, position.z);
  16604. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16605. }
  16606. }
  16607. subdivisions += 1;
  16608. for (var s = 0; s < subdivisions - 1; s++) {
  16609. for (var i = 0; i <= tessellation; i++) {
  16610. indices.push(i * subdivisions + s);
  16611. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  16612. indices.push(i * subdivisions + (s + 1));
  16613. indices.push(i * subdivisions + (s + 1));
  16614. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  16615. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  16616. }
  16617. }
  16618. createCylinderCap(true);
  16619. createCylinderCap(false);
  16620. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16621. var vertexData = new BABYLON.VertexData();
  16622. vertexData.indices = indices;
  16623. vertexData.positions = positions;
  16624. vertexData.normals = normals;
  16625. vertexData.uvs = uvs;
  16626. return vertexData;
  16627. };
  16628. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  16629. var indices = [];
  16630. var positions = [];
  16631. var normals = [];
  16632. var uvs = [];
  16633. diameter = diameter || 1;
  16634. thickness = thickness || 0.5;
  16635. tessellation = tessellation || 16;
  16636. var stride = tessellation + 1;
  16637. for (var i = 0; i <= tessellation; i++) {
  16638. var u = i / tessellation;
  16639. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  16640. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  16641. for (var j = 0; j <= tessellation; j++) {
  16642. var v = 1 - j / tessellation;
  16643. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  16644. var dx = Math.cos(innerAngle);
  16645. var dy = Math.sin(innerAngle);
  16646. var normal = new BABYLON.Vector3(dx, dy, 0);
  16647. var position = normal.scale(thickness / 2);
  16648. var textureCoordinate = new BABYLON.Vector2(u, v);
  16649. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  16650. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  16651. positions.push(position.x, position.y, position.z);
  16652. normals.push(normal.x, normal.y, normal.z);
  16653. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16654. var nextI = (i + 1) % stride;
  16655. var nextJ = (j + 1) % stride;
  16656. indices.push(i * stride + j);
  16657. indices.push(i * stride + nextJ);
  16658. indices.push(nextI * stride + j);
  16659. indices.push(i * stride + nextJ);
  16660. indices.push(nextI * stride + nextJ);
  16661. indices.push(nextI * stride + j);
  16662. }
  16663. }
  16664. var vertexData = new BABYLON.VertexData();
  16665. vertexData.indices = indices;
  16666. vertexData.positions = positions;
  16667. vertexData.normals = normals;
  16668. vertexData.uvs = uvs;
  16669. return vertexData;
  16670. };
  16671. VertexData.CreateLines = function (points) {
  16672. var indices = [];
  16673. var positions = [];
  16674. for (var index = 0; index < points.length; index++) {
  16675. positions.push(points[index].x, points[index].y, points[index].z);
  16676. if (index > 0) {
  16677. indices.push(index - 1);
  16678. indices.push(index);
  16679. }
  16680. }
  16681. var vertexData = new BABYLON.VertexData();
  16682. vertexData.indices = indices;
  16683. vertexData.positions = positions;
  16684. return vertexData;
  16685. };
  16686. VertexData.CreateGround = function (width, height, subdivisions) {
  16687. var indices = [];
  16688. var positions = [];
  16689. var normals = [];
  16690. var uvs = [];
  16691. var row, col;
  16692. width = width || 1;
  16693. height = height || 1;
  16694. subdivisions = subdivisions || 1;
  16695. for (row = 0; row <= subdivisions; row++) {
  16696. for (col = 0; col <= subdivisions; col++) {
  16697. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  16698. var normal = new BABYLON.Vector3(0, 1.0, 0);
  16699. positions.push(position.x, position.y, position.z);
  16700. normals.push(normal.x, normal.y, normal.z);
  16701. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  16702. }
  16703. }
  16704. for (row = 0; row < subdivisions; row++) {
  16705. for (col = 0; col < subdivisions; col++) {
  16706. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16707. indices.push(col + 1 + row * (subdivisions + 1));
  16708. indices.push(col + row * (subdivisions + 1));
  16709. indices.push(col + (row + 1) * (subdivisions + 1));
  16710. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16711. indices.push(col + row * (subdivisions + 1));
  16712. }
  16713. }
  16714. var vertexData = new BABYLON.VertexData();
  16715. vertexData.indices = indices;
  16716. vertexData.positions = positions;
  16717. vertexData.normals = normals;
  16718. vertexData.uvs = uvs;
  16719. return vertexData;
  16720. };
  16721. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  16722. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  16723. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  16724. var indices = [];
  16725. var positions = [];
  16726. var normals = [];
  16727. var uvs = [];
  16728. var row, col, tileRow, tileCol;
  16729. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  16730. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  16731. precision.w = (precision.w < 1) ? 1 : precision.w;
  16732. precision.h = (precision.h < 1) ? 1 : precision.h;
  16733. var tileSize = {
  16734. 'w': (xmax - xmin) / subdivisions.w,
  16735. 'h': (zmax - zmin) / subdivisions.h
  16736. };
  16737. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  16738. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  16739. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  16740. }
  16741. }
  16742. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  16743. var base = positions.length / 3;
  16744. var rowLength = precision.w + 1;
  16745. for (row = 0; row < precision.h; row++) {
  16746. for (col = 0; col < precision.w; col++) {
  16747. var square = [
  16748. base + col + row * rowLength,
  16749. base + (col + 1) + row * rowLength,
  16750. base + (col + 1) + (row + 1) * rowLength,
  16751. base + col + (row + 1) * rowLength
  16752. ];
  16753. indices.push(square[1]);
  16754. indices.push(square[2]);
  16755. indices.push(square[3]);
  16756. indices.push(square[0]);
  16757. indices.push(square[1]);
  16758. indices.push(square[3]);
  16759. }
  16760. }
  16761. var position = BABYLON.Vector3.Zero();
  16762. var normal = new BABYLON.Vector3(0, 1.0, 0);
  16763. for (row = 0; row <= precision.h; row++) {
  16764. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  16765. for (col = 0; col <= precision.w; col++) {
  16766. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  16767. position.y = 0;
  16768. positions.push(position.x, position.y, position.z);
  16769. normals.push(normal.x, normal.y, normal.z);
  16770. uvs.push(col / precision.w, row / precision.h);
  16771. }
  16772. }
  16773. }
  16774. var vertexData = new BABYLON.VertexData();
  16775. vertexData.indices = indices;
  16776. vertexData.positions = positions;
  16777. vertexData.normals = normals;
  16778. vertexData.uvs = uvs;
  16779. return vertexData;
  16780. };
  16781. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  16782. var indices = [];
  16783. var positions = [];
  16784. var normals = [];
  16785. var uvs = [];
  16786. var row, col;
  16787. for (row = 0; row <= subdivisions; row++) {
  16788. for (col = 0; col <= subdivisions; col++) {
  16789. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  16790. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  16791. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  16792. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  16793. var r = buffer[pos] / 255.0;
  16794. var g = buffer[pos + 1] / 255.0;
  16795. var b = buffer[pos + 2] / 255.0;
  16796. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  16797. position.y = minHeight + (maxHeight - minHeight) * gradient;
  16798. positions.push(position.x, position.y, position.z);
  16799. normals.push(0, 0, 0);
  16800. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  16801. }
  16802. }
  16803. for (row = 0; row < subdivisions; row++) {
  16804. for (col = 0; col < subdivisions; col++) {
  16805. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16806. indices.push(col + 1 + row * (subdivisions + 1));
  16807. indices.push(col + row * (subdivisions + 1));
  16808. indices.push(col + (row + 1) * (subdivisions + 1));
  16809. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16810. indices.push(col + row * (subdivisions + 1));
  16811. }
  16812. }
  16813. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16814. var vertexData = new BABYLON.VertexData();
  16815. vertexData.indices = indices;
  16816. vertexData.positions = positions;
  16817. vertexData.normals = normals;
  16818. vertexData.uvs = uvs;
  16819. return vertexData;
  16820. };
  16821. VertexData.CreatePlane = function (size) {
  16822. var indices = [];
  16823. var positions = [];
  16824. var normals = [];
  16825. var uvs = [];
  16826. size = size || 1;
  16827. var halfSize = size / 2.0;
  16828. positions.push(-halfSize, -halfSize, 0);
  16829. normals.push(0, 0, -1.0);
  16830. uvs.push(0.0, 0.0);
  16831. positions.push(halfSize, -halfSize, 0);
  16832. normals.push(0, 0, -1.0);
  16833. uvs.push(1.0, 0.0);
  16834. positions.push(halfSize, halfSize, 0);
  16835. normals.push(0, 0, -1.0);
  16836. uvs.push(1.0, 1.0);
  16837. positions.push(-halfSize, halfSize, 0);
  16838. normals.push(0, 0, -1.0);
  16839. uvs.push(0.0, 1.0);
  16840. indices.push(0);
  16841. indices.push(1);
  16842. indices.push(2);
  16843. indices.push(0);
  16844. indices.push(2);
  16845. indices.push(3);
  16846. var vertexData = new BABYLON.VertexData();
  16847. vertexData.indices = indices;
  16848. vertexData.positions = positions;
  16849. vertexData.normals = normals;
  16850. vertexData.uvs = uvs;
  16851. return vertexData;
  16852. };
  16853. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  16854. var indices = [];
  16855. var positions = [];
  16856. var normals = [];
  16857. var uvs = [];
  16858. radius = radius || 2;
  16859. tube = tube || 0.5;
  16860. radialSegments = radialSegments || 32;
  16861. tubularSegments = tubularSegments || 32;
  16862. p = p || 2;
  16863. q = q || 3;
  16864. var getPos = function (angle) {
  16865. var cu = Math.cos(angle);
  16866. var su = Math.sin(angle);
  16867. var quOverP = q / p * angle;
  16868. var cs = Math.cos(quOverP);
  16869. var tx = radius * (2 + cs) * 0.5 * cu;
  16870. var ty = radius * (2 + cs) * su * 0.5;
  16871. var tz = radius * Math.sin(quOverP) * 0.5;
  16872. return new BABYLON.Vector3(tx, ty, tz);
  16873. };
  16874. for (var i = 0; i <= radialSegments; i++) {
  16875. var modI = i % radialSegments;
  16876. var u = modI / radialSegments * 2 * p * Math.PI;
  16877. var p1 = getPos(u);
  16878. var p2 = getPos(u + 0.01);
  16879. var tang = p2.subtract(p1);
  16880. var n = p2.add(p1);
  16881. var bitan = BABYLON.Vector3.Cross(tang, n);
  16882. n = BABYLON.Vector3.Cross(bitan, tang);
  16883. bitan.normalize();
  16884. n.normalize();
  16885. for (var j = 0; j < tubularSegments; j++) {
  16886. var modJ = j % tubularSegments;
  16887. var v = modJ / tubularSegments * 2 * Math.PI;
  16888. var cx = -tube * Math.cos(v);
  16889. var cy = tube * Math.sin(v);
  16890. positions.push(p1.x + cx * n.x + cy * bitan.x);
  16891. positions.push(p1.y + cx * n.y + cy * bitan.y);
  16892. positions.push(p1.z + cx * n.z + cy * bitan.z);
  16893. uvs.push(i / radialSegments);
  16894. uvs.push(j / tubularSegments);
  16895. }
  16896. }
  16897. for (i = 0; i < radialSegments; i++) {
  16898. for (j = 0; j < tubularSegments; j++) {
  16899. var jNext = (j + 1) % tubularSegments;
  16900. var a = i * tubularSegments + j;
  16901. var b = (i + 1) * tubularSegments + j;
  16902. var c = (i + 1) * tubularSegments + jNext;
  16903. var d = i * tubularSegments + jNext;
  16904. indices.push(d);
  16905. indices.push(b);
  16906. indices.push(a);
  16907. indices.push(d);
  16908. indices.push(c);
  16909. indices.push(b);
  16910. }
  16911. }
  16912. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16913. var vertexData = new BABYLON.VertexData();
  16914. vertexData.indices = indices;
  16915. vertexData.positions = positions;
  16916. vertexData.normals = normals;
  16917. vertexData.uvs = uvs;
  16918. return vertexData;
  16919. };
  16920. VertexData.ComputeNormals = function (positions, indices, normals) {
  16921. var positionVectors = [];
  16922. var facesOfVertices = [];
  16923. var index;
  16924. for (index = 0; index < positions.length; index += 3) {
  16925. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  16926. positionVectors.push(vector3);
  16927. facesOfVertices.push([]);
  16928. }
  16929. var facesNormals = [];
  16930. for (index = 0; index < indices.length / 3; index++) {
  16931. var i1 = indices[index * 3];
  16932. var i2 = indices[index * 3 + 1];
  16933. var i3 = indices[index * 3 + 2];
  16934. var p1 = positionVectors[i1];
  16935. var p2 = positionVectors[i2];
  16936. var p3 = positionVectors[i3];
  16937. var p1p2 = p1.subtract(p2);
  16938. var p3p2 = p3.subtract(p2);
  16939. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  16940. facesOfVertices[i1].push(index);
  16941. facesOfVertices[i2].push(index);
  16942. facesOfVertices[i3].push(index);
  16943. }
  16944. for (index = 0; index < positionVectors.length; index++) {
  16945. var faces = facesOfVertices[index];
  16946. var normal = BABYLON.Vector3.Zero();
  16947. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  16948. normal.addInPlace(facesNormals[faces[faceIndex]]);
  16949. }
  16950. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  16951. normals[index * 3] = normal.x;
  16952. normals[index * 3 + 1] = normal.y;
  16953. normals[index * 3 + 2] = normal.z;
  16954. }
  16955. };
  16956. return VertexData;
  16957. })();
  16958. BABYLON.VertexData = VertexData;
  16959. })(BABYLON || (BABYLON = {}));
  16960. var __extends = this.__extends || function (d, b) {
  16961. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16962. function __() { this.constructor = d; }
  16963. __.prototype = b.prototype;
  16964. d.prototype = new __();
  16965. };
  16966. var BABYLON;
  16967. (function (BABYLON) {
  16968. var buildCamera = function (that, name) {
  16969. that._leftCamera.isIntermediate = true;
  16970. that.subCameras.push(that._leftCamera);
  16971. that.subCameras.push(that._rightCamera);
  16972. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  16973. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  16974. that._anaglyphPostProcess.onApply = function (effect) {
  16975. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  16976. };
  16977. that._update();
  16978. };
  16979. var AnaglyphArcRotateCamera = (function (_super) {
  16980. __extends(AnaglyphArcRotateCamera, _super);
  16981. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  16982. _super.call(this, name, alpha, beta, radius, target, scene);
  16983. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  16984. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  16985. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  16986. buildCamera(this, name);
  16987. }
  16988. AnaglyphArcRotateCamera.prototype._update = function () {
  16989. this._updateCamera(this._leftCamera);
  16990. this._updateCamera(this._rightCamera);
  16991. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  16992. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  16993. _super.prototype._update.call(this);
  16994. };
  16995. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  16996. camera.beta = this.beta;
  16997. camera.radius = this.radius;
  16998. camera.minZ = this.minZ;
  16999. camera.maxZ = this.maxZ;
  17000. camera.fov = this.fov;
  17001. camera.target = this.target;
  17002. };
  17003. return AnaglyphArcRotateCamera;
  17004. })(BABYLON.ArcRotateCamera);
  17005. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  17006. var AnaglyphFreeCamera = (function (_super) {
  17007. __extends(AnaglyphFreeCamera, _super);
  17008. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  17009. _super.call(this, name, position, scene);
  17010. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  17011. this._transformMatrix = new BABYLON.Matrix();
  17012. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  17013. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  17014. buildCamera(this, name);
  17015. }
  17016. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  17017. var target = this.getTarget();
  17018. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  17019. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  17020. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  17021. };
  17022. AnaglyphFreeCamera.prototype._update = function () {
  17023. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  17024. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  17025. this._updateCamera(this._leftCamera);
  17026. this._updateCamera(this._rightCamera);
  17027. _super.prototype._update.call(this);
  17028. };
  17029. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  17030. camera.minZ = this.minZ;
  17031. camera.maxZ = this.maxZ;
  17032. camera.fov = this.fov;
  17033. camera.viewport = this.viewport;
  17034. camera.setTarget(this.getTarget());
  17035. };
  17036. return AnaglyphFreeCamera;
  17037. })(BABYLON.FreeCamera);
  17038. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  17039. })(BABYLON || (BABYLON = {}));
  17040. var __extends = this.__extends || function (d, b) {
  17041. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17042. function __() { this.constructor = d; }
  17043. __.prototype = b.prototype;
  17044. d.prototype = new __();
  17045. };
  17046. var BABYLON;
  17047. (function (BABYLON) {
  17048. var AnaglyphPostProcess = (function (_super) {
  17049. __extends(AnaglyphPostProcess, _super);
  17050. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17051. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  17052. }
  17053. return AnaglyphPostProcess;
  17054. })(BABYLON.PostProcess);
  17055. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  17056. })(BABYLON || (BABYLON = {}));
  17057. var BABYLON;
  17058. (function (BABYLON) {
  17059. var Tags = (function () {
  17060. function Tags() {
  17061. }
  17062. Tags.EnableFor = function (obj) {
  17063. obj._tags = obj._tags || {};
  17064. obj.hasTags = function () {
  17065. return Tags.HasTags(obj);
  17066. };
  17067. obj.addTags = function (tagsString) {
  17068. return Tags.AddTagsTo(obj, tagsString);
  17069. };
  17070. obj.removeTags = function (tagsString) {
  17071. return Tags.RemoveTagsFrom(obj, tagsString);
  17072. };
  17073. obj.matchesTagsQuery = function (tagsQuery) {
  17074. return Tags.MatchesQuery(obj, tagsQuery);
  17075. };
  17076. };
  17077. Tags.DisableFor = function (obj) {
  17078. delete obj._tags;
  17079. delete obj.hasTags;
  17080. delete obj.addTags;
  17081. delete obj.removeTags;
  17082. delete obj.matchesTagsQuery;
  17083. };
  17084. Tags.HasTags = function (obj) {
  17085. if (!obj._tags) {
  17086. return false;
  17087. }
  17088. return !BABYLON.Tools.IsEmpty(obj._tags);
  17089. };
  17090. Tags.GetTags = function (obj) {
  17091. if (!obj._tags) {
  17092. return null;
  17093. }
  17094. return obj._tags;
  17095. };
  17096. Tags.AddTagsTo = function (obj, tagsString) {
  17097. if (!tagsString) {
  17098. return;
  17099. }
  17100. var tags = tagsString.split(" ");
  17101. for (var t in tags) {
  17102. Tags._AddTagTo(obj, tags[t]);
  17103. }
  17104. };
  17105. Tags._AddTagTo = function (obj, tag) {
  17106. tag = tag.trim();
  17107. if (tag === "" || tag === "true" || tag === "false") {
  17108. return;
  17109. }
  17110. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  17111. return;
  17112. }
  17113. Tags.EnableFor(obj);
  17114. obj._tags[tag] = true;
  17115. };
  17116. Tags.RemoveTagsFrom = function (obj, tagsString) {
  17117. if (!Tags.HasTags(obj)) {
  17118. return;
  17119. }
  17120. var tags = tagsString.split(" ");
  17121. for (var t in tags) {
  17122. Tags._RemoveTagFrom(obj, tags[t]);
  17123. }
  17124. };
  17125. Tags._RemoveTagFrom = function (obj, tag) {
  17126. delete obj._tags[tag];
  17127. };
  17128. Tags.MatchesQuery = function (obj, tagsQuery) {
  17129. if (tagsQuery === undefined) {
  17130. return true;
  17131. }
  17132. if (tagsQuery === "") {
  17133. return Tags.HasTags(obj);
  17134. }
  17135. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  17136. return Tags.HasTags(obj) && obj._tags[r];
  17137. });
  17138. };
  17139. return Tags;
  17140. })();
  17141. BABYLON.Tags = Tags;
  17142. })(BABYLON || (BABYLON = {}));
  17143. var BABYLON;
  17144. (function (BABYLON) {
  17145. (function (Internals) {
  17146. var AndOrNotEvaluator = (function () {
  17147. function AndOrNotEvaluator() {
  17148. }
  17149. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  17150. if (!query.match(/\([^\(\)]*\)/g)) {
  17151. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  17152. } else {
  17153. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  17154. r = r.slice(1, r.length - 1);
  17155. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  17156. });
  17157. }
  17158. if (query === "true") {
  17159. return true;
  17160. }
  17161. if (query === "false") {
  17162. return false;
  17163. }
  17164. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  17165. };
  17166. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  17167. evaluateCallback = evaluateCallback || (function (r) {
  17168. return r === "true" ? true : false;
  17169. });
  17170. var result;
  17171. var or = parenthesisContent.split("||");
  17172. for (var i in or) {
  17173. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  17174. var and = ori.split("&&");
  17175. if (and.length > 1) {
  17176. for (var j = 0; j < and.length; ++j) {
  17177. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  17178. if (andj !== "true" && andj !== "false") {
  17179. if (andj[0] === "!") {
  17180. result = !evaluateCallback(andj.substring(1));
  17181. } else {
  17182. result = evaluateCallback(andj);
  17183. }
  17184. } else {
  17185. result = andj === "true" ? true : false;
  17186. }
  17187. if (!result) {
  17188. ori = "false";
  17189. break;
  17190. }
  17191. }
  17192. }
  17193. if (result || ori === "true") {
  17194. result = true;
  17195. break;
  17196. }
  17197. if (ori !== "true" && ori !== "false") {
  17198. if (ori[0] === "!") {
  17199. result = !evaluateCallback(ori.substring(1));
  17200. } else {
  17201. result = evaluateCallback(ori);
  17202. }
  17203. } else {
  17204. result = ori === "true" ? true : false;
  17205. }
  17206. }
  17207. return result ? "true" : "false";
  17208. };
  17209. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  17210. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  17211. r = r.replace(/[\s]/g, function () {
  17212. return "";
  17213. });
  17214. return r.length % 2 ? "!" : "";
  17215. });
  17216. booleanString = booleanString.trim();
  17217. if (booleanString === "!true") {
  17218. booleanString = "false";
  17219. } else if (booleanString === "!false") {
  17220. booleanString = "true";
  17221. }
  17222. return booleanString;
  17223. };
  17224. return AndOrNotEvaluator;
  17225. })();
  17226. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  17227. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17228. var Internals = BABYLON.Internals;
  17229. })(BABYLON || (BABYLON = {}));
  17230. var BABYLON;
  17231. (function (BABYLON) {
  17232. var PostProcessRenderPass = (function () {
  17233. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  17234. this._enabled = true;
  17235. this._refCount = 0;
  17236. this._name = name;
  17237. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  17238. this.setRenderList(renderList);
  17239. this._renderTexture.onBeforeRender = beforeRender;
  17240. this._renderTexture.onAfterRender = afterRender;
  17241. this._scene = scene;
  17242. }
  17243. PostProcessRenderPass.prototype._incRefCount = function () {
  17244. if (this._refCount === 0) {
  17245. this._scene.customRenderTargets.push(this._renderTexture);
  17246. }
  17247. return ++this._refCount;
  17248. };
  17249. PostProcessRenderPass.prototype._decRefCount = function () {
  17250. this._refCount--;
  17251. if (this._refCount <= 0) {
  17252. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  17253. }
  17254. return this._refCount;
  17255. };
  17256. PostProcessRenderPass.prototype._update = function () {
  17257. this.setRenderList(this._renderList);
  17258. };
  17259. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  17260. this._renderTexture.renderList = renderList;
  17261. };
  17262. PostProcessRenderPass.prototype.getRenderTexture = function () {
  17263. return this._renderTexture;
  17264. };
  17265. return PostProcessRenderPass;
  17266. })();
  17267. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  17268. })(BABYLON || (BABYLON = {}));
  17269. var BABYLON;
  17270. (function (BABYLON) {
  17271. var PostProcessRenderEffect = (function () {
  17272. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  17273. this._engine = engine;
  17274. this._name = name;
  17275. this._singleInstance = singleInstance || true;
  17276. this._getPostProcess = getPostProcess;
  17277. this._cameras = [];
  17278. this._postProcesses = [];
  17279. this._indicesForCamera = [];
  17280. this._renderPasses = [];
  17281. this._renderEffectAsPasses = [];
  17282. }
  17283. PostProcessRenderEffect.prototype._update = function () {
  17284. for (var renderPassName in this._renderPasses) {
  17285. this._renderPasses[renderPassName]._update();
  17286. }
  17287. };
  17288. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  17289. this._renderPasses[renderPass._name] = renderPass;
  17290. this._linkParameters();
  17291. };
  17292. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  17293. delete this._renderPasses[renderPass._name];
  17294. this._linkParameters();
  17295. };
  17296. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  17297. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  17298. this._linkParameters();
  17299. };
  17300. PostProcessRenderEffect.prototype.getPass = function (passName) {
  17301. for (var renderPassName in this._renderPasses) {
  17302. if (renderPassName === passName) {
  17303. return this._renderPasses[passName];
  17304. }
  17305. }
  17306. };
  17307. PostProcessRenderEffect.prototype.emptyPasses = function () {
  17308. this._renderPasses.length = 0;
  17309. this._linkParameters();
  17310. };
  17311. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  17312. var cameraKey;
  17313. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17314. for (var i = 0; i < _cam.length; i++) {
  17315. var camera = _cam[i];
  17316. var cameraName = camera.name;
  17317. if (this._singleInstance) {
  17318. cameraKey = 0;
  17319. } else {
  17320. cameraKey = cameraName;
  17321. }
  17322. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  17323. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  17324. if (!this._indicesForCamera[cameraName]) {
  17325. this._indicesForCamera[cameraName] = [];
  17326. }
  17327. this._indicesForCamera[cameraName].push(index);
  17328. if (this._cameras.indexOf(camera) === -1) {
  17329. this._cameras[cameraName] = camera;
  17330. }
  17331. for (var passName in this._renderPasses) {
  17332. this._renderPasses[passName]._incRefCount();
  17333. }
  17334. }
  17335. this._linkParameters();
  17336. };
  17337. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  17338. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17339. for (var i = 0; i < _cam.length; i++) {
  17340. var camera = _cam[i];
  17341. var cameraName = camera.name;
  17342. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  17343. var index = this._cameras.indexOf(cameraName);
  17344. this._indicesForCamera.splice(index, 1);
  17345. this._cameras.splice(index, 1);
  17346. for (var passName in this._renderPasses) {
  17347. this._renderPasses[passName]._decRefCount();
  17348. }
  17349. }
  17350. };
  17351. PostProcessRenderEffect.prototype._enable = function (cameras) {
  17352. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17353. for (var i = 0; i < _cam.length; i++) {
  17354. var camera = _cam[i];
  17355. var cameraName = camera.name;
  17356. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  17357. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  17358. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  17359. }
  17360. }
  17361. for (var passName in this._renderPasses) {
  17362. this._renderPasses[passName]._incRefCount();
  17363. }
  17364. }
  17365. };
  17366. PostProcessRenderEffect.prototype._disable = function (cameras) {
  17367. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17368. for (var i = 0; i < _cam.length; i++) {
  17369. var camera = _cam[i];
  17370. var cameraName = camera.Name;
  17371. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  17372. for (var passName in this._renderPasses) {
  17373. this._renderPasses[passName]._decRefCount();
  17374. }
  17375. }
  17376. };
  17377. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  17378. if (this._singleInstance) {
  17379. return this._postProcesses[0];
  17380. } else {
  17381. return this._postProcesses[camera.name];
  17382. }
  17383. };
  17384. PostProcessRenderEffect.prototype._linkParameters = function () {
  17385. var _this = this;
  17386. for (var index in this._postProcesses) {
  17387. if (this.applyParameters) {
  17388. this.applyParameters(this._postProcesses[index]);
  17389. }
  17390. this._postProcesses[index].onBeforeRender = function (effect) {
  17391. _this._linkTextures(effect);
  17392. };
  17393. }
  17394. };
  17395. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  17396. for (var renderPassName in this._renderPasses) {
  17397. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  17398. }
  17399. for (var renderEffectName in this._renderEffectAsPasses) {
  17400. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  17401. }
  17402. };
  17403. return PostProcessRenderEffect;
  17404. })();
  17405. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  17406. })(BABYLON || (BABYLON = {}));
  17407. var BABYLON;
  17408. (function (BABYLON) {
  17409. var PostProcessRenderPipeline = (function () {
  17410. function PostProcessRenderPipeline(engine, name) {
  17411. this._engine = engine;
  17412. this._name = name;
  17413. this._renderEffects = [];
  17414. this._renderEffectsForIsolatedPass = [];
  17415. this._cameras = [];
  17416. }
  17417. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  17418. this._renderEffects[renderEffect._name] = renderEffect;
  17419. };
  17420. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  17421. var renderEffects = this._renderEffects[renderEffectName];
  17422. if (!renderEffects) {
  17423. return;
  17424. }
  17425. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  17426. };
  17427. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  17428. var renderEffects = this._renderEffects[renderEffectName];
  17429. if (!renderEffects) {
  17430. return;
  17431. }
  17432. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  17433. };
  17434. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  17435. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17436. var indicesToDelete = [];
  17437. for (var i = 0; i < _cam.length; i++) {
  17438. var camera = _cam[i];
  17439. var cameraName = camera.name;
  17440. if (this._cameras.indexOf(camera) === -1) {
  17441. this._cameras[cameraName] = camera;
  17442. } else if (unique) {
  17443. indicesToDelete.push(i);
  17444. }
  17445. }
  17446. for (var i = 0; i < indicesToDelete.length; i++) {
  17447. cameras.splice(indicesToDelete[i], 1);
  17448. }
  17449. for (var renderEffectName in this._renderEffects) {
  17450. this._renderEffects[renderEffectName]._attachCameras(_cam);
  17451. }
  17452. };
  17453. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  17454. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17455. for (var renderEffectName in this._renderEffects) {
  17456. this._renderEffects[renderEffectName]._detachCameras(_cam);
  17457. }
  17458. for (var i = 0; i < _cam.length; i++) {
  17459. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  17460. }
  17461. };
  17462. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  17463. var _this = this;
  17464. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17465. var pass = null;
  17466. for (var renderEffectName in this._renderEffects) {
  17467. pass = this._renderEffects[renderEffectName].getPass(passName);
  17468. if (pass != null) {
  17469. break;
  17470. }
  17471. }
  17472. if (pass === null) {
  17473. return;
  17474. }
  17475. for (var renderEffectName in this._renderEffects) {
  17476. this._renderEffects[renderEffectName]._disable(_cam);
  17477. }
  17478. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  17479. for (var i = 0; i < _cam.length; i++) {
  17480. var camera = _cam[i];
  17481. var cameraName = camera.name;
  17482. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  17483. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  17484. });
  17485. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  17486. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  17487. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  17488. }
  17489. };
  17490. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  17491. var _this = this;
  17492. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17493. for (var i = 0; i < _cam.length; i++) {
  17494. var camera = _cam[i];
  17495. var cameraName = camera.name;
  17496. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  17497. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  17498. });
  17499. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  17500. }
  17501. for (var renderEffectName in this._renderEffects) {
  17502. this._renderEffects[renderEffectName]._enable(_cam);
  17503. }
  17504. };
  17505. PostProcessRenderPipeline.prototype._update = function () {
  17506. for (var renderEffectName in this._renderEffects) {
  17507. this._renderEffects[renderEffectName]._update();
  17508. }
  17509. for (var i = 0; i < this._cameras.length; i++) {
  17510. var cameraName = this._cameras[i].name;
  17511. if (this._renderEffectsForIsolatedPass[cameraName]) {
  17512. this._renderEffectsForIsolatedPass[cameraName]._update();
  17513. }
  17514. }
  17515. };
  17516. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  17517. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  17518. return PostProcessRenderPipeline;
  17519. })();
  17520. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  17521. })(BABYLON || (BABYLON = {}));
  17522. var BABYLON;
  17523. (function (BABYLON) {
  17524. var PostProcessRenderPipelineManager = (function () {
  17525. function PostProcessRenderPipelineManager() {
  17526. this._renderPipelines = new Array();
  17527. }
  17528. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  17529. this._renderPipelines[renderPipeline._name] = renderPipeline;
  17530. };
  17531. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  17532. var renderPipeline = this._renderPipelines[renderPipelineName];
  17533. if (!renderPipeline) {
  17534. return;
  17535. }
  17536. renderPipeline._attachCameras(cameras, unique);
  17537. };
  17538. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  17539. var renderPipeline = this._renderPipelines[renderPipelineName];
  17540. if (!renderPipeline) {
  17541. return;
  17542. }
  17543. renderPipeline._detachCameras(cameras);
  17544. };
  17545. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  17546. var renderPipeline = this._renderPipelines[renderPipelineName];
  17547. if (!renderPipeline) {
  17548. return;
  17549. }
  17550. renderPipeline._enableEffect(renderEffectName, cameras);
  17551. };
  17552. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  17553. var renderPipeline = this._renderPipelines[renderPipelineName];
  17554. if (!renderPipeline) {
  17555. return;
  17556. }
  17557. renderPipeline._disableEffect(renderEffectName, cameras);
  17558. };
  17559. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  17560. var renderPipeline = this._renderPipelines[renderPipelineName];
  17561. if (!renderPipeline) {
  17562. return;
  17563. }
  17564. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  17565. };
  17566. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  17567. var renderPipeline = this._renderPipelines[renderPipelineName];
  17568. if (!renderPipeline) {
  17569. return;
  17570. }
  17571. renderPipeline._disableDisplayOnlyPass(cameras);
  17572. };
  17573. PostProcessRenderPipelineManager.prototype.update = function () {
  17574. for (var renderPipelineName in this._renderPipelines) {
  17575. this._renderPipelines[renderPipelineName]._update();
  17576. }
  17577. };
  17578. return PostProcessRenderPipelineManager;
  17579. })();
  17580. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  17581. })(BABYLON || (BABYLON = {}));
  17582. var __extends = this.__extends || function (d, b) {
  17583. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17584. function __() { this.constructor = d; }
  17585. __.prototype = b.prototype;
  17586. d.prototype = new __();
  17587. };
  17588. var BABYLON;
  17589. (function (BABYLON) {
  17590. var DisplayPassPostProcess = (function (_super) {
  17591. __extends(DisplayPassPostProcess, _super);
  17592. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17593. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  17594. }
  17595. return DisplayPassPostProcess;
  17596. })(BABYLON.PostProcess);
  17597. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  17598. })(BABYLON || (BABYLON = {}));
  17599. var BABYLON;
  17600. (function (BABYLON) {
  17601. var BoundingBoxRenderer = (function () {
  17602. function BoundingBoxRenderer(scene) {
  17603. this.frontColor = new BABYLON.Color3(1, 1, 1);
  17604. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  17605. this.showBackLines = true;
  17606. this.renderList = new BABYLON.SmartArray(32);
  17607. this._scene = scene;
  17608. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  17609. attributes: ["position"],
  17610. uniforms: ["worldViewProjection", "color"]
  17611. });
  17612. var engine = this._scene.getEngine();
  17613. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  17614. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  17615. 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]);
  17616. }
  17617. BoundingBoxRenderer.prototype.reset = function () {
  17618. this.renderList.reset();
  17619. };
  17620. BoundingBoxRenderer.prototype.render = function () {
  17621. if (this.renderList.length == 0 || !this._colorShader.isReady()) {
  17622. return;
  17623. }
  17624. var engine = this._scene.getEngine();
  17625. engine.setDepthWrite(false);
  17626. this._colorShader._preBind();
  17627. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  17628. var boundingBox = this.renderList.data[boundingBoxIndex];
  17629. var min = boundingBox.minimum;
  17630. var max = boundingBox.maximum;
  17631. var diff = max.subtract(min);
  17632. var median = min.add(diff.scale(0.5));
  17633. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  17634. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  17635. if (this.showBackLines) {
  17636. engine.setDepthFunctionToGreaterOrEqual();
  17637. this._colorShader.setColor4("color", this.backColor.toColor4());
  17638. this._colorShader.bind(worldMatrix);
  17639. engine.draw(false, 0, 24);
  17640. }
  17641. engine.setDepthFunctionToLess();
  17642. this._colorShader.setColor4("color", this.frontColor.toColor4());
  17643. this._colorShader.bind(worldMatrix);
  17644. engine.draw(false, 0, 24);
  17645. }
  17646. this._colorShader.unbind();
  17647. engine.setDepthFunctionToLessOrEqual();
  17648. engine.setDepthWrite(true);
  17649. };
  17650. BoundingBoxRenderer.prototype.dispose = function () {
  17651. this._colorShader.dispose();
  17652. this._vb.dispose();
  17653. this._scene.getEngine()._releaseBuffer(this._ib);
  17654. };
  17655. return BoundingBoxRenderer;
  17656. })();
  17657. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  17658. })(BABYLON || (BABYLON = {}));
  17659. /**
  17660. * Based on jsTGALoader - Javascript loader for TGA file
  17661. * By Vincent Thibault
  17662. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  17663. */
  17664. var BABYLON;
  17665. (function (BABYLON) {
  17666. (function (Internals) {
  17667. var TGATools = (function () {
  17668. function TGATools() {
  17669. }
  17670. TGATools.GetTGAHeader = function (data) {
  17671. var offset = 0;
  17672. var header = {
  17673. id_length: data[offset++],
  17674. colormap_type: data[offset++],
  17675. image_type: data[offset++],
  17676. colormap_index: data[offset++] | data[offset++] << 8,
  17677. colormap_length: data[offset++] | data[offset++] << 8,
  17678. colormap_size: data[offset++],
  17679. origin: [
  17680. data[offset++] | data[offset++] << 8,
  17681. data[offset++] | data[offset++] << 8
  17682. ],
  17683. width: data[offset++] | data[offset++] << 8,
  17684. height: data[offset++] | data[offset++] << 8,
  17685. pixel_size: data[offset++],
  17686. flags: data[offset++]
  17687. };
  17688. return header;
  17689. };
  17690. TGATools.UploadContent = function (gl, data) {
  17691. if (data.length < 19) {
  17692. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  17693. return;
  17694. }
  17695. var offset = 18;
  17696. var header = TGATools.GetTGAHeader(data);
  17697. if (header.id_length + offset > data.length) {
  17698. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  17699. return;
  17700. }
  17701. offset += header.id_length;
  17702. var use_rle = false;
  17703. var use_pal = false;
  17704. var use_rgb = false;
  17705. var use_grey = false;
  17706. switch (header.image_type) {
  17707. case TGATools._TYPE_RLE_INDEXED:
  17708. use_rle = true;
  17709. case TGATools._TYPE_INDEXED:
  17710. use_pal = true;
  17711. break;
  17712. case TGATools._TYPE_RLE_RGB:
  17713. use_rle = true;
  17714. case TGATools._TYPE_RGB:
  17715. use_rgb = true;
  17716. break;
  17717. case TGATools._TYPE_RLE_GREY:
  17718. use_rle = true;
  17719. case TGATools._TYPE_GREY:
  17720. use_grey = true;
  17721. break;
  17722. }
  17723. var pixel_data;
  17724. var numAlphaBits = header.flags & 0xf;
  17725. var pixel_size = header.pixel_size >> 3;
  17726. var pixel_total = header.width * header.height * pixel_size;
  17727. var palettes;
  17728. if (use_pal) {
  17729. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  17730. }
  17731. if (use_rle) {
  17732. pixel_data = new Uint8Array(pixel_total);
  17733. var c, count, i;
  17734. var localOffset = 0;
  17735. var pixels = new Uint8Array(pixel_size);
  17736. while (offset < pixel_total && localOffset < pixel_total) {
  17737. c = data[offset++];
  17738. count = (c & 0x7f) + 1;
  17739. if (c & 0x80) {
  17740. for (i = 0; i < pixel_size; ++i) {
  17741. pixels[i] = data[offset++];
  17742. }
  17743. for (i = 0; i < count; ++i) {
  17744. pixel_data.set(pixels, localOffset + i * pixel_size);
  17745. }
  17746. localOffset += pixel_size * count;
  17747. } else {
  17748. count *= pixel_size;
  17749. for (i = 0; i < count; ++i) {
  17750. pixel_data[localOffset + i] = data[offset++];
  17751. }
  17752. localOffset += count;
  17753. }
  17754. }
  17755. } else {
  17756. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  17757. }
  17758. var x_start, y_start, x_step, y_step, y_end, x_end;
  17759. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  17760. default:
  17761. case TGATools._ORIGIN_UL:
  17762. x_start = 0;
  17763. x_step = 1;
  17764. x_end = header.width;
  17765. y_start = 0;
  17766. y_step = 1;
  17767. y_end = header.height;
  17768. break;
  17769. case TGATools._ORIGIN_BL:
  17770. x_start = 0;
  17771. x_step = 1;
  17772. x_end = header.width;
  17773. y_start = header.height - 1;
  17774. y_step = -1;
  17775. y_end = -1;
  17776. break;
  17777. case TGATools._ORIGIN_UR:
  17778. x_start = header.width - 1;
  17779. x_step = -1;
  17780. x_end = -1;
  17781. y_start = 0;
  17782. y_step = 1;
  17783. y_end = header.height;
  17784. break;
  17785. case TGATools._ORIGIN_BR:
  17786. x_start = header.width - 1;
  17787. x_step = -1;
  17788. x_end = -1;
  17789. y_start = header.height - 1;
  17790. y_step = -1;
  17791. y_end = -1;
  17792. break;
  17793. }
  17794. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  17795. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  17796. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  17797. };
  17798. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17799. var image = pixel_data, colormap = palettes;
  17800. var width = header.width, height = header.height;
  17801. var color, i = 0, x, y;
  17802. var imageData = new Uint8Array(width * height * 4);
  17803. for (y = y_start; y !== y_end; y += y_step) {
  17804. for (x = x_start; x !== x_end; x += x_step, i++) {
  17805. color = image[i];
  17806. imageData[(x + width * y) * 4 + 3] = 255;
  17807. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  17808. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  17809. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  17810. }
  17811. }
  17812. return imageData;
  17813. };
  17814. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17815. var image = pixel_data;
  17816. var width = header.width, height = header.height;
  17817. var color, i = 0, x, y;
  17818. var imageData = new Uint8Array(width * height * 4);
  17819. for (y = y_start; y !== y_end; y += y_step) {
  17820. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  17821. color = image[i + 0] + (image[i + 1] << 8);
  17822. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  17823. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  17824. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  17825. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  17826. }
  17827. }
  17828. return imageData;
  17829. };
  17830. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17831. var image = pixel_data;
  17832. var width = header.width, height = header.height;
  17833. var i = 0, x, y;
  17834. var imageData = new Uint8Array(width * height * 4);
  17835. for (y = y_start; y !== y_end; y += y_step) {
  17836. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  17837. imageData[(x + width * y) * 4 + 3] = 255;
  17838. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17839. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  17840. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  17841. }
  17842. }
  17843. return imageData;
  17844. };
  17845. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17846. var image = pixel_data;
  17847. var width = header.width, height = header.height;
  17848. var i = 0, x, y;
  17849. var imageData = new Uint8Array(width * height * 4);
  17850. for (y = y_start; y !== y_end; y += y_step) {
  17851. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  17852. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17853. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  17854. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  17855. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  17856. }
  17857. }
  17858. return imageData;
  17859. };
  17860. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17861. var image = pixel_data;
  17862. var width = header.width, height = header.height;
  17863. var color, i = 0, x, y;
  17864. var imageData = new Uint8Array(width * height * 4);
  17865. for (y = y_start; y !== y_end; y += y_step) {
  17866. for (x = x_start; x !== x_end; x += x_step, i++) {
  17867. color = image[i];
  17868. imageData[(x + width * y) * 4 + 0] = color;
  17869. imageData[(x + width * y) * 4 + 1] = color;
  17870. imageData[(x + width * y) * 4 + 2] = color;
  17871. imageData[(x + width * y) * 4 + 3] = 255;
  17872. }
  17873. }
  17874. return imageData;
  17875. };
  17876. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17877. var image = pixel_data;
  17878. var width = header.width, height = header.height;
  17879. var i = 0, x, y;
  17880. var imageData = new Uint8Array(width * height * 4);
  17881. for (y = y_start; y !== y_end; y += y_step) {
  17882. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  17883. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  17884. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  17885. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17886. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  17887. }
  17888. }
  17889. return imageData;
  17890. };
  17891. TGATools._TYPE_NO_DATA = 0;
  17892. TGATools._TYPE_INDEXED = 1;
  17893. TGATools._TYPE_RGB = 2;
  17894. TGATools._TYPE_GREY = 3;
  17895. TGATools._TYPE_RLE_INDEXED = 9;
  17896. TGATools._TYPE_RLE_RGB = 10;
  17897. TGATools._TYPE_RLE_GREY = 11;
  17898. TGATools._ORIGIN_MASK = 0x30;
  17899. TGATools._ORIGIN_SHIFT = 0x04;
  17900. TGATools._ORIGIN_BL = 0x00;
  17901. TGATools._ORIGIN_BR = 0x01;
  17902. TGATools._ORIGIN_UL = 0x02;
  17903. TGATools._ORIGIN_UR = 0x03;
  17904. return TGATools;
  17905. })();
  17906. Internals.TGATools = TGATools;
  17907. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17908. var Internals = BABYLON.Internals;
  17909. })(BABYLON || (BABYLON = {}));
  17910. var BABYLON;
  17911. (function (BABYLON) {
  17912. (function (Internals) {
  17913. var DDS_MAGIC = 0x20534444;
  17914. 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;
  17915. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  17916. 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;
  17917. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  17918. function FourCCToInt32(value) {
  17919. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  17920. }
  17921. function Int32ToFourCC(value) {
  17922. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  17923. }
  17924. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  17925. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  17926. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  17927. var headerLengthInt = 31;
  17928. var off_magic = 0;
  17929. var off_size = 1;
  17930. var off_flags = 2;
  17931. var off_height = 3;
  17932. var off_width = 4;
  17933. var off_mipmapCount = 7;
  17934. var off_pfFlags = 20;
  17935. var off_pfFourCC = 21;
  17936. var off_RGBbpp = 22;
  17937. var off_RMask = 23;
  17938. var off_GMask = 24;
  17939. var off_BMask = 25;
  17940. var off_AMask = 26;
  17941. var off_caps1 = 27;
  17942. var off_caps2 = 28;
  17943. ;
  17944. var DDSTools = (function () {
  17945. function DDSTools() {
  17946. }
  17947. DDSTools.GetDDSInfo = function (arrayBuffer) {
  17948. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  17949. var mipmapCount = 1;
  17950. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  17951. mipmapCount = Math.max(1, header[off_mipmapCount]);
  17952. }
  17953. return {
  17954. width: header[off_width],
  17955. height: header[off_height],
  17956. mipmapCount: mipmapCount,
  17957. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  17958. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  17959. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  17960. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  17961. };
  17962. };
  17963. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17964. var byteArray = new Uint8Array(dataLength);
  17965. var srcData = new Uint8Array(arrayBuffer);
  17966. var index = 0;
  17967. for (var y = height - 1; y >= 0; y--) {
  17968. for (var x = 0; x < width; x++) {
  17969. var srcPos = dataOffset + (x + y * width) * 4;
  17970. byteArray[index + 2] = srcData[srcPos];
  17971. byteArray[index + 1] = srcData[srcPos + 1];
  17972. byteArray[index] = srcData[srcPos + 2];
  17973. byteArray[index + 3] = srcData[srcPos + 3];
  17974. index += 4;
  17975. }
  17976. }
  17977. return byteArray;
  17978. };
  17979. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17980. var byteArray = new Uint8Array(dataLength);
  17981. var srcData = new Uint8Array(arrayBuffer);
  17982. var index = 0;
  17983. for (var y = height - 1; y >= 0; y--) {
  17984. for (var x = 0; x < width; x++) {
  17985. var srcPos = dataOffset + (x + y * width) * 3;
  17986. byteArray[index + 2] = srcData[srcPos];
  17987. byteArray[index + 1] = srcData[srcPos + 1];
  17988. byteArray[index] = srcData[srcPos + 2];
  17989. index += 3;
  17990. }
  17991. }
  17992. return byteArray;
  17993. };
  17994. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17995. var byteArray = new Uint8Array(dataLength);
  17996. var srcData = new Uint8Array(arrayBuffer);
  17997. var index = 0;
  17998. for (var y = height - 1; y >= 0; y--) {
  17999. for (var x = 0; x < width; x++) {
  18000. var srcPos = dataOffset + (x + y * width);
  18001. byteArray[index] = srcData[srcPos];
  18002. index++;
  18003. }
  18004. }
  18005. return byteArray;
  18006. };
  18007. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  18008. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  18009. if (header[off_magic] != DDS_MAGIC) {
  18010. BABYLON.Tools.Error("Invalid magic number in DDS header");
  18011. return;
  18012. }
  18013. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  18014. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  18015. return;
  18016. }
  18017. if (info.isFourCC) {
  18018. fourCC = header[off_pfFourCC];
  18019. switch (fourCC) {
  18020. case FOURCC_DXT1:
  18021. blockBytes = 8;
  18022. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  18023. break;
  18024. case FOURCC_DXT3:
  18025. blockBytes = 16;
  18026. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  18027. break;
  18028. case FOURCC_DXT5:
  18029. blockBytes = 16;
  18030. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  18031. break;
  18032. default:
  18033. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  18034. return;
  18035. }
  18036. }
  18037. mipmapCount = 1;
  18038. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  18039. mipmapCount = Math.max(1, header[off_mipmapCount]);
  18040. }
  18041. var bpp = header[off_RGBbpp];
  18042. for (var face = 0; face < faces; face++) {
  18043. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  18044. width = header[off_width];
  18045. height = header[off_height];
  18046. dataOffset = header[off_size] + 4;
  18047. for (i = 0; i < mipmapCount; ++i) {
  18048. if (info.isRGB) {
  18049. if (bpp == 24) {
  18050. dataLength = width * height * 3;
  18051. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  18052. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  18053. } else {
  18054. dataLength = width * height * 4;
  18055. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  18056. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  18057. }
  18058. } else if (info.isLuminance) {
  18059. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  18060. var unpaddedRowSize = width;
  18061. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  18062. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  18063. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  18064. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  18065. } else {
  18066. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  18067. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  18068. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  18069. }
  18070. dataOffset += dataLength;
  18071. width *= 0.5;
  18072. height *= 0.5;
  18073. width = Math.max(1.0, width);
  18074. height = Math.max(1.0, height);
  18075. }
  18076. }
  18077. };
  18078. return DDSTools;
  18079. })();
  18080. Internals.DDSTools = DDSTools;
  18081. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18082. var Internals = BABYLON.Internals;
  18083. })(BABYLON || (BABYLON = {}));
  18084. var BABYLON;
  18085. (function (BABYLON) {
  18086. var SmartArray = (function () {
  18087. function SmartArray(capacity) {
  18088. this.length = 0;
  18089. this._duplicateId = 0;
  18090. this.data = new Array(capacity);
  18091. this._id = SmartArray._GlobalId++;
  18092. }
  18093. SmartArray.prototype.push = function (value) {
  18094. this.data[this.length++] = value;
  18095. if (this.length > this.data.length) {
  18096. this.data.length *= 2;
  18097. }
  18098. if (!value.__smartArrayFlags) {
  18099. value.__smartArrayFlags = {};
  18100. }
  18101. value.__smartArrayFlags[this._id] = this._duplicateId;
  18102. };
  18103. SmartArray.prototype.pushNoDuplicate = function (value) {
  18104. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  18105. return;
  18106. }
  18107. this.push(value);
  18108. };
  18109. SmartArray.prototype.sort = function (compareFn) {
  18110. this.data.sort(compareFn);
  18111. };
  18112. SmartArray.prototype.reset = function () {
  18113. this.length = 0;
  18114. this._duplicateId++;
  18115. };
  18116. SmartArray.prototype.concat = function (array) {
  18117. if (array.length === 0) {
  18118. return;
  18119. }
  18120. if (this.length + array.length > this.data.length) {
  18121. this.data.length = (this.length + array.length) * 2;
  18122. }
  18123. for (var index = 0; index < array.length; index++) {
  18124. this.data[this.length++] = (array.data || array)[index];
  18125. }
  18126. };
  18127. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  18128. if (array.length === 0) {
  18129. return;
  18130. }
  18131. if (this.length + array.length > this.data.length) {
  18132. this.data.length = (this.length + array.length) * 2;
  18133. }
  18134. for (var index = 0; index < array.length; index++) {
  18135. var item = (array.data || array)[index];
  18136. this.pushNoDuplicate(item);
  18137. }
  18138. };
  18139. SmartArray.prototype.indexOf = function (value) {
  18140. var position = this.data.indexOf(value);
  18141. if (position >= this.length) {
  18142. return -1;
  18143. }
  18144. return position;
  18145. };
  18146. SmartArray._GlobalId = 0;
  18147. return SmartArray;
  18148. })();
  18149. BABYLON.SmartArray = SmartArray;
  18150. })(BABYLON || (BABYLON = {}));
  18151. var BABYLON;
  18152. (function (BABYLON) {
  18153. var CannonJSPlugin = (function () {
  18154. function CannonJSPlugin() {
  18155. this._registeredMeshes = [];
  18156. this._physicsMaterials = [];
  18157. this.updateBodyPosition = function (mesh) {
  18158. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18159. var registeredMesh = this._registeredMeshes[index];
  18160. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18161. var body = registeredMesh.body.body;
  18162. var center = mesh.getBoundingInfo().boundingBox.center;
  18163. body.position.set(center.x, center.z, center.y);
  18164. body.quaternion.x = mesh.rotationQuaternion.x;
  18165. body.quaternion.z = mesh.rotationQuaternion.y;
  18166. body.quaternion.y = mesh.rotationQuaternion.z;
  18167. body.quaternion.w = -mesh.rotationQuaternion.w;
  18168. return;
  18169. }
  18170. }
  18171. };
  18172. }
  18173. CannonJSPlugin.prototype.initialize = function (iterations) {
  18174. if (typeof iterations === "undefined") { iterations = 10; }
  18175. this._world = new CANNON.World();
  18176. this._world.broadphase = new CANNON.NaiveBroadphase();
  18177. this._world.solver.iterations = iterations;
  18178. };
  18179. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  18180. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  18181. };
  18182. CannonJSPlugin.prototype.runOneStep = function (delta) {
  18183. this._world.step(delta);
  18184. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18185. var registeredMesh = this._registeredMeshes[index];
  18186. if (registeredMesh.isChild) {
  18187. continue;
  18188. }
  18189. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  18190. var deltaPos = registeredMesh.delta;
  18191. if (deltaPos) {
  18192. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  18193. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  18194. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  18195. } else {
  18196. registeredMesh.mesh.position.x = bodyX;
  18197. registeredMesh.mesh.position.y = bodyZ;
  18198. registeredMesh.mesh.position.z = bodyY;
  18199. }
  18200. if (!registeredMesh.mesh.rotationQuaternion) {
  18201. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18202. }
  18203. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  18204. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  18205. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  18206. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  18207. }
  18208. };
  18209. CannonJSPlugin.prototype.setGravity = function (gravity) {
  18210. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  18211. };
  18212. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  18213. this.unregisterMesh(mesh);
  18214. mesh.computeWorldMatrix(true);
  18215. switch (impostor) {
  18216. case BABYLON.PhysicsEngine.SphereImpostor:
  18217. var bbox = mesh.getBoundingInfo().boundingBox;
  18218. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18219. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18220. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18221. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  18222. case BABYLON.PhysicsEngine.BoxImpostor:
  18223. bbox = mesh.getBoundingInfo().boundingBox;
  18224. var min = bbox.minimumWorld;
  18225. var max = bbox.maximumWorld;
  18226. var box = max.subtract(min).scale(0.5);
  18227. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  18228. case BABYLON.PhysicsEngine.PlaneImpostor:
  18229. return this._createPlane(mesh, options);
  18230. case BABYLON.PhysicsEngine.MeshImpostor:
  18231. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18232. var rawFaces = mesh.getIndices();
  18233. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  18234. }
  18235. return null;
  18236. };
  18237. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  18238. var shape = new CANNON.Sphere(radius);
  18239. if (!options) {
  18240. return shape;
  18241. }
  18242. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18243. };
  18244. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  18245. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  18246. if (!options) {
  18247. return shape;
  18248. }
  18249. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18250. };
  18251. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  18252. var shape = new CANNON.Plane();
  18253. if (!options) {
  18254. return shape;
  18255. }
  18256. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18257. };
  18258. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  18259. var verts = [], faces = [];
  18260. mesh.computeWorldMatrix(true);
  18261. for (var i = 0; i < rawVerts.length; i += 3) {
  18262. var transformed = BABYLON.Vector3.Zero();
  18263. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  18264. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  18265. }
  18266. for (var j = 0; j < rawFaces.length; j += 3) {
  18267. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  18268. }
  18269. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  18270. if (!options) {
  18271. return shape;
  18272. }
  18273. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18274. };
  18275. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  18276. var index;
  18277. var mat;
  18278. for (index = 0; index < this._physicsMaterials.length; index++) {
  18279. mat = this._physicsMaterials[index];
  18280. if (mat.friction === friction && mat.restitution === restitution) {
  18281. return mat;
  18282. }
  18283. }
  18284. var currentMat = new CANNON.Material();
  18285. currentMat.friction = friction;
  18286. currentMat.restitution = restitution;
  18287. this._physicsMaterials.push(currentMat);
  18288. for (index = 0; index < this._physicsMaterials.length; index++) {
  18289. mat = this._physicsMaterials[index];
  18290. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  18291. contactMaterial.contactEquationStiffness = 1e10;
  18292. contactMaterial.contactEquationRegularizationTime = 10;
  18293. this._world.addContactMaterial(contactMaterial);
  18294. }
  18295. return currentMat;
  18296. };
  18297. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  18298. var initialRotation = null;
  18299. if (mesh.rotationQuaternion) {
  18300. initialRotation = mesh.rotationQuaternion.clone();
  18301. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18302. }
  18303. var bbox = mesh.getBoundingInfo().boundingBox;
  18304. var deltaPosition = mesh.position.subtract(bbox.center);
  18305. var material = this._addMaterial(friction, restitution);
  18306. var body = new CANNON.RigidBody(mass, shape, material);
  18307. if (initialRotation) {
  18308. body.quaternion.x = initialRotation.x;
  18309. body.quaternion.z = initialRotation.y;
  18310. body.quaternion.y = initialRotation.z;
  18311. body.quaternion.w = -initialRotation.w;
  18312. }
  18313. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  18314. this._world.add(body);
  18315. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  18316. return body;
  18317. };
  18318. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  18319. var compoundShape = new CANNON.Compound();
  18320. for (var index = 0; index < parts.length; index++) {
  18321. var mesh = parts[index].mesh;
  18322. var shape = this.registerMesh(mesh, parts[index].impostor);
  18323. if (index == 0) {
  18324. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  18325. } else {
  18326. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  18327. }
  18328. }
  18329. var initialMesh = parts[0].mesh;
  18330. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  18331. body.parts = parts;
  18332. return body;
  18333. };
  18334. CannonJSPlugin.prototype._unbindBody = function (body) {
  18335. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18336. var registeredMesh = this._registeredMeshes[index];
  18337. if (registeredMesh.body === body) {
  18338. registeredMesh.body = null;
  18339. registeredMesh.delta = 0;
  18340. }
  18341. }
  18342. };
  18343. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  18344. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18345. var registeredMesh = this._registeredMeshes[index];
  18346. if (registeredMesh.mesh === mesh) {
  18347. if (registeredMesh.body) {
  18348. this._world.remove(registeredMesh.body);
  18349. this._unbindBody(registeredMesh.body);
  18350. }
  18351. this._registeredMeshes.splice(index, 1);
  18352. return;
  18353. }
  18354. }
  18355. };
  18356. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  18357. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  18358. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  18359. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18360. var registeredMesh = this._registeredMeshes[index];
  18361. if (registeredMesh.mesh === mesh) {
  18362. registeredMesh.body.applyImpulse(impulse, worldPoint);
  18363. return;
  18364. }
  18365. }
  18366. };
  18367. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  18368. var body1 = null, body2 = null;
  18369. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18370. var registeredMesh = this._registeredMeshes[index];
  18371. if (registeredMesh.mesh === mesh1) {
  18372. body1 = registeredMesh.body;
  18373. } else if (registeredMesh.mesh === mesh2) {
  18374. body2 = registeredMesh.body;
  18375. }
  18376. }
  18377. if (!body1 || !body2) {
  18378. return false;
  18379. }
  18380. 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));
  18381. this._world.addConstraint(constraint);
  18382. return true;
  18383. };
  18384. CannonJSPlugin.prototype.dispose = function () {
  18385. while (this._registeredMeshes.length) {
  18386. this.unregisterMesh(this._registeredMeshes[0].mesh);
  18387. }
  18388. };
  18389. CannonJSPlugin.prototype.isSupported = function () {
  18390. return window.CANNON !== undefined;
  18391. };
  18392. return CannonJSPlugin;
  18393. })();
  18394. BABYLON.CannonJSPlugin = CannonJSPlugin;
  18395. })(BABYLON || (BABYLON = {}));
  18396. var __extends = this.__extends || function (d, b) {
  18397. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18398. function __() { this.constructor = d; }
  18399. __.prototype = b.prototype;
  18400. d.prototype = new __();
  18401. };
  18402. var BABYLON;
  18403. (function (BABYLON) {
  18404. var Condition = (function () {
  18405. function Condition(actionManager) {
  18406. this._actionManager = actionManager;
  18407. }
  18408. Condition.prototype.isValid = function () {
  18409. return true;
  18410. };
  18411. Condition.prototype._getProperty = function (propertyPath) {
  18412. return this._actionManager._getProperty(propertyPath);
  18413. };
  18414. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  18415. return this._actionManager._getEffectiveTarget(target, propertyPath);
  18416. };
  18417. return Condition;
  18418. })();
  18419. BABYLON.Condition = Condition;
  18420. var ValueCondition = (function (_super) {
  18421. __extends(ValueCondition, _super);
  18422. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  18423. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  18424. _super.call(this, actionManager);
  18425. this.propertyPath = propertyPath;
  18426. this.value = value;
  18427. this.operator = operator;
  18428. this._target = this._getEffectiveTarget(target, this.propertyPath);
  18429. this._property = this._getProperty(this.propertyPath);
  18430. }
  18431. Object.defineProperty(ValueCondition, "IsEqual", {
  18432. get: function () {
  18433. return ValueCondition._IsEqual;
  18434. },
  18435. enumerable: true,
  18436. configurable: true
  18437. });
  18438. Object.defineProperty(ValueCondition, "IsDifferent", {
  18439. get: function () {
  18440. return ValueCondition._IsDifferent;
  18441. },
  18442. enumerable: true,
  18443. configurable: true
  18444. });
  18445. Object.defineProperty(ValueCondition, "IsGreater", {
  18446. get: function () {
  18447. return ValueCondition._IsGreater;
  18448. },
  18449. enumerable: true,
  18450. configurable: true
  18451. });
  18452. Object.defineProperty(ValueCondition, "IsLesser", {
  18453. get: function () {
  18454. return ValueCondition._IsLesser;
  18455. },
  18456. enumerable: true,
  18457. configurable: true
  18458. });
  18459. ValueCondition.prototype.isValid = function () {
  18460. switch (this.operator) {
  18461. case ValueCondition.IsGreater:
  18462. return this._target[this._property] > this.value;
  18463. case ValueCondition.IsLesser:
  18464. return this._target[this._property] < this.value;
  18465. case ValueCondition.IsEqual:
  18466. case ValueCondition.IsDifferent:
  18467. var check;
  18468. if (this.value.equals) {
  18469. check = this.value.equals(this._target[this._property]);
  18470. } else {
  18471. check = this.value === this._target[this._property];
  18472. }
  18473. return this.operator === ValueCondition.IsEqual ? check : !check;
  18474. }
  18475. return false;
  18476. };
  18477. ValueCondition._IsEqual = 0;
  18478. ValueCondition._IsDifferent = 1;
  18479. ValueCondition._IsGreater = 2;
  18480. ValueCondition._IsLesser = 3;
  18481. return ValueCondition;
  18482. })(Condition);
  18483. BABYLON.ValueCondition = ValueCondition;
  18484. var PredicateCondition = (function (_super) {
  18485. __extends(PredicateCondition, _super);
  18486. function PredicateCondition(actionManager, predicate) {
  18487. _super.call(this, actionManager);
  18488. this.predicate = predicate;
  18489. }
  18490. PredicateCondition.prototype.isValid = function () {
  18491. return this.predicate();
  18492. };
  18493. return PredicateCondition;
  18494. })(Condition);
  18495. BABYLON.PredicateCondition = PredicateCondition;
  18496. var StateCondition = (function (_super) {
  18497. __extends(StateCondition, _super);
  18498. function StateCondition(actionManager, target, value) {
  18499. _super.call(this, actionManager);
  18500. this.value = value;
  18501. this._target = target;
  18502. }
  18503. StateCondition.prototype.isValid = function () {
  18504. return this._target.state === this.value;
  18505. };
  18506. return StateCondition;
  18507. })(Condition);
  18508. BABYLON.StateCondition = StateCondition;
  18509. })(BABYLON || (BABYLON = {}));
  18510. var BABYLON;
  18511. (function (BABYLON) {
  18512. var Action = (function () {
  18513. function Action(triggerOptions, condition) {
  18514. this.triggerOptions = triggerOptions;
  18515. if (triggerOptions.parameter) {
  18516. this.trigger = triggerOptions.trigger;
  18517. this._triggerParameter = triggerOptions.parameter;
  18518. } else {
  18519. this.trigger = triggerOptions;
  18520. }
  18521. this._nextActiveAction = this;
  18522. this._condition = condition;
  18523. }
  18524. Action.prototype._prepare = function () {
  18525. };
  18526. Action.prototype.getTriggerParameter = function () {
  18527. return this._triggerParameter;
  18528. };
  18529. Action.prototype._executeCurrent = function (evt) {
  18530. if (this._condition) {
  18531. var currentRenderId = this._actionManager.getScene().getRenderId();
  18532. if (this._condition._evaluationId === currentRenderId) {
  18533. if (!this._condition._currentResult) {
  18534. return;
  18535. }
  18536. } else {
  18537. this._condition._evaluationId = currentRenderId;
  18538. if (!this._condition.isValid()) {
  18539. this._condition._currentResult = false;
  18540. return;
  18541. }
  18542. this._condition._currentResult = true;
  18543. }
  18544. }
  18545. this._nextActiveAction.execute(evt);
  18546. if (this._nextActiveAction._child) {
  18547. if (!this._nextActiveAction._child._actionManager) {
  18548. this._nextActiveAction._child._actionManager = this._actionManager;
  18549. }
  18550. this._nextActiveAction = this._nextActiveAction._child;
  18551. } else {
  18552. this._nextActiveAction = this;
  18553. }
  18554. };
  18555. Action.prototype.execute = function (evt) {
  18556. };
  18557. Action.prototype.then = function (action) {
  18558. this._child = action;
  18559. action._actionManager = this._actionManager;
  18560. action._prepare();
  18561. return action;
  18562. };
  18563. Action.prototype._getProperty = function (propertyPath) {
  18564. return this._actionManager._getProperty(propertyPath);
  18565. };
  18566. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  18567. return this._actionManager._getEffectiveTarget(target, propertyPath);
  18568. };
  18569. return Action;
  18570. })();
  18571. BABYLON.Action = Action;
  18572. })(BABYLON || (BABYLON = {}));
  18573. var BABYLON;
  18574. (function (BABYLON) {
  18575. var ActionEvent = (function () {
  18576. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  18577. this.source = source;
  18578. this.pointerX = pointerX;
  18579. this.pointerY = pointerY;
  18580. this.meshUnderPointer = meshUnderPointer;
  18581. this.sourceEvent = sourceEvent;
  18582. }
  18583. ActionEvent.CreateNew = function (source) {
  18584. var scene = source.getScene();
  18585. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer);
  18586. };
  18587. ActionEvent.CreateNewFromScene = function (scene, evt) {
  18588. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  18589. };
  18590. return ActionEvent;
  18591. })();
  18592. BABYLON.ActionEvent = ActionEvent;
  18593. var ActionManager = (function () {
  18594. function ActionManager(scene) {
  18595. this.actions = new Array();
  18596. this._scene = scene;
  18597. scene._actionManagers.push(this);
  18598. }
  18599. Object.defineProperty(ActionManager, "NothingTrigger", {
  18600. get: function () {
  18601. return ActionManager._NothingTrigger;
  18602. },
  18603. enumerable: true,
  18604. configurable: true
  18605. });
  18606. Object.defineProperty(ActionManager, "OnPickTrigger", {
  18607. get: function () {
  18608. return ActionManager._OnPickTrigger;
  18609. },
  18610. enumerable: true,
  18611. configurable: true
  18612. });
  18613. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  18614. get: function () {
  18615. return ActionManager._OnLeftPickTrigger;
  18616. },
  18617. enumerable: true,
  18618. configurable: true
  18619. });
  18620. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  18621. get: function () {
  18622. return ActionManager._OnRightPickTrigger;
  18623. },
  18624. enumerable: true,
  18625. configurable: true
  18626. });
  18627. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  18628. get: function () {
  18629. return ActionManager._OnCenterPickTrigger;
  18630. },
  18631. enumerable: true,
  18632. configurable: true
  18633. });
  18634. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  18635. get: function () {
  18636. return ActionManager._OnPointerOverTrigger;
  18637. },
  18638. enumerable: true,
  18639. configurable: true
  18640. });
  18641. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  18642. get: function () {
  18643. return ActionManager._OnPointerOutTrigger;
  18644. },
  18645. enumerable: true,
  18646. configurable: true
  18647. });
  18648. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  18649. get: function () {
  18650. return ActionManager._OnEveryFrameTrigger;
  18651. },
  18652. enumerable: true,
  18653. configurable: true
  18654. });
  18655. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  18656. get: function () {
  18657. return ActionManager._OnIntersectionEnterTrigger;
  18658. },
  18659. enumerable: true,
  18660. configurable: true
  18661. });
  18662. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  18663. get: function () {
  18664. return ActionManager._OnIntersectionExitTrigger;
  18665. },
  18666. enumerable: true,
  18667. configurable: true
  18668. });
  18669. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  18670. get: function () {
  18671. return ActionManager._OnKeyDownTrigger;
  18672. },
  18673. enumerable: true,
  18674. configurable: true
  18675. });
  18676. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  18677. get: function () {
  18678. return ActionManager._OnKeyUpTrigger;
  18679. },
  18680. enumerable: true,
  18681. configurable: true
  18682. });
  18683. ActionManager.prototype.dispose = function () {
  18684. var index = this._scene._actionManagers.indexOf(this);
  18685. if (index > -1) {
  18686. this._scene._actionManagers.splice(index, 1);
  18687. }
  18688. };
  18689. ActionManager.prototype.getScene = function () {
  18690. return this._scene;
  18691. };
  18692. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  18693. for (var index = 0; index < this.actions.length; index++) {
  18694. var action = this.actions[index];
  18695. if (triggers.indexOf(action.trigger) > -1) {
  18696. return true;
  18697. }
  18698. }
  18699. return false;
  18700. };
  18701. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  18702. get: function () {
  18703. for (var index = 0; index < this.actions.length; index++) {
  18704. var action = this.actions[index];
  18705. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  18706. return true;
  18707. }
  18708. }
  18709. return false;
  18710. },
  18711. enumerable: true,
  18712. configurable: true
  18713. });
  18714. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  18715. get: function () {
  18716. for (var index = 0; index < this.actions.length; index++) {
  18717. var action = this.actions[index];
  18718. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  18719. return true;
  18720. }
  18721. }
  18722. return false;
  18723. },
  18724. enumerable: true,
  18725. configurable: true
  18726. });
  18727. ActionManager.prototype.registerAction = function (action) {
  18728. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  18729. if (this.getScene().actionManager !== this) {
  18730. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  18731. return null;
  18732. }
  18733. }
  18734. this.actions.push(action);
  18735. action._actionManager = this;
  18736. action._prepare();
  18737. return action;
  18738. };
  18739. ActionManager.prototype.processTrigger = function (trigger, evt) {
  18740. for (var index = 0; index < this.actions.length; index++) {
  18741. var action = this.actions[index];
  18742. if (action.trigger === trigger) {
  18743. if (trigger == ActionManager.OnKeyUpTrigger || trigger == ActionManager.OnKeyDownTrigger) {
  18744. var parameter = action.getTriggerParameter();
  18745. if (parameter) {
  18746. if (evt.sourceEvent.key !== parameter) {
  18747. continue;
  18748. }
  18749. }
  18750. }
  18751. action._executeCurrent(evt);
  18752. }
  18753. }
  18754. };
  18755. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  18756. var properties = propertyPath.split(".");
  18757. for (var index = 0; index < properties.length - 1; index++) {
  18758. target = target[properties[index]];
  18759. }
  18760. return target;
  18761. };
  18762. ActionManager.prototype._getProperty = function (propertyPath) {
  18763. var properties = propertyPath.split(".");
  18764. return properties[properties.length - 1];
  18765. };
  18766. ActionManager._NothingTrigger = 0;
  18767. ActionManager._OnPickTrigger = 1;
  18768. ActionManager._OnLeftPickTrigger = 2;
  18769. ActionManager._OnRightPickTrigger = 3;
  18770. ActionManager._OnCenterPickTrigger = 4;
  18771. ActionManager._OnPointerOverTrigger = 5;
  18772. ActionManager._OnPointerOutTrigger = 6;
  18773. ActionManager._OnEveryFrameTrigger = 7;
  18774. ActionManager._OnIntersectionEnterTrigger = 8;
  18775. ActionManager._OnIntersectionExitTrigger = 9;
  18776. ActionManager._OnKeyDownTrigger = 10;
  18777. ActionManager._OnKeyUpTrigger = 11;
  18778. return ActionManager;
  18779. })();
  18780. BABYLON.ActionManager = ActionManager;
  18781. })(BABYLON || (BABYLON = {}));
  18782. var __extends = this.__extends || function (d, b) {
  18783. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18784. function __() { this.constructor = d; }
  18785. __.prototype = b.prototype;
  18786. d.prototype = new __();
  18787. };
  18788. var BABYLON;
  18789. (function (BABYLON) {
  18790. var InterpolateValueAction = (function (_super) {
  18791. __extends(InterpolateValueAction, _super);
  18792. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  18793. if (typeof duration === "undefined") { duration = 1000; }
  18794. _super.call(this, triggerOptions, condition);
  18795. this.propertyPath = propertyPath;
  18796. this.value = value;
  18797. this.duration = duration;
  18798. this.stopOtherAnimations = stopOtherAnimations;
  18799. this._target = target;
  18800. }
  18801. InterpolateValueAction.prototype._prepare = function () {
  18802. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18803. this._property = this._getProperty(this.propertyPath);
  18804. };
  18805. InterpolateValueAction.prototype.execute = function () {
  18806. var scene = this._actionManager.getScene();
  18807. var keys = [
  18808. {
  18809. frame: 0,
  18810. value: this._target[this._property]
  18811. }, {
  18812. frame: 100,
  18813. value: this.value
  18814. }
  18815. ];
  18816. var dataType;
  18817. if (typeof this.value === "number") {
  18818. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  18819. } else if (this.value instanceof BABYLON.Color3) {
  18820. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  18821. } else if (this.value instanceof BABYLON.Vector3) {
  18822. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  18823. } else if (this.value instanceof BABYLON.Matrix) {
  18824. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  18825. } else if (this.value instanceof BABYLON.Quaternion) {
  18826. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  18827. } else {
  18828. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  18829. return;
  18830. }
  18831. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  18832. animation.setKeys(keys);
  18833. if (this.stopOtherAnimations) {
  18834. scene.stopAnimation(this._target);
  18835. }
  18836. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  18837. };
  18838. return InterpolateValueAction;
  18839. })(BABYLON.Action);
  18840. BABYLON.InterpolateValueAction = InterpolateValueAction;
  18841. })(BABYLON || (BABYLON = {}));
  18842. var __extends = this.__extends || function (d, b) {
  18843. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18844. function __() { this.constructor = d; }
  18845. __.prototype = b.prototype;
  18846. d.prototype = new __();
  18847. };
  18848. var BABYLON;
  18849. (function (BABYLON) {
  18850. var SwitchBooleanAction = (function (_super) {
  18851. __extends(SwitchBooleanAction, _super);
  18852. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  18853. _super.call(this, triggerOptions, condition);
  18854. this.propertyPath = propertyPath;
  18855. this._target = target;
  18856. }
  18857. SwitchBooleanAction.prototype._prepare = function () {
  18858. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18859. this._property = this._getProperty(this.propertyPath);
  18860. };
  18861. SwitchBooleanAction.prototype.execute = function () {
  18862. this._target[this._property] = !this._target[this._property];
  18863. };
  18864. return SwitchBooleanAction;
  18865. })(BABYLON.Action);
  18866. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  18867. var SetStateAction = (function (_super) {
  18868. __extends(SetStateAction, _super);
  18869. function SetStateAction(triggerOptions, target, value, condition) {
  18870. _super.call(this, triggerOptions, condition);
  18871. this.value = value;
  18872. this._target = target;
  18873. }
  18874. SetStateAction.prototype.execute = function () {
  18875. this._target.state = this.value;
  18876. };
  18877. return SetStateAction;
  18878. })(BABYLON.Action);
  18879. BABYLON.SetStateAction = SetStateAction;
  18880. var SetValueAction = (function (_super) {
  18881. __extends(SetValueAction, _super);
  18882. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  18883. _super.call(this, triggerOptions, condition);
  18884. this.propertyPath = propertyPath;
  18885. this.value = value;
  18886. this._target = target;
  18887. }
  18888. SetValueAction.prototype._prepare = function () {
  18889. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18890. this._property = this._getProperty(this.propertyPath);
  18891. };
  18892. SetValueAction.prototype.execute = function () {
  18893. this._target[this._property] = this.value;
  18894. };
  18895. return SetValueAction;
  18896. })(BABYLON.Action);
  18897. BABYLON.SetValueAction = SetValueAction;
  18898. var IncrementValueAction = (function (_super) {
  18899. __extends(IncrementValueAction, _super);
  18900. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  18901. _super.call(this, triggerOptions, condition);
  18902. this.propertyPath = propertyPath;
  18903. this.value = value;
  18904. this._target = target;
  18905. }
  18906. IncrementValueAction.prototype._prepare = function () {
  18907. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18908. this._property = this._getProperty(this.propertyPath);
  18909. if (typeof this._target[this._property] !== "number") {
  18910. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  18911. }
  18912. };
  18913. IncrementValueAction.prototype.execute = function () {
  18914. this._target[this._property] += this.value;
  18915. };
  18916. return IncrementValueAction;
  18917. })(BABYLON.Action);
  18918. BABYLON.IncrementValueAction = IncrementValueAction;
  18919. var PlayAnimationAction = (function (_super) {
  18920. __extends(PlayAnimationAction, _super);
  18921. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  18922. _super.call(this, triggerOptions, condition);
  18923. this.from = from;
  18924. this.to = to;
  18925. this.loop = loop;
  18926. this._target = target;
  18927. }
  18928. PlayAnimationAction.prototype._prepare = function () {
  18929. };
  18930. PlayAnimationAction.prototype.execute = function () {
  18931. var scene = this._actionManager.getScene();
  18932. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  18933. };
  18934. return PlayAnimationAction;
  18935. })(BABYLON.Action);
  18936. BABYLON.PlayAnimationAction = PlayAnimationAction;
  18937. var StopAnimationAction = (function (_super) {
  18938. __extends(StopAnimationAction, _super);
  18939. function StopAnimationAction(triggerOptions, target, condition) {
  18940. _super.call(this, triggerOptions, condition);
  18941. this._target = target;
  18942. }
  18943. StopAnimationAction.prototype._prepare = function () {
  18944. };
  18945. StopAnimationAction.prototype.execute = function () {
  18946. var scene = this._actionManager.getScene();
  18947. scene.stopAnimation(this._target);
  18948. };
  18949. return StopAnimationAction;
  18950. })(BABYLON.Action);
  18951. BABYLON.StopAnimationAction = StopAnimationAction;
  18952. var DoNothingAction = (function (_super) {
  18953. __extends(DoNothingAction, _super);
  18954. function DoNothingAction(triggerOptions, condition) {
  18955. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  18956. _super.call(this, triggerOptions, condition);
  18957. }
  18958. DoNothingAction.prototype.execute = function () {
  18959. };
  18960. return DoNothingAction;
  18961. })(BABYLON.Action);
  18962. BABYLON.DoNothingAction = DoNothingAction;
  18963. var CombineAction = (function (_super) {
  18964. __extends(CombineAction, _super);
  18965. function CombineAction(triggerOptions, children, condition) {
  18966. _super.call(this, triggerOptions, condition);
  18967. this.children = children;
  18968. }
  18969. CombineAction.prototype._prepare = function () {
  18970. for (var index = 0; index < this.children.length; index++) {
  18971. this.children[index]._actionManager = this._actionManager;
  18972. this.children[index]._prepare();
  18973. }
  18974. };
  18975. CombineAction.prototype.execute = function (evt) {
  18976. for (var index = 0; index < this.children.length; index++) {
  18977. this.children[index].execute(evt);
  18978. }
  18979. };
  18980. return CombineAction;
  18981. })(BABYLON.Action);
  18982. BABYLON.CombineAction = CombineAction;
  18983. var ExecuteCodeAction = (function (_super) {
  18984. __extends(ExecuteCodeAction, _super);
  18985. function ExecuteCodeAction(triggerOptions, func, condition) {
  18986. _super.call(this, triggerOptions, condition);
  18987. this.func = func;
  18988. }
  18989. ExecuteCodeAction.prototype.execute = function (evt) {
  18990. this.func(evt);
  18991. };
  18992. return ExecuteCodeAction;
  18993. })(BABYLON.Action);
  18994. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  18995. var SetParentAction = (function (_super) {
  18996. __extends(SetParentAction, _super);
  18997. function SetParentAction(triggerOptions, target, parent, condition) {
  18998. _super.call(this, triggerOptions, condition);
  18999. this._target = target;
  19000. this._parent = parent;
  19001. }
  19002. SetParentAction.prototype._prepare = function () {
  19003. };
  19004. SetParentAction.prototype.execute = function () {
  19005. if (this._target.parent === this._parent) {
  19006. return;
  19007. }
  19008. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  19009. invertParentWorldMatrix.invert();
  19010. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  19011. this._target.parent = this._parent;
  19012. };
  19013. return SetParentAction;
  19014. })(BABYLON.Action);
  19015. BABYLON.SetParentAction = SetParentAction;
  19016. })(BABYLON || (BABYLON = {}));
  19017. var __extends = this.__extends || function (d, b) {
  19018. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19019. function __() { this.constructor = d; }
  19020. __.prototype = b.prototype;
  19021. d.prototype = new __();
  19022. };
  19023. var BABYLON;
  19024. (function (BABYLON) {
  19025. var Geometry = (function () {
  19026. function Geometry(id, scene, vertexData, updatable, mesh) {
  19027. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19028. this._totalVertices = 0;
  19029. this._indices = [];
  19030. this.id = id;
  19031. this._engine = scene.getEngine();
  19032. this._meshes = [];
  19033. this._scene = scene;
  19034. if (vertexData) {
  19035. this.setAllVerticesData(vertexData, updatable);
  19036. } else {
  19037. this._totalVertices = 0;
  19038. this._indices = [];
  19039. }
  19040. if (mesh) {
  19041. this.applyToMesh(mesh);
  19042. }
  19043. }
  19044. Geometry.prototype.getScene = function () {
  19045. return this._scene;
  19046. };
  19047. Geometry.prototype.getEngine = function () {
  19048. return this._engine;
  19049. };
  19050. Geometry.prototype.isReady = function () {
  19051. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  19052. };
  19053. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  19054. vertexData.applyToGeometry(this, updatable);
  19055. };
  19056. Geometry.prototype.setVerticesData = function (kind, data, updatable) {
  19057. this._vertexBuffers = this._vertexBuffers || {};
  19058. if (this._vertexBuffers[kind]) {
  19059. this._vertexBuffers[kind].dispose();
  19060. }
  19061. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0);
  19062. if (kind === BABYLON.VertexBuffer.PositionKind) {
  19063. var stride = this._vertexBuffers[kind].getStrideSize();
  19064. this._totalVertices = data.length / stride;
  19065. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  19066. var meshes = this._meshes;
  19067. var numOfMeshes = meshes.length;
  19068. for (var index = 0; index < numOfMeshes; index++) {
  19069. var mesh = meshes[index];
  19070. mesh._resetPointsArrayCache();
  19071. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19072. mesh._createGlobalSubMesh();
  19073. mesh.computeWorldMatrix(true);
  19074. }
  19075. }
  19076. };
  19077. Geometry.prototype.updateVerticesDataDirectly = function (kind, data) {
  19078. var vertexBuffer = this.getVertexBuffer(kind);
  19079. if (!vertexBuffer) {
  19080. return;
  19081. }
  19082. vertexBuffer.updateDirectly(data);
  19083. };
  19084. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  19085. var vertexBuffer = this.getVertexBuffer(kind);
  19086. if (!vertexBuffer) {
  19087. return;
  19088. }
  19089. vertexBuffer.update(data);
  19090. if (kind === BABYLON.VertexBuffer.PositionKind) {
  19091. var extend;
  19092. if (updateExtends) {
  19093. var stride = vertexBuffer.getStrideSize();
  19094. this._totalVertices = data.length / stride;
  19095. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  19096. }
  19097. var meshes = this._meshes;
  19098. var numOfMeshes = meshes.length;
  19099. for (var index = 0; index < numOfMeshes; index++) {
  19100. var mesh = meshes[index];
  19101. mesh._resetPointsArrayCache();
  19102. if (updateExtends) {
  19103. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19104. }
  19105. }
  19106. }
  19107. };
  19108. Geometry.prototype.getTotalVertices = function () {
  19109. if (!this.isReady()) {
  19110. return 0;
  19111. }
  19112. return this._totalVertices;
  19113. };
  19114. Geometry.prototype.getVerticesData = function (kind) {
  19115. var vertexBuffer = this.getVertexBuffer(kind);
  19116. if (!vertexBuffer) {
  19117. return null;
  19118. }
  19119. return vertexBuffer.getData();
  19120. };
  19121. Geometry.prototype.getVertexBuffer = function (kind) {
  19122. if (!this.isReady()) {
  19123. return null;
  19124. }
  19125. return this._vertexBuffers[kind];
  19126. };
  19127. Geometry.prototype.getVertexBuffers = function () {
  19128. if (!this.isReady()) {
  19129. return null;
  19130. }
  19131. return this._vertexBuffers;
  19132. };
  19133. Geometry.prototype.isVerticesDataPresent = function (kind) {
  19134. if (!this._vertexBuffers) {
  19135. if (this._delayInfo) {
  19136. return this._delayInfo.indexOf(kind) !== -1;
  19137. }
  19138. return false;
  19139. }
  19140. return this._vertexBuffers[kind] !== undefined;
  19141. };
  19142. Geometry.prototype.getVerticesDataKinds = function () {
  19143. var result = [];
  19144. if (!this._vertexBuffers && this._delayInfo) {
  19145. for (var kind in this._delayInfo) {
  19146. result.push(kind);
  19147. }
  19148. } else {
  19149. for (kind in this._vertexBuffers) {
  19150. result.push(kind);
  19151. }
  19152. }
  19153. return result;
  19154. };
  19155. Geometry.prototype.setIndices = function (indices) {
  19156. if (this._indexBuffer) {
  19157. this._engine._releaseBuffer(this._indexBuffer);
  19158. }
  19159. this._indices = indices;
  19160. if (this._meshes.length !== 0 && this._indices) {
  19161. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  19162. }
  19163. var meshes = this._meshes;
  19164. var numOfMeshes = meshes.length;
  19165. for (var index = 0; index < numOfMeshes; index++) {
  19166. meshes[index]._createGlobalSubMesh();
  19167. }
  19168. };
  19169. Geometry.prototype.getTotalIndices = function () {
  19170. if (!this.isReady()) {
  19171. return 0;
  19172. }
  19173. return this._indices.length;
  19174. };
  19175. Geometry.prototype.getIndices = function () {
  19176. if (!this.isReady()) {
  19177. return null;
  19178. }
  19179. return this._indices;
  19180. };
  19181. Geometry.prototype.getIndexBuffer = function () {
  19182. if (!this.isReady()) {
  19183. return null;
  19184. }
  19185. return this._indexBuffer;
  19186. };
  19187. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  19188. var meshes = this._meshes;
  19189. var index = meshes.indexOf(mesh);
  19190. if (index === -1) {
  19191. return;
  19192. }
  19193. for (var kind in this._vertexBuffers) {
  19194. this._vertexBuffers[kind].dispose();
  19195. }
  19196. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  19197. this._indexBuffer = null;
  19198. }
  19199. meshes.splice(index, 1);
  19200. mesh._geometry = null;
  19201. if (meshes.length == 0 && shouldDispose) {
  19202. this.dispose();
  19203. }
  19204. };
  19205. Geometry.prototype.applyToMesh = function (mesh) {
  19206. if (mesh._geometry === this) {
  19207. return;
  19208. }
  19209. var previousGeometry = mesh._geometry;
  19210. if (previousGeometry) {
  19211. previousGeometry.releaseForMesh(mesh);
  19212. }
  19213. var meshes = this._meshes;
  19214. mesh._geometry = this;
  19215. this._scene.pushGeometry(this);
  19216. meshes.push(mesh);
  19217. if (this.isReady()) {
  19218. this._applyToMesh(mesh);
  19219. } else {
  19220. mesh._boundingInfo = this._boundingInfo;
  19221. }
  19222. };
  19223. Geometry.prototype._applyToMesh = function (mesh) {
  19224. var numOfMeshes = this._meshes.length;
  19225. for (var kind in this._vertexBuffers) {
  19226. if (numOfMeshes === 1) {
  19227. this._vertexBuffers[kind].create();
  19228. }
  19229. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  19230. if (kind === BABYLON.VertexBuffer.PositionKind) {
  19231. mesh._resetPointsArrayCache();
  19232. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  19233. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19234. mesh._createGlobalSubMesh();
  19235. }
  19236. }
  19237. if (numOfMeshes === 1 && this._indices) {
  19238. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  19239. }
  19240. if (this._indexBuffer) {
  19241. this._indexBuffer.references = numOfMeshes;
  19242. }
  19243. };
  19244. Geometry.prototype.load = function (scene, onLoaded) {
  19245. var _this = this;
  19246. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19247. return;
  19248. }
  19249. if (this.isReady()) {
  19250. if (onLoaded) {
  19251. onLoaded();
  19252. }
  19253. return;
  19254. }
  19255. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19256. scene._addPendingData(this);
  19257. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19258. _this._delayLoadingFunction(JSON.parse(data), _this);
  19259. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19260. _this._delayInfo = [];
  19261. scene._removePendingData(_this);
  19262. var meshes = _this._meshes;
  19263. var numOfMeshes = meshes.length;
  19264. for (var index = 0; index < numOfMeshes; index++) {
  19265. _this._applyToMesh(meshes[index]);
  19266. }
  19267. if (onLoaded) {
  19268. onLoaded();
  19269. }
  19270. }, function () {
  19271. }, scene.database);
  19272. };
  19273. Geometry.prototype.dispose = function () {
  19274. var meshes = this._meshes;
  19275. var numOfMeshes = meshes.length;
  19276. for (var index = 0; index < numOfMeshes; index++) {
  19277. this.releaseForMesh(meshes[index]);
  19278. }
  19279. this._meshes = [];
  19280. for (var kind in this._vertexBuffers) {
  19281. this._vertexBuffers[kind].dispose();
  19282. }
  19283. this._vertexBuffers = [];
  19284. this._totalVertices = 0;
  19285. if (this._indexBuffer) {
  19286. this._engine._releaseBuffer(this._indexBuffer);
  19287. }
  19288. this._indexBuffer = null;
  19289. this._indices = [];
  19290. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19291. this.delayLoadingFile = null;
  19292. this._delayLoadingFunction = null;
  19293. this._delayInfo = [];
  19294. this._boundingInfo = null;
  19295. var geometries = this._scene.getGeometries();
  19296. index = geometries.indexOf(this);
  19297. if (index > -1) {
  19298. geometries.splice(index, 1);
  19299. }
  19300. };
  19301. Geometry.prototype.copy = function (id) {
  19302. var vertexData = new BABYLON.VertexData();
  19303. vertexData.indices = [];
  19304. var indices = this.getIndices();
  19305. for (var index = 0; index < indices.length; index++) {
  19306. vertexData.indices.push(indices[index]);
  19307. }
  19308. var updatable = false;
  19309. var stopChecking = false;
  19310. for (var kind in this._vertexBuffers) {
  19311. vertexData.set(this.getVerticesData(kind), kind);
  19312. if (!stopChecking) {
  19313. updatable = this.getVertexBuffer(kind).isUpdatable();
  19314. stopChecking = !updatable;
  19315. }
  19316. }
  19317. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  19318. geometry.delayLoadState = this.delayLoadState;
  19319. geometry.delayLoadingFile = this.delayLoadingFile;
  19320. geometry._delayLoadingFunction = this._delayLoadingFunction;
  19321. for (kind in this._delayInfo) {
  19322. geometry._delayInfo = geometry._delayInfo || [];
  19323. geometry._delayInfo.push(kind);
  19324. }
  19325. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  19326. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19327. return geometry;
  19328. };
  19329. Geometry.ExtractFromMesh = function (mesh, id) {
  19330. var geometry = mesh._geometry;
  19331. if (!geometry) {
  19332. return null;
  19333. }
  19334. return geometry.copy(id);
  19335. };
  19336. Geometry.RandomId = function () {
  19337. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  19338. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  19339. return v.toString(16);
  19340. });
  19341. };
  19342. return Geometry;
  19343. })();
  19344. BABYLON.Geometry = Geometry;
  19345. (function (Geometry) {
  19346. (function (Primitives) {
  19347. var _Primitive = (function (_super) {
  19348. __extends(_Primitive, _super);
  19349. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  19350. this._beingRegenerated = true;
  19351. this._canBeRegenerated = canBeRegenerated;
  19352. _super.call(this, id, scene, vertexData, false, mesh);
  19353. this._beingRegenerated = false;
  19354. }
  19355. _Primitive.prototype.canBeRegenerated = function () {
  19356. return this._canBeRegenerated;
  19357. };
  19358. _Primitive.prototype.regenerate = function () {
  19359. if (!this._canBeRegenerated) {
  19360. return;
  19361. }
  19362. this._beingRegenerated = true;
  19363. this.setAllVerticesData(this._regenerateVertexData(), false);
  19364. this._beingRegenerated = false;
  19365. };
  19366. _Primitive.prototype.asNewGeometry = function (id) {
  19367. return _super.prototype.copy.call(this, id);
  19368. };
  19369. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  19370. if (!this._beingRegenerated) {
  19371. return;
  19372. }
  19373. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  19374. };
  19375. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  19376. if (!this._beingRegenerated) {
  19377. return;
  19378. }
  19379. _super.prototype.setVerticesData.call(this, kind, data, false);
  19380. };
  19381. _Primitive.prototype._regenerateVertexData = function () {
  19382. throw new Error("Abstract method");
  19383. };
  19384. _Primitive.prototype.copy = function (id) {
  19385. throw new Error("Must be overriden in sub-classes.");
  19386. };
  19387. return _Primitive;
  19388. })(Geometry);
  19389. Primitives._Primitive = _Primitive;
  19390. var Box = (function (_super) {
  19391. __extends(Box, _super);
  19392. function Box(id, scene, size, canBeRegenerated, mesh) {
  19393. this.size = size;
  19394. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19395. }
  19396. Box.prototype._regenerateVertexData = function () {
  19397. return BABYLON.VertexData.CreateBox(this.size);
  19398. };
  19399. Box.prototype.copy = function (id) {
  19400. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19401. };
  19402. return Box;
  19403. })(_Primitive);
  19404. Primitives.Box = Box;
  19405. var Sphere = (function (_super) {
  19406. __extends(Sphere, _super);
  19407. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  19408. this.segments = segments;
  19409. this.diameter = diameter;
  19410. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19411. }
  19412. Sphere.prototype._regenerateVertexData = function () {
  19413. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  19414. };
  19415. Sphere.prototype.copy = function (id) {
  19416. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  19417. };
  19418. return Sphere;
  19419. })(_Primitive);
  19420. Primitives.Sphere = Sphere;
  19421. var Cylinder = (function (_super) {
  19422. __extends(Cylinder, _super);
  19423. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  19424. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  19425. this.height = height;
  19426. this.diameterTop = diameterTop;
  19427. this.diameterBottom = diameterBottom;
  19428. this.tessellation = tessellation;
  19429. this.subdivisions = subdivisions;
  19430. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19431. }
  19432. Cylinder.prototype._regenerateVertexData = function () {
  19433. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  19434. };
  19435. Cylinder.prototype.copy = function (id) {
  19436. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  19437. };
  19438. return Cylinder;
  19439. })(_Primitive);
  19440. Primitives.Cylinder = Cylinder;
  19441. var Torus = (function (_super) {
  19442. __extends(Torus, _super);
  19443. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  19444. this.diameter = diameter;
  19445. this.thickness = thickness;
  19446. this.tessellation = tessellation;
  19447. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19448. }
  19449. Torus.prototype._regenerateVertexData = function () {
  19450. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  19451. };
  19452. Torus.prototype.copy = function (id) {
  19453. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  19454. };
  19455. return Torus;
  19456. })(_Primitive);
  19457. Primitives.Torus = Torus;
  19458. var Ground = (function (_super) {
  19459. __extends(Ground, _super);
  19460. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  19461. this.width = width;
  19462. this.height = height;
  19463. this.subdivisions = subdivisions;
  19464. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19465. }
  19466. Ground.prototype._regenerateVertexData = function () {
  19467. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  19468. };
  19469. Ground.prototype.copy = function (id) {
  19470. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  19471. };
  19472. return Ground;
  19473. })(_Primitive);
  19474. Primitives.Ground = Ground;
  19475. var TiledGround = (function (_super) {
  19476. __extends(TiledGround, _super);
  19477. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  19478. this.xmin = xmin;
  19479. this.zmin = zmin;
  19480. this.xmax = xmax;
  19481. this.zmax = zmax;
  19482. this.subdivisions = subdivisions;
  19483. this.precision = precision;
  19484. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19485. }
  19486. TiledGround.prototype._regenerateVertexData = function () {
  19487. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  19488. };
  19489. TiledGround.prototype.copy = function (id) {
  19490. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  19491. };
  19492. return TiledGround;
  19493. })(_Primitive);
  19494. Primitives.TiledGround = TiledGround;
  19495. var Plane = (function (_super) {
  19496. __extends(Plane, _super);
  19497. function Plane(id, scene, size, canBeRegenerated, mesh) {
  19498. this.size = size;
  19499. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19500. }
  19501. Plane.prototype._regenerateVertexData = function () {
  19502. return BABYLON.VertexData.CreatePlane(this.size);
  19503. };
  19504. Plane.prototype.copy = function (id) {
  19505. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19506. };
  19507. return Plane;
  19508. })(_Primitive);
  19509. Primitives.Plane = Plane;
  19510. var TorusKnot = (function (_super) {
  19511. __extends(TorusKnot, _super);
  19512. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  19513. this.radius = radius;
  19514. this.tube = tube;
  19515. this.radialSegments = radialSegments;
  19516. this.tubularSegments = tubularSegments;
  19517. this.p = p;
  19518. this.q = q;
  19519. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19520. }
  19521. TorusKnot.prototype._regenerateVertexData = function () {
  19522. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  19523. };
  19524. TorusKnot.prototype.copy = function (id) {
  19525. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  19526. };
  19527. return TorusKnot;
  19528. })(_Primitive);
  19529. Primitives.TorusKnot = TorusKnot;
  19530. })(Geometry.Primitives || (Geometry.Primitives = {}));
  19531. var Primitives = Geometry.Primitives;
  19532. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  19533. var Geometry = BABYLON.Geometry;
  19534. })(BABYLON || (BABYLON = {}));
  19535. var __extends = this.__extends || function (d, b) {
  19536. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19537. function __() { this.constructor = d; }
  19538. __.prototype = b.prototype;
  19539. d.prototype = new __();
  19540. };
  19541. var BABYLON;
  19542. (function (BABYLON) {
  19543. var Gamepads = (function () {
  19544. function Gamepads(ongamedpadconnected) {
  19545. var _this = this;
  19546. this.babylonGamepads = [];
  19547. this.oneGamepadConnected = false;
  19548. this.isMonitoring = false;
  19549. this.gamepadEventSupported = 'GamepadEvent' in window;
  19550. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  19551. 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=";
  19552. this._callbackGamepadConnected = ongamedpadconnected;
  19553. if (this.gamepadSupportAvailable) {
  19554. if (this.gamepadEventSupported) {
  19555. window.addEventListener('gamepadconnected', function (evt) {
  19556. _this._onGamepadConnected(evt);
  19557. }, false);
  19558. window.addEventListener('gamepaddisconnected', function (evt) {
  19559. _this._onGamepadDisconnected(evt);
  19560. }, false);
  19561. } else {
  19562. this._startMonitoringGamepads();
  19563. }
  19564. if (!this.oneGamepadConnected) {
  19565. this._insertGamepadDOMInstructions();
  19566. }
  19567. } else {
  19568. this._insertGamepadDOMNotSupported();
  19569. }
  19570. }
  19571. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  19572. Gamepads.gamepadDOMInfo = document.createElement("div");
  19573. var buttonAImage = document.createElement("img");
  19574. buttonAImage.src = this.buttonADataURL;
  19575. var spanMessage = document.createElement("span");
  19576. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  19577. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  19578. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  19579. Gamepads.gamepadDOMInfo.style.position = "absolute";
  19580. Gamepads.gamepadDOMInfo.style.width = "100%";
  19581. Gamepads.gamepadDOMInfo.style.height = "48px";
  19582. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  19583. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  19584. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  19585. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  19586. buttonAImage.style.position = "relative";
  19587. buttonAImage.style.bottom = "8px";
  19588. spanMessage.style.position = "relative";
  19589. spanMessage.style.fontSize = "32px";
  19590. spanMessage.style.bottom = "32px";
  19591. spanMessage.style.color = "green";
  19592. document.body.appendChild(Gamepads.gamepadDOMInfo);
  19593. };
  19594. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  19595. Gamepads.gamepadDOMInfo = document.createElement("div");
  19596. var spanMessage = document.createElement("span");
  19597. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  19598. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  19599. Gamepads.gamepadDOMInfo.style.position = "absolute";
  19600. Gamepads.gamepadDOMInfo.style.width = "100%";
  19601. Gamepads.gamepadDOMInfo.style.height = "40px";
  19602. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  19603. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  19604. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  19605. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  19606. spanMessage.style.position = "relative";
  19607. spanMessage.style.fontSize = "32px";
  19608. spanMessage.style.color = "red";
  19609. document.body.appendChild(Gamepads.gamepadDOMInfo);
  19610. };
  19611. Gamepads.prototype.dispose = function () {
  19612. document.body.removeChild(Gamepads.gamepadDOMInfo);
  19613. };
  19614. Gamepads.prototype._onGamepadConnected = function (evt) {
  19615. var newGamepad = this._addNewGamepad(evt.gamepad);
  19616. if (this._callbackGamepadConnected)
  19617. this._callbackGamepadConnected(newGamepad);
  19618. this._startMonitoringGamepads();
  19619. };
  19620. Gamepads.prototype._addNewGamepad = function (gamepad) {
  19621. if (!this.oneGamepadConnected) {
  19622. this.oneGamepadConnected = true;
  19623. if (Gamepads.gamepadDOMInfo) {
  19624. document.body.removeChild(Gamepads.gamepadDOMInfo);
  19625. Gamepads.gamepadDOMInfo = null;
  19626. }
  19627. }
  19628. var newGamepad;
  19629. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  19630. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  19631. } else {
  19632. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  19633. }
  19634. this.babylonGamepads.push(newGamepad);
  19635. return newGamepad;
  19636. };
  19637. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  19638. for (var i in this.babylonGamepads) {
  19639. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  19640. this.babylonGamepads.splice(i, 1);
  19641. break;
  19642. }
  19643. }
  19644. if (this.babylonGamepads.length == 0) {
  19645. this._stopMonitoringGamepads();
  19646. }
  19647. };
  19648. Gamepads.prototype._startMonitoringGamepads = function () {
  19649. if (!this.isMonitoring) {
  19650. this.isMonitoring = true;
  19651. this._checkGamepadsStatus();
  19652. }
  19653. };
  19654. Gamepads.prototype._stopMonitoringGamepads = function () {
  19655. this.isMonitoring = false;
  19656. };
  19657. Gamepads.prototype._checkGamepadsStatus = function () {
  19658. var _this = this;
  19659. this._updateGamepadObjects();
  19660. for (var i in this.babylonGamepads) {
  19661. this.babylonGamepads[i].update();
  19662. }
  19663. if (this.isMonitoring) {
  19664. if (window.requestAnimationFrame) {
  19665. window.requestAnimationFrame(function () {
  19666. _this._checkGamepadsStatus();
  19667. });
  19668. } else if (window.mozRequestAnimationFrame) {
  19669. window.mozRequestAnimationFrame(function () {
  19670. _this._checkGamepadsStatus();
  19671. });
  19672. } else if (window.webkitRequestAnimationFrame) {
  19673. window.webkitRequestAnimationFrame(function () {
  19674. _this._checkGamepadsStatus();
  19675. });
  19676. }
  19677. }
  19678. };
  19679. Gamepads.prototype._updateGamepadObjects = function () {
  19680. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  19681. for (var i = 0; i < gamepads.length; i++) {
  19682. if (gamepads[i]) {
  19683. if (!(gamepads[i].index in this.babylonGamepads)) {
  19684. var newGamepad = this._addNewGamepad(gamepads[i]);
  19685. if (this._callbackGamepadConnected) {
  19686. this._callbackGamepadConnected(newGamepad);
  19687. }
  19688. } else {
  19689. this.babylonGamepads[i].browserGamepad = gamepads[i];
  19690. }
  19691. }
  19692. }
  19693. };
  19694. return Gamepads;
  19695. })();
  19696. BABYLON.Gamepads = Gamepads;
  19697. var StickValues = (function () {
  19698. function StickValues(x, y) {
  19699. this.x = x;
  19700. this.y = y;
  19701. }
  19702. return StickValues;
  19703. })();
  19704. BABYLON.StickValues = StickValues;
  19705. var Gamepad = (function () {
  19706. function Gamepad(id, index, browserGamepad) {
  19707. this.id = id;
  19708. this.index = index;
  19709. this.browserGamepad = browserGamepad;
  19710. if (this.browserGamepad.axes.length >= 2) {
  19711. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  19712. }
  19713. if (this.browserGamepad.axes.length >= 4) {
  19714. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  19715. }
  19716. }
  19717. Gamepad.prototype.onleftstickchanged = function (callback) {
  19718. this._onleftstickchanged = callback;
  19719. };
  19720. Gamepad.prototype.onrightstickchanged = function (callback) {
  19721. this._onrightstickchanged = callback;
  19722. };
  19723. Object.defineProperty(Gamepad.prototype, "leftStick", {
  19724. get: function () {
  19725. return this._leftStick;
  19726. },
  19727. set: function (newValues) {
  19728. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  19729. this._onleftstickchanged(newValues);
  19730. }
  19731. this._leftStick = newValues;
  19732. },
  19733. enumerable: true,
  19734. configurable: true
  19735. });
  19736. Object.defineProperty(Gamepad.prototype, "rightStick", {
  19737. get: function () {
  19738. return this._rightStick;
  19739. },
  19740. set: function (newValues) {
  19741. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  19742. this._onrightstickchanged(newValues);
  19743. }
  19744. this._rightStick = newValues;
  19745. },
  19746. enumerable: true,
  19747. configurable: true
  19748. });
  19749. Gamepad.prototype.update = function () {
  19750. if (this._leftStick) {
  19751. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  19752. }
  19753. if (this._rightStick) {
  19754. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  19755. }
  19756. };
  19757. return Gamepad;
  19758. })();
  19759. BABYLON.Gamepad = Gamepad;
  19760. var GenericPad = (function (_super) {
  19761. __extends(GenericPad, _super);
  19762. function GenericPad(id, index, gamepad) {
  19763. _super.call(this, id, index, gamepad);
  19764. this.id = id;
  19765. this.index = index;
  19766. this.gamepad = gamepad;
  19767. this._buttons = new Array(gamepad.buttons.length);
  19768. }
  19769. GenericPad.prototype.onbuttondown = function (callback) {
  19770. this._onbuttondown = callback;
  19771. };
  19772. GenericPad.prototype.onbuttonup = function (callback) {
  19773. this._onbuttonup = callback;
  19774. };
  19775. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  19776. if (newValue !== currentValue) {
  19777. if (this._onbuttondown && newValue === 1) {
  19778. this._onbuttondown(buttonIndex);
  19779. }
  19780. if (this._onbuttonup && newValue === 0) {
  19781. this._onbuttonup(buttonIndex);
  19782. }
  19783. }
  19784. return newValue;
  19785. };
  19786. GenericPad.prototype.update = function () {
  19787. _super.prototype.update.call(this);
  19788. for (var index = 0; index < this._buttons.length; index++) {
  19789. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  19790. }
  19791. };
  19792. return GenericPad;
  19793. })(Gamepad);
  19794. BABYLON.GenericPad = GenericPad;
  19795. (function (Xbox360Button) {
  19796. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  19797. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  19798. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  19799. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  19800. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  19801. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  19802. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  19803. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  19804. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  19805. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  19806. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  19807. var Xbox360Button = BABYLON.Xbox360Button;
  19808. (function (Xbox360Dpad) {
  19809. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  19810. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  19811. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  19812. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  19813. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  19814. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  19815. var Xbox360Pad = (function (_super) {
  19816. __extends(Xbox360Pad, _super);
  19817. function Xbox360Pad() {
  19818. _super.apply(this, arguments);
  19819. this._leftTrigger = 0;
  19820. this._rightTrigger = 0;
  19821. this._buttonA = 0;
  19822. this._buttonB = 0;
  19823. this._buttonX = 0;
  19824. this._buttonY = 0;
  19825. this._buttonBack = 0;
  19826. this._buttonStart = 0;
  19827. this._buttonLB = 0;
  19828. this._buttonRB = 0;
  19829. this._buttonLeftStick = 0;
  19830. this._buttonRightStick = 0;
  19831. this._dPadUp = 0;
  19832. this._dPadDown = 0;
  19833. this._dPadLeft = 0;
  19834. this._dPadRight = 0;
  19835. }
  19836. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  19837. this._onlefttriggerchanged = callback;
  19838. };
  19839. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  19840. this._onrighttriggerchanged = callback;
  19841. };
  19842. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  19843. get: function () {
  19844. return this._leftTrigger;
  19845. },
  19846. set: function (newValue) {
  19847. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  19848. this._onlefttriggerchanged(newValue);
  19849. }
  19850. this._leftTrigger = newValue;
  19851. },
  19852. enumerable: true,
  19853. configurable: true
  19854. });
  19855. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  19856. get: function () {
  19857. return this._rightTrigger;
  19858. },
  19859. set: function (newValue) {
  19860. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  19861. this._onrighttriggerchanged(newValue);
  19862. }
  19863. this._rightTrigger = newValue;
  19864. },
  19865. enumerable: true,
  19866. configurable: true
  19867. });
  19868. Xbox360Pad.prototype.onbuttondown = function (callback) {
  19869. this._onbuttondown = callback;
  19870. };
  19871. Xbox360Pad.prototype.onbuttonup = function (callback) {
  19872. this._onbuttonup = callback;
  19873. };
  19874. Xbox360Pad.prototype.ondpaddown = function (callback) {
  19875. this._ondpaddown = callback;
  19876. };
  19877. Xbox360Pad.prototype.ondpadup = function (callback) {
  19878. this._ondpadup = callback;
  19879. };
  19880. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  19881. if (newValue !== currentValue) {
  19882. if (this._onbuttondown && newValue === 1) {
  19883. this._onbuttondown(buttonType);
  19884. }
  19885. if (this._onbuttonup && newValue === 0) {
  19886. this._onbuttonup(buttonType);
  19887. }
  19888. }
  19889. return newValue;
  19890. };
  19891. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  19892. if (newValue !== currentValue) {
  19893. if (this._ondpaddown && newValue === 1) {
  19894. this._ondpaddown(buttonType);
  19895. }
  19896. if (this._ondpadup && newValue === 0) {
  19897. this._ondpadup(buttonType);
  19898. }
  19899. }
  19900. return newValue;
  19901. };
  19902. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  19903. get: function () {
  19904. return this._buttonA;
  19905. },
  19906. set: function (value) {
  19907. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  19908. },
  19909. enumerable: true,
  19910. configurable: true
  19911. });
  19912. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  19913. get: function () {
  19914. return this._buttonB;
  19915. },
  19916. set: function (value) {
  19917. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  19918. },
  19919. enumerable: true,
  19920. configurable: true
  19921. });
  19922. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  19923. get: function () {
  19924. return this._buttonX;
  19925. },
  19926. set: function (value) {
  19927. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  19928. },
  19929. enumerable: true,
  19930. configurable: true
  19931. });
  19932. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  19933. get: function () {
  19934. return this._buttonY;
  19935. },
  19936. set: function (value) {
  19937. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  19938. },
  19939. enumerable: true,
  19940. configurable: true
  19941. });
  19942. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  19943. get: function () {
  19944. return this._buttonStart;
  19945. },
  19946. set: function (value) {
  19947. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  19948. },
  19949. enumerable: true,
  19950. configurable: true
  19951. });
  19952. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  19953. get: function () {
  19954. return this._buttonBack;
  19955. },
  19956. set: function (value) {
  19957. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  19958. },
  19959. enumerable: true,
  19960. configurable: true
  19961. });
  19962. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  19963. get: function () {
  19964. return this._buttonLB;
  19965. },
  19966. set: function (value) {
  19967. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  19968. },
  19969. enumerable: true,
  19970. configurable: true
  19971. });
  19972. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  19973. get: function () {
  19974. return this._buttonRB;
  19975. },
  19976. set: function (value) {
  19977. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  19978. },
  19979. enumerable: true,
  19980. configurable: true
  19981. });
  19982. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  19983. get: function () {
  19984. return this._buttonLeftStick;
  19985. },
  19986. set: function (value) {
  19987. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  19988. },
  19989. enumerable: true,
  19990. configurable: true
  19991. });
  19992. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  19993. get: function () {
  19994. return this._buttonRightStick;
  19995. },
  19996. set: function (value) {
  19997. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  19998. },
  19999. enumerable: true,
  20000. configurable: true
  20001. });
  20002. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  20003. get: function () {
  20004. return this._dPadUp;
  20005. },
  20006. set: function (value) {
  20007. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  20008. },
  20009. enumerable: true,
  20010. configurable: true
  20011. });
  20012. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  20013. get: function () {
  20014. return this._dPadDown;
  20015. },
  20016. set: function (value) {
  20017. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  20018. },
  20019. enumerable: true,
  20020. configurable: true
  20021. });
  20022. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  20023. get: function () {
  20024. return this._dPadLeft;
  20025. },
  20026. set: function (value) {
  20027. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  20028. },
  20029. enumerable: true,
  20030. configurable: true
  20031. });
  20032. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  20033. get: function () {
  20034. return this._dPadRight;
  20035. },
  20036. set: function (value) {
  20037. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  20038. },
  20039. enumerable: true,
  20040. configurable: true
  20041. });
  20042. Xbox360Pad.prototype.update = function () {
  20043. _super.prototype.update.call(this);
  20044. this.buttonA = this.browserGamepad.buttons[0].value;
  20045. this.buttonB = this.browserGamepad.buttons[1].value;
  20046. this.buttonX = this.browserGamepad.buttons[2].value;
  20047. this.buttonY = this.browserGamepad.buttons[3].value;
  20048. this.buttonLB = this.browserGamepad.buttons[4].value;
  20049. this.buttonRB = this.browserGamepad.buttons[5].value;
  20050. this.leftTrigger = this.browserGamepad.buttons[6].value;
  20051. this.rightTrigger = this.browserGamepad.buttons[7].value;
  20052. this.buttonBack = this.browserGamepad.buttons[8].value;
  20053. this.buttonStart = this.browserGamepad.buttons[9].value;
  20054. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  20055. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  20056. this.dPadUp = this.browserGamepad.buttons[12].value;
  20057. this.dPadDown = this.browserGamepad.buttons[13].value;
  20058. this.dPadLeft = this.browserGamepad.buttons[14].value;
  20059. this.dPadRight = this.browserGamepad.buttons[15].value;
  20060. };
  20061. return Xbox360Pad;
  20062. })(Gamepad);
  20063. BABYLON.Xbox360Pad = Xbox360Pad;
  20064. })(BABYLON || (BABYLON = {}));
  20065. var __extends = this.__extends || function (d, b) {
  20066. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20067. function __() { this.constructor = d; }
  20068. __.prototype = b.prototype;
  20069. d.prototype = new __();
  20070. };
  20071. var BABYLON;
  20072. (function (BABYLON) {
  20073. var GamepadCamera = (function (_super) {
  20074. __extends(GamepadCamera, _super);
  20075. function GamepadCamera(name, position, scene) {
  20076. var _this = this;
  20077. _super.call(this, name, position, scene);
  20078. this.angularSensibility = 200;
  20079. this.moveSensibility = 75;
  20080. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  20081. _this._onNewGameConnected(gamepad);
  20082. });
  20083. }
  20084. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  20085. if (gamepad.index === 0) {
  20086. this._gamepad = gamepad;
  20087. }
  20088. };
  20089. GamepadCamera.prototype._checkInputs = function () {
  20090. if (!this._gamepad) {
  20091. return;
  20092. }
  20093. var LSValues = this._gamepad.leftStick;
  20094. var normalizedLX = LSValues.x / this.moveSensibility;
  20095. var normalizedLY = LSValues.y / this.moveSensibility;
  20096. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  20097. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  20098. var RSValues = this._gamepad.rightStick;
  20099. var normalizedRX = RSValues.x / this.angularSensibility;
  20100. var normalizedRY = RSValues.y / this.angularSensibility;
  20101. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  20102. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  20103. ;
  20104. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20105. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  20106. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20107. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  20108. };
  20109. GamepadCamera.prototype.dispose = function () {
  20110. this._gamepads.dispose();
  20111. _super.prototype.dispose.call(this);
  20112. };
  20113. return GamepadCamera;
  20114. })(BABYLON.FreeCamera);
  20115. BABYLON.GamepadCamera = GamepadCamera;
  20116. })(BABYLON || (BABYLON = {}));
  20117. var __extends = this.__extends || function (d, b) {
  20118. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20119. function __() { this.constructor = d; }
  20120. __.prototype = b.prototype;
  20121. d.prototype = new __();
  20122. };
  20123. var BABYLON;
  20124. (function (BABYLON) {
  20125. var LinesMesh = (function (_super) {
  20126. __extends(LinesMesh, _super);
  20127. function LinesMesh(name, scene, updatable) {
  20128. if (typeof updatable === "undefined") { updatable = false; }
  20129. _super.call(this, name, scene);
  20130. this.color = new BABYLON.Color3(1, 1, 1);
  20131. this.alpha = 1;
  20132. this._indices = new Array();
  20133. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  20134. attributes: ["position"],
  20135. uniforms: ["worldViewProjection", "color"],
  20136. needAlphaBlending: true
  20137. });
  20138. }
  20139. Object.defineProperty(LinesMesh.prototype, "material", {
  20140. get: function () {
  20141. return this._colorShader;
  20142. },
  20143. enumerable: true,
  20144. configurable: true
  20145. });
  20146. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  20147. get: function () {
  20148. return false;
  20149. },
  20150. enumerable: true,
  20151. configurable: true
  20152. });
  20153. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  20154. get: function () {
  20155. return false;
  20156. },
  20157. enumerable: true,
  20158. configurable: true
  20159. });
  20160. LinesMesh.prototype._bind = function (subMesh, effect, wireframe) {
  20161. var engine = this.getScene().getEngine();
  20162. var indexToBind = this._geometry.getIndexBuffer();
  20163. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  20164. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  20165. };
  20166. LinesMesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  20167. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20168. return;
  20169. }
  20170. var engine = this.getScene().getEngine();
  20171. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  20172. };
  20173. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  20174. return null;
  20175. };
  20176. LinesMesh.prototype.dispose = function (doNotRecurse) {
  20177. this._colorShader.dispose();
  20178. _super.prototype.dispose.call(this, doNotRecurse);
  20179. };
  20180. return LinesMesh;
  20181. })(BABYLON.Mesh);
  20182. BABYLON.LinesMesh = LinesMesh;
  20183. })(BABYLON || (BABYLON = {}));
  20184. var BABYLON;
  20185. (function (BABYLON) {
  20186. var OutlineRenderer = (function () {
  20187. function OutlineRenderer(scene) {
  20188. this._scene = scene;
  20189. }
  20190. OutlineRenderer.prototype.render = function (subMesh, batch) {
  20191. var scene = this._scene;
  20192. var engine = this._scene.getEngine();
  20193. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  20194. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  20195. return;
  20196. }
  20197. var mesh = subMesh.getRenderingMesh();
  20198. var material = subMesh.getMaterial();
  20199. engine.enableEffect(this._effect);
  20200. this._effect.setFloat("offset", mesh.outlineWidth);
  20201. this._effect.setColor3("color", mesh.outlineColor);
  20202. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  20203. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  20204. if (useBones) {
  20205. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  20206. }
  20207. mesh._bind(subMesh, this._effect, false);
  20208. if (material && material.needAlphaTesting()) {
  20209. var alphaTexture = material.getAlphaTestTexture();
  20210. this._effect.setTexture("diffuseSampler", alphaTexture);
  20211. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  20212. }
  20213. if (hardwareInstancedRendering) {
  20214. mesh._renderWithInstances(subMesh, false, batch, this._effect, engine);
  20215. } else {
  20216. if (batch.renderSelf[subMesh._id]) {
  20217. this._effect.setMatrix("world", mesh.getWorldMatrix());
  20218. mesh._draw(subMesh, true);
  20219. }
  20220. if (batch.visibleInstances[subMesh._id]) {
  20221. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20222. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20223. this._effect.setMatrix("world", instance.getWorldMatrix());
  20224. mesh._draw(subMesh, true);
  20225. }
  20226. }
  20227. }
  20228. };
  20229. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  20230. var defines = [];
  20231. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  20232. var mesh = subMesh.getMesh();
  20233. var material = subMesh.getMaterial();
  20234. if (material && material.needAlphaTesting()) {
  20235. defines.push("#define ALPHATEST");
  20236. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20237. attribs.push(BABYLON.VertexBuffer.UVKind);
  20238. defines.push("#define UV1");
  20239. }
  20240. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20241. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  20242. defines.push("#define UV2");
  20243. }
  20244. }
  20245. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20246. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20247. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20248. defines.push("#define BONES");
  20249. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  20250. }
  20251. if (useInstances) {
  20252. defines.push("#define INSTANCES");
  20253. attribs.push("world0");
  20254. attribs.push("world1");
  20255. attribs.push("world2");
  20256. attribs.push("world3");
  20257. }
  20258. var join = defines.join("\n");
  20259. if (this._cachedDefines != join) {
  20260. this._cachedDefines = join;
  20261. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  20262. }
  20263. return this._effect.isReady();
  20264. };
  20265. return OutlineRenderer;
  20266. })();
  20267. BABYLON.OutlineRenderer = OutlineRenderer;
  20268. })(BABYLON || (BABYLON = {}));
  20269. var BABYLON;
  20270. (function (BABYLON) {
  20271. var MeshAssetTask = (function () {
  20272. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  20273. this.name = name;
  20274. this.meshesNames = meshesNames;
  20275. this.rootUrl = rootUrl;
  20276. this.sceneFilename = sceneFilename;
  20277. this.isCompleted = false;
  20278. }
  20279. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20280. var _this = this;
  20281. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  20282. _this.loadedMeshes = meshes;
  20283. _this.loadedParticleSystems = particleSystems;
  20284. _this.loadedSkeletons = skeletons;
  20285. _this.isCompleted = true;
  20286. if (_this.onSuccess) {
  20287. _this.onSuccess(_this);
  20288. }
  20289. onSuccess();
  20290. }, null, function () {
  20291. if (_this.onError) {
  20292. _this.onError(_this);
  20293. }
  20294. onError();
  20295. });
  20296. };
  20297. return MeshAssetTask;
  20298. })();
  20299. BABYLON.MeshAssetTask = MeshAssetTask;
  20300. var TextFileAssetTask = (function () {
  20301. function TextFileAssetTask(name, url) {
  20302. this.name = name;
  20303. this.url = url;
  20304. this.isCompleted = false;
  20305. }
  20306. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20307. var _this = this;
  20308. BABYLON.Tools.LoadFile(this.url, function (data) {
  20309. _this.text = data;
  20310. _this.isCompleted = true;
  20311. if (_this.onSuccess) {
  20312. _this.onSuccess(_this);
  20313. }
  20314. onSuccess();
  20315. }, null, scene.database, false, function () {
  20316. if (_this.onError) {
  20317. _this.onError(_this);
  20318. }
  20319. onError();
  20320. });
  20321. };
  20322. return TextFileAssetTask;
  20323. })();
  20324. BABYLON.TextFileAssetTask = TextFileAssetTask;
  20325. var BinaryFileAssetTask = (function () {
  20326. function BinaryFileAssetTask(name, url) {
  20327. this.name = name;
  20328. this.url = url;
  20329. this.isCompleted = false;
  20330. }
  20331. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20332. var _this = this;
  20333. BABYLON.Tools.LoadFile(this.url, function (data) {
  20334. _this.data = data;
  20335. _this.isCompleted = true;
  20336. if (_this.onSuccess) {
  20337. _this.onSuccess(_this);
  20338. }
  20339. onSuccess();
  20340. }, null, scene.database, true, function () {
  20341. if (_this.onError) {
  20342. _this.onError(_this);
  20343. }
  20344. onError();
  20345. });
  20346. };
  20347. return BinaryFileAssetTask;
  20348. })();
  20349. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  20350. var ImageAssetTask = (function () {
  20351. function ImageAssetTask(name, url) {
  20352. this.name = name;
  20353. this.url = url;
  20354. this.isCompleted = false;
  20355. }
  20356. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20357. var _this = this;
  20358. var img = new Image();
  20359. img.onload = function () {
  20360. _this.image = img;
  20361. _this.isCompleted = true;
  20362. if (_this.onSuccess) {
  20363. _this.onSuccess(_this);
  20364. }
  20365. onSuccess();
  20366. };
  20367. img.onerror = function () {
  20368. if (_this.onError) {
  20369. _this.onError(_this);
  20370. }
  20371. onError();
  20372. };
  20373. img.src = this.url;
  20374. };
  20375. return ImageAssetTask;
  20376. })();
  20377. BABYLON.ImageAssetTask = ImageAssetTask;
  20378. var TextureAssetTask = (function () {
  20379. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  20380. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20381. this.name = name;
  20382. this.url = url;
  20383. this.noMipmap = noMipmap;
  20384. this.invertY = invertY;
  20385. this.samplingMode = samplingMode;
  20386. this.isCompleted = false;
  20387. }
  20388. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20389. var _this = this;
  20390. var onload = function () {
  20391. _this.isCompleted = true;
  20392. if (_this.onSuccess) {
  20393. _this.onSuccess(_this);
  20394. }
  20395. onSuccess();
  20396. };
  20397. var onerror = function () {
  20398. if (_this.onError) {
  20399. _this.onError(_this);
  20400. }
  20401. onError();
  20402. };
  20403. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  20404. };
  20405. return TextureAssetTask;
  20406. })();
  20407. BABYLON.TextureAssetTask = TextureAssetTask;
  20408. var AssetsManager = (function () {
  20409. function AssetsManager(scene) {
  20410. this._tasks = new Array();
  20411. this._waitingTasksCount = 0;
  20412. this.useDefaultLoadingScreen = true;
  20413. this._scene = scene;
  20414. }
  20415. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  20416. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  20417. this._tasks.push(task);
  20418. return task;
  20419. };
  20420. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  20421. var task = new TextFileAssetTask(taskName, url);
  20422. this._tasks.push(task);
  20423. return task;
  20424. };
  20425. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  20426. var task = new BinaryFileAssetTask(taskName, url);
  20427. this._tasks.push(task);
  20428. return task;
  20429. };
  20430. AssetsManager.prototype.addImageTask = function (taskName, url) {
  20431. var task = new ImageAssetTask(taskName, url);
  20432. this._tasks.push(task);
  20433. return task;
  20434. };
  20435. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  20436. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20437. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  20438. this._tasks.push(task);
  20439. return task;
  20440. };
  20441. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  20442. this._waitingTasksCount--;
  20443. if (this._waitingTasksCount === 0) {
  20444. if (this.onFinish) {
  20445. this.onFinish(this._tasks);
  20446. }
  20447. this._scene.getEngine().hideLoadingUI();
  20448. }
  20449. };
  20450. AssetsManager.prototype._runTask = function (task) {
  20451. var _this = this;
  20452. task.run(this._scene, function () {
  20453. if (_this.onTaskSuccess) {
  20454. _this.onTaskSuccess(task);
  20455. }
  20456. _this._decreaseWaitingTasksCount();
  20457. }, function () {
  20458. if (_this.onTaskError) {
  20459. _this.onTaskError(task);
  20460. }
  20461. _this._decreaseWaitingTasksCount();
  20462. });
  20463. };
  20464. AssetsManager.prototype.reset = function () {
  20465. this._tasks = new Array();
  20466. return this;
  20467. };
  20468. AssetsManager.prototype.load = function () {
  20469. this._waitingTasksCount = this._tasks.length;
  20470. if (this._waitingTasksCount === 0) {
  20471. if (this.onFinish) {
  20472. this.onFinish(this._tasks);
  20473. }
  20474. return this;
  20475. }
  20476. if (this.useDefaultLoadingScreen) {
  20477. this._scene.getEngine().displayLoadingUI();
  20478. }
  20479. for (var index = 0; index < this._tasks.length; index++) {
  20480. var task = this._tasks[index];
  20481. this._runTask(task);
  20482. }
  20483. return this;
  20484. };
  20485. return AssetsManager;
  20486. })();
  20487. BABYLON.AssetsManager = AssetsManager;
  20488. })(BABYLON || (BABYLON = {}));
  20489. var __extends = this.__extends || function (d, b) {
  20490. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20491. function __() { this.constructor = d; }
  20492. __.prototype = b.prototype;
  20493. d.prototype = new __();
  20494. };
  20495. var BABYLON;
  20496. (function (BABYLON) {
  20497. var VRDeviceOrientationCamera = (function (_super) {
  20498. __extends(VRDeviceOrientationCamera, _super);
  20499. function VRDeviceOrientationCamera(name, position, scene) {
  20500. _super.call(this, name, position, scene);
  20501. this._alpha = 0;
  20502. this._beta = 0;
  20503. this._gamma = 0;
  20504. }
  20505. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  20506. this._alpha = +evt.alpha | 0;
  20507. this._beta = +evt.beta | 0;
  20508. this._gamma = +evt.gamma | 0;
  20509. if (this._gamma < 0) {
  20510. this._gamma = 90 + this._gamma;
  20511. } else {
  20512. this._gamma = 270 - this._gamma;
  20513. }
  20514. this.rotation.x = this._gamma / 180.0 * Math.PI;
  20515. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  20516. this.rotation.z = this._beta / 180.0 * Math.PI;
  20517. };
  20518. return VRDeviceOrientationCamera;
  20519. })(BABYLON.OculusCamera);
  20520. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  20521. })(BABYLON || (BABYLON = {}));
  20522. var __extends = this.__extends || function (d, b) {
  20523. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20524. function __() { this.constructor = d; }
  20525. __.prototype = b.prototype;
  20526. d.prototype = new __();
  20527. };
  20528. var BABYLON;
  20529. (function (BABYLON) {
  20530. var WebVRCamera = (function (_super) {
  20531. __extends(WebVRCamera, _super);
  20532. function WebVRCamera(name, position, scene) {
  20533. _super.call(this, name, position, scene);
  20534. this._hmdDevice = null;
  20535. this._sensorDevice = null;
  20536. this._cacheState = null;
  20537. this._cacheQuaternion = new BABYLON.Quaternion();
  20538. this._cacheRotation = BABYLON.Vector3.Zero();
  20539. this._vrEnabled = false;
  20540. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  20541. }
  20542. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  20543. var size = devices.length;
  20544. var i = 0;
  20545. this._sensorDevice = null;
  20546. this._hmdDevice = null;
  20547. while (i < size && this._hmdDevice === null) {
  20548. if (devices[i] instanceof HMDVRDevice) {
  20549. this._hmdDevice = devices[i];
  20550. }
  20551. i++;
  20552. }
  20553. i = 0;
  20554. while (i < size && this._sensorDevice === null) {
  20555. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  20556. this._sensorDevice = devices[i];
  20557. }
  20558. i++;
  20559. }
  20560. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  20561. };
  20562. WebVRCamera.prototype._update = function () {
  20563. if (this._vrEnabled) {
  20564. this._cacheState = this._sensorDevice.getState();
  20565. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  20566. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  20567. this.rotation.x = -this._cacheRotation.z;
  20568. this.rotation.y = -this._cacheRotation.y;
  20569. this.rotation.z = this._cacheRotation.x;
  20570. }
  20571. _super.prototype._update.call(this);
  20572. };
  20573. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  20574. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20575. if (navigator.getVRDevices) {
  20576. navigator.getVRDevices().then(this._getWebVRDevices);
  20577. } else if (navigator.mozGetVRDevices) {
  20578. navigator.mozGetVRDevices(this._getWebVRDevices);
  20579. }
  20580. };
  20581. WebVRCamera.prototype.detachControl = function (element) {
  20582. _super.prototype.detachControl.call(this, element);
  20583. this._vrEnabled = false;
  20584. };
  20585. return WebVRCamera;
  20586. })(BABYLON.OculusCamera);
  20587. BABYLON.WebVRCamera = WebVRCamera;
  20588. })(BABYLON || (BABYLON = {}));